Namespace lsst

namespace lsst

Remove all non-astronomical counts from the Chunk Exposure’s pixels.

Class for a simple mapping implementing a generic AstrometryTransform.

It uses a template rather than a pointer so that the derived classes can use the specifics of the transform. The class simplePolyMapping overloads a few routines.

Forward declarations for lsst::utils::Cache

For details on the Cache class, see the Cache.h file.

A base class for image defects

Numeric constants used by the Integrate.h integrator routines.

Compute Image Statistics

Note

Gauss-Kronrod-Patterson quadrature coefficients for use in quadpack routine qng. These coefficients were calculated with 101 decimal digit arithmetic by L. W. Fullerton, Bell Labs, Nov 1981.

Note

The Statistics class itself can only handle lsst::afw::image::MaskedImage() types. The philosophy has been to handle other types by making them look like lsst::afw::image::MaskedImage() and reusing that code. Users should have no need to instantiate a Statistics object directly, but should use the overloaded makeStatistics() factory functions.

namespace afw
namespace cameraGeom

Enums

enum ReadoutCorner

Readout corner, in the frame of reference of the assembled image

Values:

LL
LR
UR
UL
enum AssemblyState

Assembly state of the amplifier, used to identify bounding boxes and component existence.

Values:

RAW
SCIENCE
enum DetectorType

Type of imaging detector

Values:

SCIENCE
FOCUS
GUIDER
WAVEFRONT

Functions

void swap(CameraSys &a, CameraSys &b)
std::ostream &operator<<(std::ostream &os, CameraSysPrefix const &detSysPrefix)
std::ostream &operator<<(std::ostream &os, CameraSys const &cameraSys)
std::ostream &operator<<(std::ostream &os, TransformMap::Connection const &connection)

Variables

CameraSys const FOCAL_PLANE

Focal plane coordinates: Position on a 2-d planar approximation to the focal plane (x,y mm).

The origin and orientation may be defined by the camera team, but we strongly recommend that the origin be on the optical axis and (if using CCD detectors) that the X axis be aligned along CCD rows.

Note

Location and orientation of detectors are defined in a 3-d version of FOCAL_PLANE coordinates (the z axis is also relevant). Rectilinear x, y (and z when talking about the location of a detector) on the camera focal plane (mm). For z=0 choose a convenient point near the focus at x, y = 0.

CameraSys const FIELD_ANGLE

Field angle coordinates: Angle of a principal ray relative to the optical axis (x,y radians).

The orientation of the x,y axes is the same as FOCAL_PLANE.

CameraSysPrefix const PIXELS

Pixel coordinates: Nominal position on the entry surface of a given detector (x, y unbinned pixels).

For CCD detectors the x axis must be along rows (the direction of the serial register). This is required for our interpolation algorithm to interpolate across bad columns.

This ignores manufacturing imperfections, “tree ring” distortions and all other such effects. It is a uniform grid of rectangular (usually square) pixels.

Warning

This is a detector prefix; call Detector.makeCameraSys(PIXELS) to make a full CameraSys.

CameraSysPrefix const TAN_PIXELS

Tangent-plane pixels on the detector (x, y unbinned pixels)

Converting from PIXELS to TAN_PIXELS has the effect of removing optical distortion (and the distortion due to rectangular pixels) with the point at the center of the detector being unaffected by the transformation.

In detail, PIXELS->TAN_PIXELS is PIXELS->FIELD_ANGLE plus an affine transformation, such that:

  • The x,y axes are parallel to the detector axes

  • The dimensions are nominal pixels at the center of the focal plane (where nominal pixels size is mean of x, y pixel size).

  • The point at the center of the detector has the same value in PIXELS and TAN_PIXELS

This is a detector prefix; call Detector.makeCameraSys(TAN_PIXELS) to make a full CameraSys.

CameraSysPrefix const ACTUAL_PIXELS

The actual pixels where the photon lands and electrons are generated (x,y unbinned) This takes into account manufacturing defects, “tree ring” distortions and other such effects.

This is a detector prefix; call Detector.makeCameraSys(ACTUAL_PIXELS) to make a full CameraSys.

class Amplifier
#include <Amplifier.h>

Geometry and electronic information about raw amplifier images

The Amplifier class itself is an abstract base class that provides no mutation or copy interfaces. Typically Amplifiers are constructed via the Builder subclass, which can produce a shared_ptr to an immutable Amplifier instance.

Here is a pictorial example showing the meaning of flipX and flipY:

    CCD with 4 amps        Desired assembled output      Use these parameters

    --x         x--            y
   |  amp1    amp2 |           |                               flipX       flipY
   y               y           |                       amp1    False       True
                               | CCD image             amp2    True        True
   y               y           |                       amp3    False       False
   |  amp3    amp4 |           |                       amp4    True        False
    --x         x--             ----------- x
Note

  • All bounding boxes are parent boxes with respect to the raw image.

  • The overscan and prescan bounding boxes represent the full regions; unusable regions are set via ISR configuration parameters.

  • xyOffset is not used for instrument signature removal (ISR); it is intended for use by display utilities. It supports construction of a raw CCD image in the case that raw data is provided as individual amplifier images (which is uncommon):

    • Use 0,0 for cameras that supply raw data as a raw CCD image (most cameras)

    • Use nonzero for cameras that supply raw data as separate amplifier images with xy0=0,0 (LSST)

  • This design assumes assembled X is always +/- raw X, which we require for CCDs (so that bleed trails are always along the Y axis).

Subclassed by lsst::afw::cameraGeom::Amplifier::Builder

class Camera : public lsst::afw::cameraGeom::DetectorCollection, public lsst::afw::table::io::PersistableFacade<Camera>
#include <Camera.h>

An immutable representation of a camera.

Cameras are created (and modified, when necessary) via the Camera::Builder helper class.

class CameraSys
#include <CameraSys.h>

Camera coordinate system; used as a key in in TransformMap

class CameraSysPrefix
#include <CameraSys.h>

Camera coordinate system prefix

Used for coordinate systems that are detector-based before the detector name is known (e.g. for constants such as PIXELS).

This is Jim Bosch’s clever idea for simplifying Detector.convert; CameraSys is always complete and CameraSysPrefix is not.

class Detector : public lsst::afw::cameraGeom::DetectorBase, public lsst::afw::table::io::PersistableFacade<Detector>, public Storable
#include <Detector.h>

A representation of a detector in a mosaic camera.

Detector holds both simple data fields (see DetectorBase) and a set of related coordinate systems and transforms, and acts as a container of Amplifier objects.

Detector is immutable, but copies can be modified via one of its Builder classes. A Detector must be created initially as part of a Camera (see Camera::Builder::add), but can then be modified either individually (see Detector::rebuild and Detector::PartialRebuilder) or as part of modifying the full Camera (see Detector::InCameraBuilder).

The coordinate systems and transforms known to a Detector are shared with its parent Camera and all other Detectors in that Camera.

class DetectorBase
#include <Detector.h>

An abstract base class that provides common accessors for Detector and Detector::Builder.

Subclassed by lsst::afw::cameraGeom::Detector, lsst::afw::cameraGeom::Detector::Builder

class DetectorCollection : public lsst::afw::cameraGeom::DetectorCollectionBase<Detector const>, public lsst::afw::table::io::PersistableFacade<DetectorCollection>, public lsst::afw::table::io::Persistable
#include <DetectorCollection.h>

An immutable collection of Detectors that can be accessed by name or ID

Subclassed by lsst::afw::cameraGeom::Camera

template<typename T>
class DetectorCollectionBase
#include <DetectorCollection.h>

An abstract base class for collections of Detectors and specific subclasses thereof.

This class provides the common interface and implementation for

DetectorCollection (which holds true Detector instances) and Camera::Builder (which holds Detector::InCameraBuilder instances). It is not intended to define an interface independent of those classes.
Template Parameters
  • T: Element type; either Detector or a subclass thereof.

class Orientation
#include <Orientation.h>

Describe a detector’s orientation in the focal plane

All rotations are about the reference point on the detector. Rotations are intrinsic, meaning each rotation is applied in the coordinates system produced by the previous rotation. Rotations are applied in this order: yaw (Z), pitch (Y’), and roll (X’’).

Warning

: default refPoint is -0.5, -0.5 (the lower left corner of a detector). This means that the default-constructed Orientation is not a unity transform, but instead includes a 1/2 pixel shift.

class TransformMap : public lsst::afw::table::io::PersistableFacade<TransformMap>, public lsst::afw::table::io::Persistable
#include <TransformMap.h>

A registry of 2-dimensional coordinate transforms for a specific camera.

Represents the interrelationships between camera coordinate systems for a particular camera. It can be seen as a mapping between a pair of CameraSys and a Transform between them (though it does not conform to either the C++ map or Python dictionary APIs).

TransformMap supports:

  • Transforming between any two supported CameraSys using the transform methods.

  • Retrieving a transform between any two supported CameraSys using getTransform.

  • Iteration over supported CameraSys using begin and end in C++ and standard Python iteration in Python.

TransformMap is immutable and must always be held by shared_ptr; this is enforced by making all non-deleted constructors private, and instead providing static make member functions for construction (in Python, these are exposed as regular constructors).

Unless otherwise specified, all methods guarantee only basic exception safety.

namespace coord

Functions

std::ostream &operator<<(std::ostream &os, Observatory const &obs)

Print an Observatory to the stream

Parameters
  • [inout] os: Stream to print to

  • [in] obs: the Observatory to print

std::ostream &operator<<(std::ostream &os, Weather const &weath)

print a Weather to an output stream

class Observatory
#include <Observatory.h>

Hold the location of an observatory

class Weather
#include <Weather.h>

Basic weather information sufficient for a simple model for air mass or refraction

Weather is immutable.

namespace detection

Typedefs

typedef std::uint64_t FootprintIdPixel

Pixel type for FootprintSet::insertIntoImage()

This is independent of the template parameters for FootprintSet, and including it within FootprintSet makes it difficult for SWIG to interpret the type.

typedef afw::table::ColumnViewT<PeakRecord> PeakColumnView
typedef afw::table::CatalogT<PeakRecord> PeakCatalog
typedef afw::table::CatalogT<PeakRecord const> ConstPeakCatalog

Functions

std::shared_ptr<Footprint> mergeFootprints(Footprint const &footprint1, Footprint const &footprint2)

Merges two Footprints appends their peaks, and unions their spans, returning a new Footprint. Region is not preserved, and is set to an empty lsst::geom::Box2I object.

std::vector<lsst::geom::Box2I> footprintToBBoxList(Footprint const &footprint)

Return a list of BBoxs, whose union contains exactly the pixels in the footprint, neither more nor less.

Useful in generating sets of meas::algorithms::Defects for the ISR

Parameters
  • footprint: Footprint to turn into bounding box list

template<typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT> makeHeavyFootprint(Footprint const &foot, lsst::afw::image::MaskedImage<ImagePixelT, MaskPixelT, VariancePixelT> const &img, HeavyFootprintCtrl const *ctrl = NULL)

Create a HeavyFootprint with footprint defined by the given Footprint and pixel values from the given MaskedImage.

template<typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
std::shared_ptr<HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT>> mergeHeavyFootprints(HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT> const &h1, HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT> const &h2)

Sum the two given HeavyFootprints h1 and h2, returning a HeavyFootprint with the union footprint, and summed pixels where they overlap. The peak list is the union of the two inputs.

std::ostream &operator<<(std::ostream &os, PeakRecord const &record)
Threshold createThreshold(const double value, const std::string type = "value", const bool polarity = true)

Factory method for creating Threshold objects

Return

desired Threshold

Parameters
  • value: value of threshold

  • type: string representation of a ThresholdType. This parameter is optional. Allowed values are: “variance”, “value”, “stdev”, “pixel_stdev”

  • polarity: If true detect positive objects, false for negative

class Footprint : public lsst::afw::table::io::PersistableFacade<lsst::afw::detection::Footprint>, public lsst::afw::table::io::Persistable
#include <Footprint.h>

Class to describe the properties of a detected object from an image

A Footprint is designed to be constructed with information about a detected object in an image. Internally a Footprint holds a SpanSet which is used to describe the location of the object in the image (the x, y pixel locations which are considered part of the object). In addition a Footprint contains a PeakCatalog which is used to store the location and intensity of peaks in the detection.

Subclassed by lsst::afw::detection::HeavyFootprint< ImagePixelT, MaskPixelT, VariancePixelT >

class FootprintControl
#include <FootprintCtrl.h>

A Control Object for Footprints, controlling e.g. how they are grown

class FootprintMergeList
#include <FootprintMerge.h>

List of Merged Footprints.

Stores a vector of FootprintMerges and SourceRecords that contain the union of different footprints and which filters it was detected in. Individual Footprints from a SourceCatalog can be added to the vector (note that any SourceRecords with parent!=0 will be skipped). If a Footprint overlaps an existing FootprintMerge, the Footprint will be added to it. If not, then a new FootprintMerge will be created and added to the vector.

The search algorithm uses a brute force approach over the current list. This should be fine if we are operating on smallish number of objects, such as at the tract level.

class FootprintSet
#include <FootprintSet.h>

A set of Footprints, associated with a MaskedImage

class GaussianPsf : public lsst::afw::table::io::PersistableFacade<GaussianPsf>, public lsst::afw::detection::Psf
#include <GaussianPsf.h>

A circularly symmetric Gaussian Psf class with no spatial variation, intended mostly for testing purposes.

This class is essentially an alternate implementation of meas::algorithms::SingleGaussianPsf; While SingleGaussianPsf inherits from ImagePsf and KernelPsf, and hence delegates to those various operations relating to the PSF model image (e.g. computeShape()), GaussianPsf computes these analytically.

template<typename ImagePixelT, typename MaskPixelT = lsst::afw::image::MaskPixel, typename VariancePixelT = lsst::afw::image::VariancePixel>
class HeavyFootprint : public lsst::afw::table::io::PersistableFacade<HeavyFootprint<ImagePixelT, MaskPixelT, VariancePixelT>>, public lsst::afw::detection::Footprint
#include <HeavyFootprint.h>

A set of pixels in an Image, including those pixels’ actual values

class HeavyFootprintCtrl
#include <FootprintCtrl.h>

A control object for HeavyFootprints

class PeakRecord : public lsst::afw::table::BaseRecord
#include <Peak.h>

Record class that represents a peak in a Footprint

class PeakTable : public lsst::afw::table::BaseTable
#include <Peak.h>

Table class for Peaks in Footprints.

class Psf : public lsst::afw::table::io::PersistableFacade<Psf>, public Storable
#include <Psf.h>

A polymorphic base class for representing an image’s Point Spread Function

Most of a Psf’s functionality involves its evaluation at a position and color, either or both of which may be unspecified (which will result in evaluation at some average position or color). Unlike the closely-related Kernel class, there is no requirement that a Psf have a well-defined spatial function or any parameters. Psfs are not necessarily continuous, and the dimensions of image of the Psf at a point may not be fixed.

Psfs have two methods for getting at image at a point:

  • the image returned by computeImage() is in the same coordinate system as the pixelized image

  • the image returned by computeKernelImage() is in an offset coordinate system with the point P at (0,0); this implies that the image (x0,y0) will be negative

Because P does not need to have integer coordinates, these two images are fractionally offset from each other and we use interpolation to get (1) from (2).

Psfs are immutable - derived classes should have no non-const methods, and hence should be fully-defined after construction. This allows shared_ptrs to Psfs to be passed around and shared between objects without concern for whether they will be unexpectedly modified.

In most cases, Psf derived classes should inherit from meas::algorithms::ImagePsf or meas::algorithms::KernelPsf, as these will provide default implementions for several member functions.

Subclassed by lsst::afw::detection::GaussianPsf, lsst::meas::algorithms::ImagePsf

class Threshold
#include <Threshold.h>

A Threshold is used to pass a threshold value to detection algorithms

The threshold may be a simple value (type == VALUE), or in units of the image standard deviation. Alternatively you may specify that you’ll provide the standard deviation (type == STDEV) or variance (type == VARIANCE)

Note that the constructor is not declared explicit, so you may pass a bare threshold, and it’ll be interpreted as a VALUE.

namespace fits

Functions

LSST_EXCEPTION_TYPE(FitsError, lsst::pex::exceptions::IoError, lsst::afw::fits::FitsError)

An exception thrown when problems are found when reading or writing FITS files. An exception thrown when a FITS file has the wrong type.

std::string makeErrorMessage(std::string const &fileName = "", int status = 0, std::string const &msg = "")

Return an error message reflecting FITS I/O errors.

Parameters
  • [in] fileName: FITS filename to be included in the error message.

  • [in] status: The last status value returned by the cfitsio library; if nonzero, the error message will include a description from cfitsio.

  • [in] msg: An additional custom message to include.

std::string makeErrorMessage(std::string const &fileName, int status, boost::format const &msg)
std::string makeErrorMessage(void *fptr, int status = 0, std::string const &msg = "")

Return an error message reflecting FITS I/O errors.

Parameters
  • [in] fptr: A cfitsio fitsfile pointer to be inspected for a filename. Passed as void* to avoid including fitsio.h in the header file.

  • [in] status: The last status value returned by the cfitsio library; if nonzero, the error message will include a description from cfitsio.

  • [in] msg: An additional custom message to include.

std::string makeErrorMessage(void *fptr, int status, boost::format const &msg)
std::string makeLimitedFitsHeader(lsst::daf::base::PropertySet const &metadata, std::set<std::string> const &excludeNames = {})

Format a PropertySet into an FITS header string in a simplistic fashion.

This function is designed to format data for creating a WCS. As such, it is quite limited:

  • It skips entries whose name is longer than 8 characters, since none are used for FITS-WCS

  • It skips string entries if the fully formatted string is longer than 80 characters

  • It skips entries with types it cannot handle (e.g. long, long long)

  • For entries that have array data, it only writes the final value, since that is the value that should be used by code that reads FITS headers.

  • It makes no attempt to insure that required entries, such as SIMPLE, are present.

Return

a FITS header string (exactly 80 characters per entry, no line terminators)

Parameters
  • [in] metadata: Metadata to format; if this is a PropertyList then the order of items is preserved

  • [in] excludeNames: Names of entries to exclude from the returned header string

template<typename T>
int getBitPix()

Return the cfitsio integer BITPIX code for the given data type.

template<typename T, int N, int C>
ndarray::Array<T const, N, N> const makeContiguousArray(ndarray::Array<T, N, C> const &array)

Construct a contiguous ndarray

A deep copy is only performed if the array is not already contiguous.

std::shared_ptr<daf::base::PropertyList> combineMetadata(std::shared_ptr<const daf::base::PropertyList> first, std::shared_ptr<const daf::base::PropertyList> second)

Combine two sets of metadata in a FITS-appropriate fashion

“COMMENT” and “HISTORY” entries:

  • If of type std::string then the values in second are appended to values in first

  • If not of type std::string then they are silently ignored

All other entries:

  • Values in second override values in first (regardless of type)

  • Only scalars are copied; if a vector is found, only the last value is copied

Return

The combined metadata. Item names have the following order:

  • names in first, omitting all names except “COMMENT” and “HISTORY” that appear in second

  • names in second, omitting “COMMENT” and “HISTORY” if valid versions appear in first

Parameters
  • [in] first: The first set of metadata to combine

  • [in] second: The second set of metadata to combine

std::shared_ptr<daf::base::PropertyList> readMetadata(std::string const &fileName, int hdu = DEFAULT_HDU, bool strip = false)

Read FITS header

Includes support for the INHERIT convention: if ‘INHERIT = T’ is in the header, the PHU will be read as well, and nominated HDU will override any duplicated values.

Return the metadata (header entries) from a FITS file.

Parameters
  • fileName: the file whose header will be read

  • hdu: the HDU to read (0-indexed; 0 is the Primary HDU).

  • strip: if true, common FITS keys that usually have non-metadata intepretations (e.g. NAXIS, BITPIX) will be ignored.

Parameters
  • [in] fileName: File to read.

  • [in] hdu: HDU to read, 0-indexed. The special value of afw::fits::DEFAULT_HDU will read the first non-empty HDU.

  • [in] strip: If true, ignore special header keys usually managed by cfitsio (e.g. NAXIS).

std::shared_ptr<daf::base::PropertyList> readMetadata(fits::MemFileManager &manager, int hdu = DEFAULT_HDU, bool strip = false)

Read FITS header

Includes support for the INHERIT convention: if ‘INHERIT = T’ is in the header, the PHU will be read as well, and nominated HDU will override any duplicated values.

Parameters
  • manager: the in-memory file whose header will be read

  • hdu: the HDU to read (0-indexed; 0 is the Primary HDU).

  • strip: if true, common FITS keys that usually have non-metadata intepretations (e.g. NAXIS, BITPIX) will be ignored.

std::shared_ptr<daf::base::PropertyList> readMetadata(fits::Fits &fitsfile, bool strip = false)

Read FITS header

Includes support for the INHERIT convention: if ‘INHERIT = T’ is in the header, the PHU will be read as well, and nominated HDU will override any duplicated values.

Parameters
  • fitsfile: the file and HDU to be read

  • strip: if true, common FITS keys that usually have non-metadata intepretations (e.g. NAXIS, BITPIX) will be ignored.

void setAllowImageCompression(bool allow)
bool getAllowImageCompression()
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromString(std::string const &name)

Interpret compression algorithm expressed in string.

std::string compressionAlgorithmToString(ImageCompressionOptions::CompressionAlgorithm algorithm)

Provide string version of compression algorithm.

ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromCfitsio(int cfitsio)

Convert compression algorithm from cfitsio to ImageCompressionOptions::CompressionAlgorithm.

int compressionAlgorithmToCfitsio(ImageCompressionOptions::CompressionAlgorithm algorithm)

Convert ImageCompressionOptions::CompressionAlgorithm to cfitsio.

ImageScalingOptions::ScalingAlgorithm scalingAlgorithmFromString(std::string const &name)

Interpret scaling algorithm expressed in string.

std::string scalingAlgorithmToString(ImageScalingOptions::ScalingAlgorithm algorithm)

Provide string version of compression algorithm.

Variables

const int DEFAULT_HDU = INT_MIN

Specify that the default HDU should be read.

This special HDU number indicates that the first extension should be used if the primary HDU is empty (i.e., has NAXIS=0) and the Primary HDU is the current.

class Fits
#include <fits.h>

A simple struct that combines the two arguments that must be passed to most cfitsio routines and contains thin and/or templated wrappers around common cfitsio routines.

This is NOT intended to be an object-oriented C++ wrapper around cfitsio; it’s simply a thin layer that saves a lot of repetition, const/reinterpret casts, and replaces void pointer args and type codes with templates and overloads.

Like a cfitsio pointer, a Fits object always considers one HDU the “active” one, and most operations will be applied to that HDU.

All member functions are non-const because they may modify the ‘status’ data member.

Note

All functions that take a row or column number below are 0-indexed; the internal cfitsio calls are all 1-indexed.

class HduMoveGuard
#include <fits.h>

RAII scoped guard for moving the HDU in a Fits object.

This class attempts to ensure that the HDU state of a Fits object is restored when the guard class goes out of scope, even in the presence of exceptions. (In practice, resetting the HDU can only fail if the Fits object has become sufficiently corrupted that it’s no longer usable at all).

class HeaderIterationFunctor
#include <fits.h>

Base class for polymorphic functors used to iterator over FITS key headers.

Subclass this, and then pass an instance to Fits::forEachKey to iterate over all the keys in a header.

struct ImageCompressionOptions
#include <fitsCompression.h>

Options for tile compression of image pixels

Tile compression is a feature provided by cfitsio, where contiguous parts of the image (“tiles”, e.g., rows, multiple rows, blocks or the entire image) are compressed separately. The aim of this struct is to hold the parameters used to configure the compression.

Floating-point images can be losslessly compressed (quantizeLevel=0.0) using (only) the GZIP or GZIP_SHUFFLE compression algorithms, but the compression factor so achieved is modest (e.g., ~ 10% compression). Better compression factors can be achieved if floating-point images are first quantised into integer images. This can be done by cfitsio (through the quantizeLevel parameter) or through use of the ImageScalingOptions.

The Compression is specified by:

  • the compression algorithm

  • the tile size

  • the quantization level (for quantization applied by cfitsio; for floating-point images)

Due to bugs, cfitsio may require setting the quantizeLevel to a value other than zero when compressing integer data, but in this case it should have no effect.

struct ImageScale
#include <fitsCompression.h>

Scale to apply to image

Images are scaled to the type implied by the provided BITPIX using the provided scale and zero-point:

value in memory = BZERO + BSCALE * value in FITS

In addition to scaling, a random field of values distributed [0,1) may be added before quantisation (“fuzz”); this preserves the expectation value of the floating-point image, while increasing the variance by 1/12.

class ImageScalingOptions
#include <fitsCompression.h>

Options for scaling image pixels

Scaling (quantisation) of floating-point images is important in order to achieve respectable compression factors. Unfortunately, scaling a floating-point image means losing some information, in two ways: values are quantised so values in between the quanta will be rounded up or down; and values outside the range of supported values in the integer image will be clipped. This implementation is based on the successful implementation used by Pan-STARRS.

cfitsio provides a facility for scaling image pixels on write (see ImageCompressionOptions.quantizeLevel), but that facility is limited (it provides a single scaling option, and doesn’t use our masks when collecting statistics). This scaling facility provides multiple scaling options, and could be extended to support more in the future (e.g., logarithmic or asinh scaling).

Scaling is specified by:

  • the scaling algorithm: the algorithm used to determining the scales (and therefore the dynamic range).

  • the bits per pixel: 8,16,32,64,-32,-64 (negative means floating-point but you probably don’t want to use those here); larger values give more dynamic range, produce larger images (which effect may be negated by compression).

  • fuzz: whether to add a random field of values distributed [0,1) before quantisation; this preserves the expectation value of the floating-point image, while increasing the variance by 1/12.

  • seed: seed for the random number generator used by the fuzz.

  • maskPlanes: a list of mask planes to be ignored when doing statistics.

  • quantizeLevel: for the STDEV_* algorithms, specifies the ratio of the quantum size to the image standard deviation.

  • quantizePad: for the STDEV_POSITIVE and STDEV_NEGATIVE algorithms, specifies how many standard deviations to allow on the short side.

  • bscale, bzero: for the MANUAL algorithm, specifies the BSCALE and BZERO to use.

Scaling algorithms are:

  • NONE: no scaling or quantisation at all. The image goes out the way it came in.

  • RANGE: scale based on the dynamic range in the image. This preserves dynamic range at the cost of sensitivity to low-level fluctuations.

  • STDEV_POSITIVE: the scale is set to sample the standard deviation of the image (bscale = stdev/quantizeLevel) and the dynamic range extends principally positive (allowing only quantizePad standard deviations negative).

  • STDEV_NEGATIVE: similar to STDEV_POSITIVE, but the dynamic range extends principally negative.

  • STDEV_BOTH: the scale is set similar to STDEV_POSITIVE, but the dynamic range is shared between the positive and negative sides.

  • MANUAL: the scale is set manually. We do what we’re told, no more, no less.

Perhaps this one class could/should have been polymorphic, with different subclasses for different algorithms? But I went with a C-like approach keying off the enum, probably because I was influenced by Pan-STARRS’ C code.

struct ImageWriteOptions
#include <fits.h>

Options for writing an image to FITS

An image being written to FITS may be scaled (quantised) and/or compressed. This struct is a container for options controlling each of those separately.

class MemFileManager
#include <fits.h>

Lifetime-management for memory that goes into FITS memory files.

namespace detail

Functions

template<typename T>
std::shared_ptr<PixelArrayBase> makePixelArray(int bitpix, ndarray::Array<T, 1, 1> const &array)

Create a PixelArray suitable for an image with the nominated BITPIX

Return

A new PixelArray.

Parameters
  • [in] bitpix: Bits per pixel (0,8,16,32,64,-32,-64) for output.

  • [in] array: Array with pixel values to convert.

template<typename T>
struct Bitpix
#include <fitsCompression.h>

FITS BITPIX header value by C++ type.

template<typename T>
class PixelArray : public lsst::afw::fits::detail::PixelArrayBase
#include <fitsCompression.h>

Typed array of pixel values.

class PixelArrayBase
#include <fitsCompression.h>

Abstract base class for an array of pixel values

For writing pixels out with the C-based cfitsio API, it’s helpful to have a type-agnostic holder of the pixel values (because although we can template on the array type, the output type can be configured at run-time, which means we can’t use ndarray::Array as the carrier). This is essentially a C++-ish void* array.

Subclassed by lsst::afw::fits::detail::PixelArray< T >

namespace formatters

Functions

bool extractOptionalFlag(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties, std::string const &name)

Returns true if and only if properties is non-null and contains a unique property with the given name that has type bool and a value of true.

std::string const getItemName(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties)

Extracts and returns the string-valued "itemName" property from the given data property object.

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: If the given pointer is null, or the PropertySet pointed to does not contain a unique property named "itemName".

int extractSliceId(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties)
int64_t extractFpaExposureId(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties)
int64_t extractCcdExposureId(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties)
int64_t extractAmpExposureId(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties)
int extractVisitId(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties)
int extractCcdId(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties)
int extractAmpId(std::shared_ptr<lsst::daf::base::PropertySet const> const &properties)
int countFitsHeaderCards(lsst::daf::base::PropertySet const &prop)
ndarray::Array<std::uint8_t, 1, 1> stringToBytes(std::string const &str)

Encode a std::string as a vector of uint8

std::string bytesToString(ndarray::Array<std::uint8_t const, 1, 1> const &bytes)

Decode a std::string from a vector of uint8 returned by stringToBytes

namespace geom

Typedefs

using TransformPoint2ToPoint2 = Transform<Point2Endpoint, Point2Endpoint>
using TransformPoint2ToGeneric = Transform<Point2Endpoint, GenericEndpoint>
using TransformPoint2ToSpherePoint = Transform<Point2Endpoint, SpherePointEndpoint>

Functions

std::ostream &operator<<(std::ostream &os, GenericEndpoint const &endpoint)

Print “GenericEndpoint(_n_)” to the ostream where _n_ is the number of axes, e.g. “GenericAxes(4)”.

std::ostream &operator<<(std::ostream &os, Point2Endpoint const &endpoint)

Print “Point2Endpoint()” to the ostream.

std::ostream &operator<<(std::ostream &os, SpherePointEndpoint const &endpoint)

Print “SpherePointEndpoint()” to the ostream.

Eigen::Matrix2d makeCdMatrix(lsst::geom::Angle const &scale, lsst::geom::Angle const &orientation = 0 * lsst::geom::degrees, bool flipX = false)

Make a WCS CD matrix

Return

the CD matrix, where element (i-1, j-1) corresponds to FITS keyword CDi_j and i, j have range [1, 2]

Parameters
  • [in] scale: Pixel scale as an angle on sky/pixels

  • [in] orientation: Position angle of pixel +Y, measured from N through E. At 0 degrees, +Y is along N and +X is along W/E if flipX false/true At 90 degrees, +Y is along E and +X is along N/S if flipX false/true

  • [in] flipX: Flip x axis? See orientation for details.

std::shared_ptr<SkyWcs> makeFlippedWcs(SkyWcs const &wcs, bool flipLR, bool flipTB, lsst::geom::Point2D const &center)

Return a copy of a FITS-WCS with pixel positions flipped around a specified center

Parameters
  • [in] wcs: The initial WCS

  • [in] flipLR: Flip pixel positions left/right about center

  • [in] flipTB: Flip pixel positions top/bottom about center

  • [in] center: Center pixel position of flip

std::shared_ptr<SkyWcs> makeModifiedWcs(TransformPoint2ToPoint2 const &pixelTransform, SkyWcs const &wcs, bool modifyActualPixels)

Create a new SkyWcs whose pixels are transformed by pixelTransform, as described below.

If modifyActualPixels is true and the cameraGeom::ACTUAL_PIXELS frame exists then pixelTransform is inserted just after the cameraGeom::ACTUAL_PIXELS frame:

newActualPixelsToPixels = pixelTransform -> oldActualPixelsToPixels

This is appropriate for shifting a WCS, e.g. when writing FITS metadata for a subimage.

If modifyActualPixels is false or the cameraGeom::ACTUAL_PIXELS frame does not exist then pixelTransform is inserted just after the cameraGeom::PIXELS frame:

newPixelsToIwc = pixelTransform -> oldPixelsToIwc

This is appropriate for inserting a model for optical distortion.

Other than the change described above, the new SkyWcs will be just like the old one.

Return

the new WCS

Parameters
  • [in] pixelTransform: Transform to insert

  • [in] wcs: Input WCS

  • [in] modifyActualPixels: Location at which to insert the transform; if true and the cameraGeom::ACTUAL_PIXELS frame is present then insert just after the cameraGeom::ACTUAL_PIXELS frame, else insert just after the cameraGeom::PIXELS frame.

std::shared_ptr<SkyWcs> makeSkyWcs(daf::base::PropertySet &metadata, bool strip = false)

Construct a SkyWcs from FITS keywords

This function is preferred over calling the SkyWcs metadata constructor directly because it allows us to change SkyWcs to an abstract base class in the future, without affecting code that constructs a WCS from FITS metadata.

Parameters
  • [in] metadata: FITS header metadata

  • [in] strip: If true: strip items from metadata used to create the WCS, such as RADESYS, EQUINOX, CTYPE12, CRPIX12, CRVAL12, etc. Always keep keywords that might be wanted for other purpposes, including NAXIS12 and date-related keywords such as “DATE-OBS” and “TIMESYS” (but not “EQUINOX”).

Exceptions
  • lsst::pex::exceptions::TypeError: if the metadata does not describe a celestial WCS.

std::shared_ptr<SkyWcs> makeSkyWcs(lsst::geom::Point2D const &crpix, lsst::geom::SpherePoint const &crval, Eigen::Matrix2d const &cdMatrix, std::string const &projection = "TAN")

Construct a simple FITS SkyWcs with no distortion

Parameters
  • [in] crpix: Center of projection on the CCD using the LSST convention: 0, 0 is the lower left pixel of the parent image

  • [in] crval: Center of projection on the sky

  • [in] cdMatrix: CD matrix, where element (i-1, j-1) corresponds to FITS keyword CDi_j and i, j have range [1, 2]. May be computed by calling makeCdMatrix.

  • [in] projection: The name of the FITS WCS projection, e.g. “TAN” or “STG”

std::shared_ptr<SkyWcs> makeSkyWcs(TransformPoint2ToPoint2 const &pixelsToFieldAngle, lsst::geom::Angle const &orientation, bool flipX, lsst::geom::SpherePoint const &boresight, std::string const &projection = "TAN")

Construct a FITS SkyWcs from camera geometry

Return

a SkyWcs whose sky origin is the boresight and pixel origin is focal plane (0, 0).

Note

Unlike makeCdMatrix, orientation is with respect to the focal plane axes, not the CCD axes. This is because field angle is defined with respect to focal plane axes.

Parameters
  • [in] pixelsToFieldAngle: Transformation from pixels to field angle (in radians).

  • [in] orientation: Position angle of focal plane +Y, measured from N through E at crval. At 0 degrees, +Y is along N and +X is along W/E if flipX false/true. At 90 degrees, +Y is along E and +X is along N/S if flipX false/true.

  • [in] flipX: Flip x axis? See orientation for details.

  • [in] boresight: ICRS sky position at the boresight (field angle (0, 0)).

  • [in] projection: The name of the FITS WCS projection, e.g. “TAN” or “STG”.

std::shared_ptr<SkyWcs> makeTanSipWcs(lsst::geom::Point2D const &crpix, lsst::geom::SpherePoint const &crval, Eigen::Matrix2d const &cdMatrix, Eigen::MatrixXd const &sipA, Eigen::MatrixXd const &sipB)

Construct a TAN-SIP SkyWcs with forward SIP distortion terms and an iterative inverse.

Parameters
  • [in] crpix: Center of projection on the CCD using the LSST convention: 0, 0 is the lower left pixel of the parent image

  • [in] crval: Center of projection on the sky

  • [in] cdMatrix: CD matrix, where element (i-1, j-1) corresponds to FITS keyword CDi_j and i, j have range [1, 2]. May be computed by calling makeCdMatrix.

  • [in] sipA: Forward distortion matrix for axis 1

  • [in] sipB: Forward distortion matrix for axis 2

std::shared_ptr<SkyWcs> makeTanSipWcs(lsst::geom::Point2D const &crpix, lsst::geom::SpherePoint const &crval, Eigen::Matrix2d const &cdMatrix, Eigen::MatrixXd const &sipA, Eigen::MatrixXd const &sipB, Eigen::MatrixXd const &sipAp, Eigen::MatrixXd const &sipBp)

Construct a TAN WCS with forward and inverse SIP distortion terms.

Parameters
  • [in] crpix: Center of projection on the CCD using the LSST convention: 0, 0 is the lower left pixel of the parent image

  • [in] crval: Center of projection on the sky

  • [in] cdMatrix: CD matrix, where element (i-1, j-1) corresponds to FITS keyword CDi_j and i, j have range [1, 2]. May be computed by calling makeCdMatrix.

  • [in] sipA: Forward distortion matrix for axis 1

  • [in] sipB: Forward distortion matrix for axis 2

  • [in] sipAp: Reverse distortion matrix for axis 1

  • [in] sipBp: Reverse distortion matrix for axis 2

std::shared_ptr<TransformPoint2ToPoint2> makeWcsPairTransform(SkyWcs const &src, SkyWcs const &dst)

A Transform obtained by putting two SkyWcs objects “back to back”.

Provides basic exception safety.

Return

a Transform whose forward transformation converts from src pixels to dst pixels, and whose inverse transformation converts in the opposite direction.

Parameters
  • src: the WCS for the source pixels

  • dst: the WCS for the destination pixels

std::shared_ptr<TransformPoint2ToSpherePoint> getIntermediateWorldCoordsToSky(SkyWcs const &wcs, bool simplify = true)

Return a transform from intermediate world coordinates to sky

std::shared_ptr<TransformPoint2ToPoint2> getPixelToIntermediateWorldCoords(SkyWcs const &wcs, bool simplify = true)

Return a transform from pixel coordinates to intermediate world coordinates

The pixel frame is is the base frame: cameraGeom::ACTUAL_PIXELS, if present, else cameraGeom::PIXELS.

std::ostream &operator<<(std::ostream &os, SkyWcs const &wcs)

Print a SkyWcs to an ostream (delegates to SkyWcs.toString()).

template<class FromEndpoint, class ToEndpoint>
std::ostream &operator<<(std::ostream &os, Transform<FromEndpoint, ToEndpoint> const &transform)

Print a Transform to an ostream

The format is “Transform<_fromEndpoint_, _toEndpoint_>” where fromEndpoint and toEndpoint are the appropriate endpoint printed to the ostream; for example “Transform<GenericEndpoint(4), Point2Endpoint()>”

lsst::geom::AffineTransform linearizeTransform(TransformPoint2ToPoint2 const &original, lsst::geom::Point2D const &inPoint)

Approximate a Transform by its local linearization.

Return

an lsst::geom::AffineTransform whose value and Jacobian at inPoint match those of original. It may be invertible; in general, linearizations are invertible if the Jacobian at inPoint is invertible.

Template Parameters
  • FromEndpointToEndpoint: The endpoints of the transform.

Parameters
  • original: the Transform to linearize

  • inPoint: the point at which a linear approximation is desired

Exceptions
  • pex::exceptions::InvalidParameterError: Thrown if original does not have a well-defined value and Jacobian at inPoint Not exception safe.

std::shared_ptr<TransformPoint2ToPoint2> makeTransform(lsst::geom::AffineTransform const &affine)

Wrap an lsst::geom::AffineTransform as a Transform.

Provides basic exception safety.

Return

a Transform that that maps any lsst::geom::Point2D x to affine(x). It shall be invertible iff affine is invertible.

Parameters
  • affine: The lsst::geom::AffineTransform to wrap.

std::shared_ptr<TransformPoint2ToPoint2> makeRadialTransform(std::vector<double> const &coeffs)

A purely radial polynomial distortion.

The Transform transforms an input \(x\) to

\[ \frac{x}{r} \sum_{i=1}^{N} \mathrm{coeffs[i]} \ r^i \]
where \(r\) is the magnitude of \(x\).

Return

the radial distortion represented by coeffs. The Transform shall have an inverse, which may be approximate.

Parameters
  • coeffs: radial polynomial coefficients. May be an empty vector to represent the identity transformation; otherwise must have size > 1, coeffs[0] = 0, and coeffs[1] 0.

Exceptions
  • pex::exceptions::InvalidParameterError: Thrown if coeffs does not have the required format. Provides basic exception safety.

std::shared_ptr<TransformPoint2ToPoint2> makeRadialTransform(std::vector<double> const &forwardCoeffs, std::vector<double> const &inverseCoeffs)

A purely radial polynomial distortion.

Similar to makeRadialTransform(std::vector<double> const &), but allows the user to provide an inverse.

Return

the radial distortion represented by coeffs. The Transform shall have an inverse, whose accuracy is determined by the relationship between forwardCoeffs and inverseCoeffs.

Parameters
  • forwardCoeffs: radial polynomial coefficients. May be an empty vector to represent the identity transformation; otherwise must have size > 1, coeffs[0] = 0, and coeffs[1] 0.

  • inverseCoeffs: coefficients for the inverse transform, as above. Does not need to have the same degree as forwardCoeffs, but either both must be empty or neither must be empty.

Exceptions
  • pex::exceptions::InvalidParameterError: Thrown if forwardCoeffs or inverseCoeffs does not have the required format. Provides basic exception safety.

std::shared_ptr<TransformPoint2ToPoint2> makeIdentityTransform()

Trivial Transform x x.

Provides basic exception safety.

Return

a Transform mapping any lsst::geom::Point2D to itself. The Transform’s inverse shall be itself.

std::shared_ptr<daf::base::PropertyList> createTrivialWcsMetadata(std::string const &wcsName, lsst::geom::Point2I const &xy0)
void deleteBasicWcsMetadata(daf::base::PropertySet &metadata, std::string const &wcsName)
Eigen::Matrix2d getCdMatrixFromMetadata(daf::base::PropertySet &metadata)

Read a CD matrix from FITS WCS metadata

The elements of the returned matrix are in degrees

Exceptions
  • pex::exceptions::TypeError: if no CD matrix coefficients found (missing coefficients are set to 0, as usual, but they cannot all be missing).

lsst::geom::Point2I getImageXY0FromMetadata(daf::base::PropertySet &metadata, std::string const &wcsName, bool strip = false)
Eigen::MatrixXd getSipMatrixFromMetadata(daf::base::PropertySet const &metadata, std::string const &name)
bool hasSipMatrix(daf::base::PropertySet const &metadata, std::string const &name)
std::shared_ptr<daf::base::PropertyList> makeSipMatrixMetadata(Eigen::MatrixXd const &matrix, std::string const &name)
std::shared_ptr<daf::base::PropertyList> makeSimpleWcsMetadata(lsst::geom::Point2D const &crpix, lsst::geom::SpherePoint const &crval, Eigen::Matrix2d const &cdMatrix, std::string const &projection = "TAN")

Make FITS metadata for a simple FITS WCS (one with no distortion).

This can also be used as a starting point for creating metadata for more sophisticated FITS WCS.

Parameters
  • [in] crpix: Center of projection on the CCD using the LSST convention: 0, 0 is the lower left pixel of the image

  • [in] crval: Center of projection on the sky

  • [in] cdMatrix: CD matrix where element (i-1, j-1) corresponds to FITS keyword CDi_j and i, j have range [1, 2]

  • [in] projection: The name of the FITS WCS projection, e.g. “TAN” or “STG”

std::shared_ptr<daf::base::PropertyList> makeTanSipMetadata(lsst::geom::Point2D const &crpix, lsst::geom::SpherePoint const &crval, Eigen::Matrix2d const &cdMatrix, Eigen::MatrixXd const &sipA, Eigen::MatrixXd const &sipB)

Make metadata for a TAN-SIP WCS without inverse matrices

Parameters
  • [in] crpix: Center of projection on the CCD using the LSST convention: 0, 0 is the lower left pixel of the parent image

  • [in] crval: Center of projection on the sky

  • [in] cdMatrix: CD matrix, where element (i-1, j-1) corresponds to FITS keyword CDi_j and i, j have range [1, 2]. May be computed by calling makeCdMatrix.

  • [in] sipA: Forward distortion matrix for axis 1

  • [in] sipB: Forward distortion matrix for axis 2

std::shared_ptr<daf::base::PropertyList> makeTanSipMetadata(lsst::geom::Point2D const &crpix, lsst::geom::SpherePoint const &crval, Eigen::Matrix2d const &cdMatrix, Eigen::MatrixXd const &sipA, Eigen::MatrixXd const &sipB, Eigen::MatrixXd const &sipAp, Eigen::MatrixXd const &sipBp)

Make metadata for a TAN-SIP WCS

Parameters
  • [in] crpix: Center of projection on the CCD using the LSST convention: 0, 0 is the lower left pixel of the parent image

  • [in] crval: Center of projection on the sky

  • [in] cdMatrix: CD matrix, where element (i-1, j-1) corresponds to FITS keyword CDi_j and i, j have range [1, 2]. May be computed by calling makeCdMatrix.

  • [in] sipA: Forward distortion matrix for axis 1

  • [in] sipB: Forward distortion matrix for axis 2

  • [in] sipAp: Reverse distortion matrix for axis 1

  • [in] sipBp: Reverse distortion matrix for axis 2

template<typename PointT, typename ArrayT>
class BaseEndpoint
#include <Endpoint.h>

Virtual base class for endpoints, which are helper classes for Transform

Endpoints transform points and lists of points from LSST-specific data types, such as lsst::geom::Point2D and lsst::geom::SpherePoint, to a form accepted by ast::Mapping.tran. Each type of endpoint is used for a particular LSST data type, for example:

Endpoints use the following forms of data for raw data:

  • std::vector<double> for a single point

  • ndarray<double, 2, 2> with dimensions number of axes x number of points for an array of points

Endpoints are designed as helper classes for Transform. Each transform has a two endpoints: one for input data and one for output data.

Endpoint also provides two methods to work with ast::Frames:

  • normalizeFrame verifies that a frame is the correct type, and adjusts its settings if necessary

  • makeFrame creates a new frame with the correct type and settings

Template Parameters
  • PointT: LSST data type for one point

  • ArrayT: LSST data type for an array of points

template<typename PointT>
class BaseVectorEndpoint : public lsst::afw::geom::BaseEndpoint<PointT, std::vector<PointT>>
#include <Endpoint.h>

Base class for endpoints with Array = std::vector<Point> where Point has 2 dimensions

Note

Subclasses must provide dataFromPoint, dataFromArray, pointFromData and arrayFromData

class GenericEndpoint : public lsst::afw::geom::BaseEndpoint<std::vector<double>, ndarray::Array<double, 2, 2>>
#include <Endpoint.h>

A generic endpoint for data in the format used by ast::Mapping

Thus supports all ast frame classes and any number of axes, and thus can be used as an endpoint for any ast::Mapping.

class Point2Endpoint : public lsst::afw::geom::BaseVectorEndpoint<lsst::geom::Point2D>
#include <Endpoint.h>

An endpoint for lsst::geom::Point2D

class SipApproximation
#include <SipApproximation.h>

A fitter and results class for approximating a general Transform in a form compatible with FITS WCS persistence.

The Simple Imaging Polynomial (SIP) convention (Shupe et al 2005) adds forward and reverse polynomial mappings to a standard projection FITS WCS projection (e.g. “TAN” for gnomonic) that relate Intermediate World Coordinates (see Calabretta & Greisen 2002) to image pixel coordinates. The SIP “forward” transform is defined by polynomial coeffients \(A\) and \(B\) that map pixel coordinates \((u, v)\) to Intermediate World Coordinates \((x, y)\) via

\[\begin{split} \boldsymbol{S}\left[\begin{array}{c} x \\ y \end{array}\right] \equiv \left[\begin{array}{c} x_s \\ y_s \end{array}\right] = \left[\begin{array}{c} (u - u_0) + \displaystyle\sum_{p,q}^{0 \le p + q \le N} \mathrm{A}_{p,q} (u - u_0)^p (v - v_0)^q \\ (v - v_0) + \displaystyle\sum_{p,q}^{0 \le p + q \le N} \mathrm{B}_{p,q} (u - u_0)^p (v - v_0)^q \end{array}\right] \end{split}\]
The reverse transform has essentially the same form:
\[\begin{split} \left[\begin{array}{c} u - u_0 \\ v - v_0 \end{array}\right] = \left[\begin{array}{c} x_s + \displaystyle\sum_{p,q}^{0 \le p + q \le N} \mathrm{AP}_{p,q} x_s^p y_s^q \\ y_s + \displaystyle\sum_{p,q}^{0 \le p + q \le N} \mathrm{BP}_{p,q} x_s^p y_s^q \end{array}\right] \end{split}\]
In both cases, \((u_0, v_0)\) is the pixel origin (CRPIX in FITS WCS) and \(\boldsymbol{S}\) is the inverse of the Jacobian “CD” matrix. Both CRPIX and CD are considered fixed inputs, and we do not attempt to null the zeroth- and first-order terms of \(A\) and \(B\) (as some SIP fitters do); together, these conventions make solving for the coefficients a much simpler linear problem.

While LSST WCSs are in general too complex to be described exactly in FITS WCS, they can generally be closely approximated by standard FITS WCS projection with additional SIP distortions. This class fits such an approximation, given a TransformPoint2ToPoint2 object that represents the exact mapping from pixels to Intermediate World Coordinates with a SIP distortion.

Note

In the implementation, we typically refer to \((u-u_0, v-v_0)\) as dpix (for “pixel delta”), and \((x_s, y_s)\) as siwc

(for “scaled

intermediate world coordinates”).

class SkyWcs : public lsst::afw::table::io::PersistableFacade<SkyWcs>, public Storable
#include <SkyWcs.h>

A 2-dimensional celestial WCS that transform pixels to ICRS RA/Dec, using the LSST standard for pixels.

SkyWcs is an immutable object that can not only represent any standard FITS WCS, but can also contain arbitrary Transforms, e.g. to model optical distortion or pixel imperfections.

In order to make a SkyWcs that models optical distortion, say, it is usually simplest to start with a standard FITS WCS (such as a TAN WCS) as an approximation, then insert a transform that models optical distortion by calling makeModifiedWcs. However, it is also possible to build a SkyWcs entirely from transforms, if you prefer, by building an ast::FrameDict and constructing the SkyWcs from that.

Frames of reference

SkyWcs internally keeps track of the following frames of reference:

  • cameraGeom::ACTUAL_PIXELS (optional): “actual” pixel position using the LSST standard. This has the same meaning as the cameraGeom::ACTUAL_PIXELS frame: actual pixels include effects such as “tree ring” distortions and electrical effects at the edge of CCDs. This frame should only be provided if there is a reasonable model for these imperfections.

  • cameraGeom::PIXELS: nominal pixel position, using the LSST standard. This has the same meaning as the cameraGeom::PIXELS frame: nominal pixels may be rectangular, but are uniform in size and spacing.

  • IWC: intermediate world coordinates (the FITS WCS concept).

  • SKY: position on the sky as ICRS, with standard RA, Dec axis order.

Pixel position standards

The LSST standard for pixel position is: 0,0 is the center of the lower left image pixel. The FITS standard for pixel position is: 1,1 is the center of the lower left image pixel.

LSST and FITS also use a different origin for subimages:

  • LSST pixel position is in the frame of reference of the parent image

  • FITS pixel position is in the frame of reference of the subimage However, SkyWcs does not keep track of this difference. Code that persists and unpersists SkyWcs using FITS-WCS header cards must handle the offset, e.g. by calling copyAtShiftedPixelOrigin

Internal details: the contained ast::FrameDict

SkyWcs contains an ast::FrameDict which transforms from pixels to sky (in radians) in the forward direction.

This FrameDict contains the named frames described in frames of reference, e.g. “SKY”, “IWC”, cameraGeom::PIXELS and possibly cameraGeom::ACTUAL_PIXELS. “SKY” is the current frame. If cameraGeom::ACTUAL_PIXELS is present then it is the base frame, otherwise cameraGeom::PIXELS is the base frame.

The “SKY” frame is of type ast::SkyFrame and has the following attributes:

  • SkyRef is set to the sky origin of the WCS (ICRS RA, Dec) in radians.

  • SkyRefIs is set to “Ignored” so that SkyRef is not used in transformations.

The other frames are of type ast::Frame and have 2 axes.

class Span
#include <Span.h>

A range of pixels within one row of an Image

class SpanPixelIterator : public boost::iterator_facade<SpanPixelIterator, lsst::geom::Point2I const, boost::random_access_traversal_tag>
#include <SpanPixelIterator.h>

An iterator that yields lsst::geom::Point2I and increases in the x direction.

This is used to iterate over the pixels in a Span, and by extension to iterate over regions like boxes and ellipses.

class SpherePointEndpoint : public lsst::afw::geom::BaseVectorEndpoint<lsst::geom::SpherePoint>
#include <Endpoint.h>

An endpoint for lsst::geom::SpherePoint

A SpherePointEndpoint always has 2 axes: longitude, latitude

template<class FromEndpoint, class ToEndpoint>
class Transform : public lsst::afw::table::io::PersistableFacade<Transform<FromEndpoint, ToEndpoint>>, public lsst::afw::table::io::Persistable
#include <Transform.h>

Transform LSST spatial data, such as lsst::geom::Point2D and lsst::geom::SpherePoint, using an AST mapping.

This class contains two Endpoints, to specify the “from” and “to” LSST data type, and an ast::Mapping to specify the transformation.

Depending on the ast::FrameSet or ast::Mapping used to define it, a Transform may provide either a forward transform, an inverse transform, or both. In particular, the inverse of a forward-only transform is an inverse-only transform. The hasForward and hasInverse methods can be used to check which transforms are available.

Unless otherwise stated, all constructors and methods may throw std::runtime_error to indicate internal errors within AST.

Transforms are always immutable.

Note

You gain some safety by constructing a Transform from an ast::FrameSet, since the base and current frames in the FrameSet can be checked against by the appropriate endpoint.

Note

”In place” versions of applyForward and applyInverse are not available because data must be copied when converting from LSST data types to the type used by astshim, so it didn’t seem worth the bother.

namespace detail

Functions

std::shared_ptr<ast::FrameSet> readFitsWcs(daf::base::PropertySet &metadata, bool strip = true)

Read a FITS convention WCS FrameSet from FITS metadata

The resulting FrameSet may be any kind of WCS supported by FITS; if it is a celestial WCS then 1,1 will be the lower left corner of the image (the FITS convention, not the LSST convention).

This routine replaces RADECSYS with RADESYS if the former is present and the latter is not, since that is a common misspelling in FITS headers.

The returned FrameSet will have an IWC (intermediate world coordinate system) frame.

Parameters
  • [inout] metadata: FITS header cards

  • [in] strip: If true: strip items from metadata used to create the WCS, such as RADESYS, EQUINOX, CTYPE12, CRPIX12, CRVAL12, etc. Always keep keywords that might be wanted for other purpposes, including NAXIS12 and date-related keywords such as “DATE-OBS” and “TIMESYS” (but not “EQUINOX”).

Exceptions
  • pex::exceptions::TypeError: if the metadata does not contain a FITS-WCS

std::shared_ptr<ast::FrameDict> readLsstSkyWcs(daf::base::PropertySet &metadata, bool strip = true)

Read an LSST celestial WCS FrameDict from a FITS header.

Calls getImageXY0FromMetadata to determine image XY0.

Saves CRVAL by setting the output SkyFrame’s SkyRef to CRVAL and SkyRefIs=”Ignore” (so SkyRef is not treated as an offset).

The frames of the returned WCS will be as follows:

  • ”PIXELS” (base frame): pixel frame with 0,0 the lower left corner of the image (LSST convention)

  • ”IWC”: FITS WCS intermediate world coordinate system

  • ”SKY” (current frame): an ast::SkyFrame with domain “SKY”: ICRS RA, Dec

Warning

Does not compensate for the offset between a subimage and its parent image; callers must do that manually, e.g. by calling SkyWcs::copyAtShiftedPosition.

Warning

the general SkyWcs generated by LSST software cannot be exactly represented using standard WCS FITS cards, and so this function cannot read those. This function is intended for two purposes:

  • Read the standard FITS WCS found in raw data and other images from non-LSST observatories and convert it to the LSST pixel convention.

  • Read the approximate FITS WCS that LSST writes to FITS images (for use by non-LSST code).

All frames are instances of ast::Frame except the SKY frame. All have 2 axes.

Parameters
  • [inout] metadata: FITS header cards

  • [in] strip: If true: strip items from metadata used to create the WCS, such as RADESYS, EQUINOX, CTYPE12, CRPIX12, CRVAL12, etc. Always keep keywords that might be wanted for other purpposes, including NAXIS12 and date-related keywords such as “DATE-OBS” and “TIMESYS” (but not “EQUINOX”).

Exceptions
  • lsst::pex::exceptions::TypeError: if the metadata does not describe a celestial WCS.

std::shared_ptr<daf::base::PropertyList> getPropertyListFromFitsChan(ast::FitsChan &fitsChan)

Copy values from an AST FitsChan into a PropertyList

Warning

COMMENT and HISTORY cards are treated as string values

Exceptions
  • lsst::pex::exceptions::TypeError: if fitsChan contains cards whose type is not supported by PropertyList: complex numbers, or cards with no value

ast::FitsChan getFitsChanFromPropertyList(daf::base::PropertySet &metadata, std::set<std::string> const &excludeNames = {}, std::string options = "")

Construct AST FitsChan from PropertyList

Return

an ast::FitsChan representing this PropertyList

Parameters
  • [in] metadata: Metadata to transfer; if this is a PropertyList then the order of items is preserved.

  • [in] excludeNames: Names of entries to exclude from the returned header string.

  • [in] options: Options string to pass to ast::FitsChan constructor.

template<class Transform>
std::shared_ptr<Transform> readStream(std::istream &is)

Deserialize a Transform from an input stream

Template Parameters
  • Transform: the Transform class; can be Transform<FromEndpoint, ToEndpoint>, SkyWcs, or any other compatible class, i.e. it must support the following (see Transform.h for details):

    • a constructor that takes an ast::FrameSet

    • static method getShortClassName

    • method getMapping

Parameters
  • [in] is: input stream from which to deserialize this Transform

template<class Transform>
void writeStream(Transform const &transform, std::ostream &os)

Serialize a Transform to an output stream

Version 1 format is as follows:

  • The version number (an integer)

  • A space

  • The short class name, as obtained from getShortClassName

  • A space

  • The contained ast::FrameSet written using FrameSet.show(os, false)

Parameters
  • [out] os: output stream to which to serialize this Transform

  • [in] transform: Transform to serialize

Variables

constexpr int serializationVersion = 1

version of serialization used when writing (older versions may also be supported when reading)

namespace ellipses

Typedefs

typedef Separable<Distortion, DeterminantRadius> SeparableDistortionDeterminantRadius
typedef Separable<Distortion, TraceRadius> SeparableDistortionTraceRadius
typedef Separable<Distortion, LogDeterminantRadius> SeparableDistortionLogDeterminantRadius
typedef Separable<Distortion, LogTraceRadius> SeparableDistortionLogTraceRadius
typedef Separable<ConformalShear, DeterminantRadius> SeparableConformalShearDeterminantRadius
typedef Separable<ConformalShear, TraceRadius> SeparableConformalShearTraceRadius
typedef Separable<ConformalShear, LogDeterminantRadius> SeparableConformalShearLogDeterminantRadius
typedef Separable<ConformalShear, LogTraceRadius> SeparableConformalShearLogTraceRadius
typedef Separable<ReducedShear, DeterminantRadius> SeparableReducedShearDeterminantRadius
typedef Separable<ReducedShear, TraceRadius> SeparableReducedShearTraceRadius
typedef Separable<ReducedShear, LogDeterminantRadius> SeparableReducedShearLogDeterminantRadius
typedef Separable<ReducedShear, LogTraceRadius> SeparableReducedShearLogTraceRadius
class Axes : public lsst::afw::geom::ellipses::BaseCore
#include <Axes.h>

An ellipse core for the semimajor/semiminor axis and position angle parametrization (a,b,theta).

class BaseCore
#include <BaseCore.h>

A base class for parametrizations of the “core” of an ellipse - the ellipticity and size.

A subclass of BaseCore provides a particular interpretation of the three pointing point values that define an ellipse’s size and ellipticity (including position angle). All core subclasses are implicitly convertible and can be assigned to from any other core.

Subclassed by lsst::afw::geom::ellipses::Axes, lsst::afw::geom::ellipses::Quadrupole, lsst::afw::geom::ellipses::Separable< Ellipticity_, Radius_ >

Coordinate transforms

These member functions transform the ellipse by the given lsst::geom::LinearTransform. The transform can be done in-place by calling inPlace() on the returned expression object, or returned as a new shared_ptr by calling copy().

class ConformalShear : public lsst::afw::geom::ellipses::detail::EllipticityBase
#include <ConformalShear.h>

A logarithmic complex ellipticity with magnitude \(|e| = \ln (a/b) \).

For a more complete definition, see Bernstein and Jarvis (2002); this the same as their conformal shear \(\eta\) (eq. 2.3-2.6).

class DeterminantRadius
#include <radii.h>

The radius defined as the 4th root of the determinant of the quadrupole matrix.

The determinant radius is equal to the standard radius for a circle, and \(\pi R_{det}^2\) is the area of the ellipse.

class Distortion : public lsst::afw::geom::ellipses::detail::EllipticityBase
#include <Distortion.h>

A complex ellipticity with magnitude \(|e| = \frac{a^2 - b^2}{a^2 + b^2}\).

For a more complete definition, see Bernstein and Jarvis (2002); this the same as their distortion \(\delta\) (eq. 2.7).

class Ellipse
#include <Ellipse.h>

An ellipse defined by an arbitrary BaseCore and a center point.

An ellipse is composed of its center coordinate and its Core - a parametrization of the ellipticity and size of the ellipse. Setting the core of an ellipse never changes the type of the contained core, it merely sets the parameters of that core by converting the parameters.

Coordinate transforms

These member functions transform the ellipse by the given lsst::geom::AffineTransform. The transform can be done in-place by calling inPlace() on the returned expression object, or returned as a new shared_ptr by calling copy().

class LogDeterminantRadius
#include <radii.h>

The natural logarithm of the DeterminantRadius

class LogTraceRadius
#include <radii.h>

The natural logarithm of the TraceRadius

class Parametric
#include <Parametric.h>

A functor that returns points on the boundary of the ellipse as a function of a parameter that runs between 0 and 2 pi (but is not angle).

class PixelRegion
#include <PixelRegion.h>

A pixelized region containing all pixels whose centers are within an Ellipse.

The pixel region for an ellipse may be larger or smaller in area than the ellipse itself, depending on the details of where pixel centers land, and it may be empty even if the area of the ellipse is nonzero.

class Quadrupole : public lsst::afw::geom::ellipses::BaseCore
#include <Quadrupole.h>

An ellipse core with quadrupole moments as parameters.

class ReducedShear : public lsst::afw::geom::ellipses::detail::EllipticityBase
#include <ReducedShear.h>

A complex ellipticity with magnitude \(|e| = \frac{a-b}{a+b} \).

For a more complete definition, see Bernstein and Jarvis (2002); this the same as their reduced shear \(g\) (eq. 2.8).

template<typename Ellipticity_, typename Radius_>
class Separable : public lsst::afw::geom::ellipses::BaseCore
#include <Separable.h>

An ellipse core with a complex ellipticity and radius parameterization.

class TraceRadius
#include <radii.h>

The radius defined as \(\sqrt{0.5(I_{xx} + I_{yy})}\)

The trace radius is equal to the standard radius for a circle

namespace detail
class EllipticityBase
#include <EllipticityBase.h>

EllipticityBase is a base class for complex ellipticity types.

EllipticityBase does not have a virtual destructor, and only exists for code reuse purposes. The ellipticity classes are not polymorphic simply to keep them small.

Subclassed by lsst::afw::geom::ellipses::ConformalShear, lsst::afw::geom::ellipses::Distortion, lsst::afw::geom::ellipses::ReducedShear

namespace polygon

Functions

LSST_EXCEPTION_TYPE(SinglePolygonException, lsst::pex::exceptions::RuntimeError, lsst::afw::geom::polygon::SinglePolygonException)

An exception that indicates the single-polygon assumption has been violated

The single-polygon assumption is used in Polygon::intersectionSingle and Polygon::unionSingle.

std::ostream &operator<<(std::ostream &os, Polygon const &poly)

Stream polygon.

class Polygon : public lsst::afw::table::io::PersistableFacade<Polygon>, public Storable
#include <Polygon.h>

Cartesian polygons

Polygons are defined by a set of vertices

namespace image

Typedefs

typedef std::int32_t MaskPixel

default type for Masks and MaskedImage Masks

typedef float VariancePixel

default type for MaskedImage variance images

Enums

enum ImageOrigin

Values:

PARENT
LOCAL
enum xOrY

Values:

X
Y
enum RotType

Type of rotation.

Values:

UNKNOWN

Rotation angle is unknown. Note: if there is no instrument rotator then it is better to compute SKY or HORIZON and use that rotation type rather than specify UNKNOWN.

SKY

Position angle of focal plane +Y, measured from N through E. At 0 degrees, +Y is along N and +X is along E/W depending on handedness. At 90 degrees, +Y is along E and +X is along S/N depending on handedness.

HORIZON

Position angle of focal plane +Y, measured from +Alt through +Az. At 0 degrees, +Y is along +Alt and +X is along +/-Az, depending on handedness. At 90 degrees, +Y is along +Az and +X is along -/+Alt, depending on handedness.

MOUNT

The position sent to the instrument rotator; the details depend on the rotator.

Functions

double abMagFromFlux(double flux)

Compute AB magnitude from flux in Janskys.

double abMagErrFromFluxErr(double fluxErr, double flux)

Compute AB magnitude error from flux and flux error in Janskys.

double fluxFromABMag(double mag)

Compute flux in Janskys from AB magnitude.

double fluxErrFromABMagErr(double magErr, double mag)

Compute flux error in Janskys from AB magnitude error and AB magnitude.

template<typename T>
ndarray::Array<T, 1> abMagFromFlux(ndarray::Array<T const, 1> const &flux)

Compute AB magnitude from flux in Janskys.

template<typename T>
ndarray::Array<T, 1> abMagErrFromFluxErr(ndarray::Array<T const, 1> const &fluxErr, ndarray::Array<T const, 1> const &flux)

Compute AB magnitude error from flux and flux error in Janskys.

template<typename T>
ndarray::Array<T, 1> fluxFromABMag(ndarray::Array<T const, 1> const &mag)

Compute flux in Janskys from AB magnitude.

template<typename T>
ndarray::Array<T, 1> fluxErrFromABMagErr(ndarray::Array<T const, 1> const &magErr, ndarray::Array<T const, 1> const &mag)

Compute flux error in Janskys from AB magnitude error and AB magnitude.

template<typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
std::shared_ptr<Exposure<ImagePixelT, MaskPixelT, VariancePixelT>> makeExposure(MaskedImage<ImagePixelT, MaskPixelT, VariancePixelT> &mimage, std::shared_ptr<geom::SkyWcs const> wcs = std::shared_ptr<geom::SkyWcs const>())

Parameters

A function to return an Exposure of the correct type (cf. std::make_pair)

template<typename LhsPixelT, typename RhsPixelT>
Image<LhsPixelT> &operator+=(Image<LhsPixelT> &lhs, Image<RhsPixelT> const &rhs)

Add lhs to Image rhs (i.e. pixel-by-pixel addition) where types are different.

template<typename LhsPixelT, typename RhsPixelT>
Image<LhsPixelT> &operator-=(Image<LhsPixelT> &lhs, Image<RhsPixelT> const &rhs)

Subtract lhs from Image rhs (i.e. pixel-by-pixel subtraction) where types are different.

template<typename LhsPixelT, typename RhsPixelT>
Image<LhsPixelT> &operator*=(Image<LhsPixelT> &lhs, Image<RhsPixelT> const &rhs)

Multiply lhs by Image rhs (i.e. pixel-by-pixel multiplication) where types are different.

template<typename LhsPixelT, typename RhsPixelT>
Image<LhsPixelT> &operator/=(Image<LhsPixelT> &lhs, Image<RhsPixelT> const &rhs)

Divide lhs by Image rhs (i.e. pixel-by-pixel division) where types are different.

template<typename PixelT>
void swap(Image<PixelT> &a, Image<PixelT> &b)
template<typename PixelT>
void swap(DecoratedImage<PixelT> &a, DecoratedImage<PixelT> &b)
lsst::geom::Box2I bboxFromMetadata(daf::base::PropertySet &metadata)

Determine the image bounding box from its metadata (FITS header)

Note that this modifies the metadata, stripping the WCS headers that provide the xy0.

template<typename T1, typename T2>
bool imagesOverlap(ImageBase<T1> const &image1, ImageBase<T2> const &image2)

Return true if the pixels for two images or masks overlap in memory.

template<typename LhsT>
void for_each_pixel(Image<LhsT> &lhs, pixelOp0<LhsT> const &func)

Parameters
  • lhs: Image to set

  • func: functor to call

Set each pixel in an Image<LhsT> to func()

template<typename LhsT>
void for_each_pixel(Image<LhsT> &lhs, pixelOp1<LhsT> const &func)

Parameters
  • lhs: Image to set

  • func: functor to call

Set each pixel in an Image<LhsT> to func(lhs)

template<typename LhsT>
void for_each_pixel(Image<LhsT> &lhs, pixelOp1XY<LhsT> const &func)

Parameters
  • lhs: Image to set

  • func: functor to call

Set each pixel in an Image<LhsT> to func(x, y, lhs)

(x, y) allow for lhs.getXY0()

template<typename LhsT, typename RhsT>
void for_each_pixel(Image<LhsT> &lhs, Image<RhsT> const &rhs, pixelOp1<RhsT> const &func)

Parameters
  • lhs: Image to set

  • rhs: other Image to pass to func

  • func: functor to call

Set each pixel in an Image<LhsT> to func(rhs), getting the rhs from an Image<RhsT>

template<typename LhsT, typename RhsT>
void for_each_pixel(Image<LhsT> &lhs, Image<RhsT> const &rhs, pixelOp2<LhsT, RhsT> const &func)

Parameters
  • lhs: Image to set

  • rhs: other Image to pass to func

  • func: functor to call

Set each pixel in an Image<LhsT> to func(lhs, rhs), getting the rhs from an Image<RhsT>

template<typename LhsT, typename RhsT>
void for_each_pixel(Image<LhsT> &lhs, Image<RhsT> const &rhs, pixelOp2XY<LhsT, RhsT> const &func)

Parameters
  • lhs: Image to set

  • rhs: other Image to pass to func

  • func: functor to call

Set each pixel in an Image<LhsT> to func(x, y, lhs, rhs), getting the rhs from an Image<RhsT>

(x, y) allow for lhs.getXY0()

template<typename PixelT>
void swap(ImageBase<PixelT> &a, ImageBase<PixelT> &b)
template<typename Image1T, typename Image2T>
double innerProduct(Image1T const &lhs, Image2T const &rhs, int const border = 0)

Calculate the inner product of two images

Return

The inner product

Parameters
  • lhs: first image

  • rhs: Other image to dot with first

  • border: number of pixels to ignore around the edge

Exceptions
  • lsst::pex::exceptions::LengthError: if all the images aren’t the same size

template<typename PixelT>
std::shared_ptr<Image<PixelT>> operator+(Image<PixelT> const &img, ImageSlice<PixelT> const &slc)

Overload operator+()

We require two of these, one for image+slice (this one) and one for slice+image (next one down)

Parameters

template<typename PixelT>
std::shared_ptr<Image<PixelT>> operator+(ImageSlice<PixelT> const &slc, Image<PixelT> const &img)

Overload operator+()

We require two of these, one for image+slice (previous one) and one for slice+image (this)

Parameters

template<typename PixelT>
void operator+=(Image<PixelT> &img, ImageSlice<PixelT> const &slc)

Overload operator+=()

We’ll only allow ‘image += slice’. It doesn’t make sense to add an image to a slice.

Parameters

template<typename PixelT>
std::shared_ptr<Image<PixelT>> operator-(Image<PixelT> const &img, ImageSlice<PixelT> const &slc)

Overload operator-()

We’ll only allow ‘image - slice’, as ‘slice - image’ doesn’t make sense.

Parameters

template<typename PixelT>
void operator-=(Image<PixelT> &img, ImageSlice<PixelT> const &slc)

Overload operator-=()

Only ‘image -= slice’ is defined. ‘slice -= image’ wouldn’t make sense.

Parameters

template<typename PixelT>
std::shared_ptr<Image<PixelT>> operator*(Image<PixelT> const &img, ImageSlice<PixelT> const &slc)

Overload operator*()

We’ll define both ‘image*slice’ (this one) and ‘slice*image’ (next one down).

Parameters

template<typename PixelT>
std::shared_ptr<Image<PixelT>> operator*(ImageSlice<PixelT> const &slc, Image<PixelT> const &img)

Overload operator*()

We’ll define both ‘image*slice’ (this one) and ‘slice*image’ (next one down).

Parameters

template<typename PixelT>
void operator*=(Image<PixelT> &img, ImageSlice<PixelT> const &slc)

Overload operator*=()

Only ‘image *= slice’ is defined, as ‘slice *= image’ doesn’t make sense.

Parameters

template<typename PixelT>
std::shared_ptr<Image<PixelT>> operator/(Image<PixelT> const &img, ImageSlice<PixelT> const &slc)

Overload operator/()

Only ‘image / slice’ is defined, as ‘slice / image’ doesn’t make sense.

Parameters

template<typename PixelT>
void operator/=(Image<PixelT> &img, ImageSlice<PixelT> const &slc)

Overload operator/=()

Only ‘image /= slice’ is defined, as ‘slice /= image’ doesn’t make sense.

Parameters

double indexToPosition(double ind)

Parameters
  • ind: image index

Convert image index to image position

The LSST indexing convention is:

  • the index of the bottom left pixel is 0,0

  • the position of the center of the bottom left pixel is PixelZeroPos, PixelZeroPos

Return

image position

int positionToIndex(double pos)

Parameters
  • pos: image position

Convert image position to nearest integer index

The LSST indexing convention is:

  • the index of the bottom left pixel is 0,0

  • the position of the center of the bottom left pixel is PixelZeroPos, PixelZeroPos

Return

nearest integer index

int positionToIndex(double &residual, double pos)

Parameters
  • residual: fractional part of index

  • pos: image position

Convert image position to index (nearest integer and fractional parts)

The LSST indexing convention is:

  • the index of the bottom left pixel is 0,0

  • the position of the center of the bottom left pixel is PixelZeroPos, PixelZeroPos

Note: in python this is called positionToIndexAndResidual

Return

nearest integer index

std::pair<int, double> positionToIndex(double const pos, bool)

Parameters
  • pos: image position

Convert image position to index (nearest integer and fractional parts)

Return

std::pair(nearest integer index, fractional part)

template<typename PixelT>
void swap(Mask<PixelT> &a, Mask<PixelT> &b)
template<typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
MaskedImage<ImagePixelT, MaskPixelT, VariancePixelT> *makeMaskedImage(typename std::shared_ptr<Image<ImagePixelT>> image, typename std::shared_ptr<Mask<MaskPixelT>> mask = Mask<MaskPixelT>(), typename std::shared_ptr<Image<VariancePixelT>> variance = Image<VariancePixelT>())

Parameters
  • image: image

  • mask: mask

  • variance: variance

A function to return a MaskedImage of the correct type (cf. std::make_pair)

template<typename ImagePixelT1, typename ImagePixelT2>
bool imagesOverlap(MaskedImage<ImagePixelT1, MaskPixel, VariancePixel> const &image1, MaskedImage<ImagePixelT2, MaskPixel, VariancePixel> const &image2)

Return true if the pixels for two masked images (image, variance or mask plane) overlap in memory.

std::ostream &operator<<(std::ostream &os, Measurement const &measurement)
void assertNonNegative(double value, std::string const &name)

Raise lsst::pex::exceptions::InvalidParameterError if value is not >=0.

Used for checking the calibration mean/error in the constructor.

Parameters
  • value: Value that should be positive.

  • name: Text to prepend to error message.

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if value < 0

std::shared_ptr<PhotoCalib> makePhotoCalibFromMetadata(daf::base::PropertySet &metadata, bool strip = false)

Construct a PhotoCalib from FITS FLUXMAG0/FLUXMAG0ERR keywords.

This provides backwards compatibility with the obsoleted Calib object that PhotoCalib replaced. It should not be used outside of reading old Exposures written before PhotoCalib existed.

Return

Pointer to the constructed PhotoCalib, or nullptr if FLUXMAG0 is not in the metadata.

Parameters
  • metadata: FITS header metadata containing FLUXMAG0 and FLUXMAG0ERR keys.

  • strip: Strip FLUXMAG0 and FLUXMAG0ERR from metadata?

std::shared_ptr<PhotoCalib> makePhotoCalibFromCalibZeroPoint(double instFluxMag0, double instFluxMag0Err)

Construct a PhotoCalib from the deprecated Calib-style instFluxMag0/instFluxMag0Err values.

This provides backwards compatibility with the obsoleted Calib object that PhotoCalib replaced. It should not be used outside of tests that compare with old persisted Calib objects.

Return

Pointer to the constructed PhotoCalib.

Parameters
  • instFluxMag0: The instrumental flux at zero magnitude. If 0, the resulting PhotoCalib will have infinite calibrationMean and non-finite (inf or NaN) calibrationErr.

  • instFluxMag0Err: The instrumental flux at zero magnitude error. If 0, the resulting PhotoCalib will have 0 calibrationErr.

std::shared_ptr<daf::base::PropertyList> readMetadata(std::string const &fileName, int hdu = fits::DEFAULT_HDU, bool strip = false)

Return the metadata (header entries) from a FITS file.

Parameters
  • [in] fileName: File to read.

  • [in] hdu: HDU to read, 0-indexed. The special value of afw::fits::DEFAULT_HDU will read the first non-empty HDU.

  • [in] strip: If true, ignore special header keys usually managed by cfitsio (e.g. NAXIS).

template<typename ImageT>
ImageT::SinglePixel badPixel(typename ImageT::Pixel bad = 0)

Parameters
  • bad: The bad value if NaN isn’t supported

Return a value indicating a bad pixel for the given Image type

A quiet NaN is returned for types that support it otherwise bad

std::ostream &operator<<(std::ostream &os, VisitInfo const &visitInfo)

Variables

double const JanskysPerABFlux = 3631.0
const double PixelZeroPos = 0.0

position of center of pixel 0

FITS uses 1.0, SDSS uses 0.5, LSST uses 0.0 (http://dev.lsstcorp.org/trac/wiki/BottomLeftPixelProposalII%3A)

class ApCorrMap : public lsst::afw::table::io::PersistableFacade<ApCorrMap>, public Storable
#include <ApCorrMap.h>

A thin wrapper around std::map to allow aperture corrections to be attached to Exposures.

ApCorrMap simply adds error handling accessors, persistence, and a bit of encapsulation to std::map (given the simplified interface, for instance, we could switch to unordered_map or some other underyling container in the future).

class CheckIndices
#include <ImageBase.h>

A class used to request that array accesses be checked.

class CoaddInputs : public lsst::afw::table::io::PersistableFacade<CoaddInputs>, public Storable
#include <CoaddInputs.h>

A simple Persistable struct containing ExposureCatalogs that record the inputs to a coadd.

The visits catalog corresponds to what task code refers to as coaddTempExps, while the ccds catalog corresponds to individual input CCD images (calexps), and has a “visitId” column that points back to the visits catalog.

The records in the visits catalog will all have the same Wcs as the coadd, as they represent images that have already been warped to the coadd frame. Regardless of whether or not the coadd is PSF-matched, the visit record Psf will generally be CoaddPsfs (albeit single-depth ones, so they simply pick out the single non-coadd-Psf that is valid for each point).

class Color
#include <Color.h>

Describe the colour of a source

We need a concept of colour more general than “g - r” in order to calculate e.g. atmospheric dispersion or a source’s PSF

Note

This is very much just a place holder until we work out what we need. A full SED may be required, in which case a constructor from an SED name might be appropriate, or a couple of colours, or …

template<typename PixelT>
struct ConstReference
#include <ImageBase.h>

metafunction to extract const reference type from PixelT

template<typename PixelT>
class DecoratedImage
#include <Image.h>

A container for an Image and its associated metadata

class DefectBase
#include <Defect.h>

Encapsulate information about a bad portion of a detector

Subclassed by lsst::meas::algorithms::Defect

template<typename ImageT, typename MaskT = lsst::afw::image::MaskPixel, typename VarianceT = lsst::afw::image::VariancePixel>
class Exposure
#include <Exposure.h>

A class to contain the data, WCS, and other information needed to describe an image of the sky. Exposure Class Implementation for LSST: a templated framework class for creating an Exposure from a MaskedImage and a Wcs.

An Exposure is required to take one afwImage::MaskedImage or a region (col, row) defining the size of a MaskedImage (this can be of size 0,0). An Exposure can (but is not required to) contain an afwImage::SkyWcs.

The template types should optimally be a float, double, unsigned int 16 bit, or unsigned int 32 bit for the image (pixel) type and an unsigned int 32 bit for the mask type. These types have been explicitly instantiated for the Exposure class. All MaskedImage and Wcs constructors are ‘const’ to allow for views and copying.

An Exposure can get and return its MaskedImage, SkyWcs, and a subExposure. The getSubExposure member takes a BBox region defining the subRegion of the original Exposure to be returned. The member retrieves the MaskedImage corresponding to the subRegion. The MaskedImage class throws an exception for any subRegion extending beyond the original MaskedImage bounding box. This member is not yet fully implemented because it requires the SkyWcs class to return the SkyWcs metadata to the member so the CRPIX values of the SkyWcs can be adjusted to reflect the new subMaskedImage origin. The getSubExposure member will eventually return a subExposure consisting of the subMAskedImage and the SkyWcs object with its corresponding adjusted metadata.

The hasWcs member is used to determine if the Exposure has a SkyWcs. It is not required to have one.

class ExposureFitsReader
#include <ExposureFitsReader.h>

A FITS reader class for Exposures and their components.

All ExposureFitsReader methods provide strong exception safety, but exceptions thrown by the internal fits::Fits object itself may change its status variable or HDU pointer; ExposureFitsReader guards against this by resetting those before any use of the Fits object.

class ExposureInfo
#include <ExposureInfo.h>

A collection of all the things that make an Exposure different from a MaskedImage

The constness semantics of the things held by ExposureInfo are admittedly a bit of a mess, but they’re that way to preserve backwards compatibility for now. Eventually I’d like to make a lot of these things immutable, but in the meantime, here’s the summary:

  • Filter is held and returned by value.

  • VisitInfo is immutable and is held by a const ptr and has a setter and getter.

  • Metadata is held by non-const pointer, and you can get a non-const pointer via a const member function accessor (i.e. constness is not propagated).

  • all other types are only accessible through non-const pointers

The setter for Wcs clones its input arguments (this is a departure from the previous behavior for Wcs but it’s safer w.r.t. aliasing and it matches the old (and current) behavior of the Exposure and ExposureInfo constructors, which clone their arguments. The setter for Psf and constructors do not clone the Psf, as Psfs are immutable and hence we don’t need to ensure strict ownership. The setter for Detector does not clone its input argument, because while it technically isn’t, we can safely consider a Detector to be immutable once it’s attached to an ExposureInfo.

class Filter : public Storable
#include <Filter.h>

Holds an integer identifier for an LSST filter.

class FilterProperty
#include <Filter.h>

Describe the properties of a Filter (e.g. effective wavelength)

template<typename PixelT>
class Image : public lsst::afw::image::ImageBase<PixelT>
#include <Image.h>

A class to represent a 2-dimensional array of pixels.

Subclassed by lsst::afw::image::ImageSlice< PixelT >

template<typename PixelT>
class ImageBase
#include <ImageBase.h>

The base class for all image classed (Image, Mask, MaskedImage, …)

Subclassed by lsst::afw::image::Image< lsst::afw::math::Kernel::Pixel >, lsst::afw::image::Image< Pixel >, lsst::afw::image::Image< PixelT >

class ImageBaseFitsReader
#include <ImageBaseFitsReader.h>

Base class for image FITS readers.

This class should be considered an implementation detail of ImageFitsReader and MaskFitsReader that provides their common methods, not the definition of an interface.

All ImageBaseFitsReader methods provide strong exception safety, but exceptions thrown by the internal fits::Fits object itself may change its status variable or HDU pointer; ImageBaseFitsReader guards against this by resetting those before any use of the Fits object.

Subclassed by lsst::afw::image::ImageFitsReader, lsst::afw::image::MaskFitsReader

class ImageFitsReader : public lsst::afw::image::ImageBaseFitsReader
#include <ImageFitsReader.h>

A FITS reader class for regular Images.

All ImageFitsReader methods provide strong exception safety, but exceptions thrown by the internal fits::Fits object itself may change its status variable or HDU pointer; ImageFitsReader guards against this by resetting those before any use of the Fits object.

template<typename ImageT>
class ImagePca

Subclassed by lsst::ip::diffim::detail::KernelPca< ImageT >, lsst::meas::algorithms::PsfImagePca< ImageT >

template<typename PixelT>
class ImageSlice : public lsst::afw::image::Image<PixelT>
#include <ImageSlice.h>

A class to specify a slice of an image

template<typename MaskPixelT = lsst::afw::image::MaskPixel>
class Mask : public lsst::afw::image::ImageBase<MaskPixelT>
#include <Mask.h>

Represent a 2-dimensional array of bitmask pixels

Some mask planes are always defined (although you can add more with Mask::addMaskPlane):

  • BAD This pixel is known to be bad (e.g. the amplifier is not working)

  • CR This pixel is contaminated by a cosmic ray

  • DETECTED This pixel lies within an object’s Footprint

  • DETECTED_NEGATIVE This pixel lies within an object’s Footprint, and the detection was looking for pixels below a specified level

  • EDGE This pixel is too close to the edge to be processed properly

  • INTRP This pixel has been interpolated over

    Note

    should be called INTERPOLATED

  • SAT This pixel is saturated and has bloomed

    Note

    should be called SATURATED

  • SUSPECT This pixel is untrustworthy, and you may wish to discard any Source containing it

template<typename ImagePixelT, typename MaskPixelT = lsst::afw::image::MaskPixel, typename VariancePixelT = lsst::afw::image::VariancePixel>
class MaskedImage
#include <MaskedImage.h>

A class to manipulate images, masks, and variance as a single object.

class MaskedImageFitsReader
#include <MaskedImageFitsReader.h>

A FITS reader class for MaskedImages and their components.

All MaskedImageFitsReader methods provide strong exception safety, but exceptions thrown by the internal fits::Fits object itself may change its status variable or HDU pointer; MaskedImageFitsReader guards against this by resetting those before any use of the Fits object.

class MaskFitsReader : public lsst::afw::image::ImageBaseFitsReader
#include <MaskFitsReader.h>

A FITS reader class for Masks.

All MaskFitsReader methods provide strong exception safety, but exceptions thrown by the internal fits::Fits object itself may change its status variable or HDU pointer; MaskFitsReader guards against this by resetting those before any use of the Fits object.

struct Measurement
#include <PhotoCalib.h>

A value and its error.

class PhotoCalib : public lsst::afw::table::io::PersistableFacade<PhotoCalib>, public Storable
#include <PhotoCalib.h>

The photometric calibration of an exposure.

A PhotoCalib is a BoundedField (a function with a specified domain) that converts from post-ISR counts-on-chip (ADU) to flux and magnitude. It is defined such that a calibration of 1 means one count is equal to one nanojansky (nJy, 10^-35 W/m^2/Hz in SI units). The nJy was chosen because it represents a linear flux unit with values in a convenient range (e.g. LSST’s single image depth of 24.5 is 575 nJy). See more detailed discussion in: https://pstn-001.lsst.io/

PhotoCalib is immutable.

The spatially varying flux calibration has units of nJy/ADU, and is defined such that, at a position (x,y) in the domain of the boundedField calibration and for a given measured source instFlux:

\[ instFlux*calibration(x,y) = flux [nJy] \]
while the errors (constant on the domain) are defined as:
\[ sqrt((instFluxErr/instFlux)^2 + (calibrationErr/calibration)^2)*flux = fluxErr [nJy] \]
This implies that the conversions from instFlux and instFlux error to magnitude and magnitude error are as follows:
\[ -2.5*log_{10}(instFlux*calibration(x,y)*1e-9/referenceFlux) = magnitude \]

where referenceFlux is the AB Magnitude reference flux from Oke & Gunn 1983 (first equation),

\[ referenceFlux = 1e23 * 10^{(48.6/-2.5)} \]
and
\[ 2.5/log(10)*sqrt((instFluxErr/instFlux)^2 + (calibrationErr/calibration)^2) = magnitudeErr \]
Note that this is independent of referenceFlux.

template<typename ValT>
struct pixelOp0 : public std::function<ValT()>
#include <ImageAlgorithm.h>

A functor class equivalent to std::function<ValT ()>, but with a virtual operator()

template<typename ValT>
struct pixelOp1 : public std::function<ValT(ValT)>
#include <ImageAlgorithm.h>

A functor class equivalent to std::function<ValT (ValT)>, but with a virtual operator()

template<typename ValT>
struct pixelOp1XY : public std::function<ValT(int, int, ValT)>
#include <ImageAlgorithm.h>

A functor class equivalent to std::function<ValT (int, int, ValT)>, but with a virtual operator()

template<typename LhsT, typename RhsT>
struct pixelOp2 : public std::function<LhsT(LhsT, RhsT)>
#include <ImageAlgorithm.h>

A functor class equivalent to std::function<LhsT (LhsT, RhsT)>, but with a virtual operator()

template<typename LhsT, typename RhsT>
struct pixelOp2XY : public std::function<LhsT(int, int, LhsT, RhsT)>
#include <ImageAlgorithm.h>

A functor class equivalent to std::function<LhsT (int, int, LhsT, RhsT)>, but with a virtual operator()

template<typename PixelT>
struct Reference
#include <ImageBase.h>

metafunction to extract reference type from PixelT

class TransmissionCurve : public lsst::afw::table::io::PersistableFacade<TransmissionCurve>, public Storable, public std::enable_shared_from_this<TransmissionCurve>
#include <TransmissionCurve.h>

A spatially-varying transmission curve as a function of wavelength.

TransmissionCurve can only be evaluated at discrete (albeit arbitrary) user-provided positions; it does not provide an interface for computing average transmission over regions or computing spatially-varying scalars from integrals over the wavelength dimension.

TransmissionCurves are immutable and are expected to be passed and held by shared_ptr<TransmissionCurve const>. As such they are neither copyable nor movable (because there should be no need to copy or move).

All wavelength values should be in Angstroms.

The flux units and overall normalization of TransmissionCurves is unspecified by the class, but their normalization and units should always be consistent throughout the spatial area over which they are defined (an implementation should not e.g. re-normalize to unit bolometric flux at each position it is evaluated at). Other classes and functions using TransmissionCurves should of course document the flux units and/or normalization expected/provided.

class VisitInfo : public lsst::afw::table::io::PersistableFacade<VisitInfo>, public Storable
#include <VisitInfo.h>

Information about a single exposure of an imaging camera.

Includes exposure duration and date, and telescope pointing and orientation.

All information is for the middle of the exposure and at the boresight (center of the focal plane). Thus for a mosaic camera VisitInfo is the same for all detectors in the mosaic.

VisitInfo is immutable.

namespace detail

Typedefs

typedef std::map<std::string, int> MaskPlaneDict

Functions

int stripFilterKeywords(std::shared_ptr<lsst::daf::base::PropertySet> metadata)

Remove Filter-related keywords from the metadata

Return

Number of keywords stripped

Parameters
  • [inout] metadata: Metadata to be stripped

void setVisitInfoMetadata(daf::base::PropertyList &metadata, VisitInfo const &visitInfo)

Set FITS metadata from a VisitInfo

Parameters
  • [inout] metadata: FITS keyword metadata to set

  • [in] visitInfo: instance of VisitInfo from which to set metadata

int stripVisitInfoKeywords(daf::base::PropertySet &metadata)

Remove VisitInfo-related keywords from the metadata

Return

Number of keywords stripped

Parameters
  • [inout] metadata: FITS keyword metadata

Variables

std::string const wcsNameForXY0 = "A"
std::string const fitsFile_RE = "\.fits(\.[fg]z)?$"

regexp to identify when MaskedImages should be written as MEFs

std::string const compressedFileNoMEF_RE = "(\.gz)$"

regexp to identify compressed files that we can’t write MEFs to

struct basic_tag
#include <ImageBase.h>

Base image tag.

Subclassed by lsst::afw::image::detail::Image_tag, lsst::afw::image::detail::Mask_tag, lsst::afw::image::detail::MaskedImage_tag

struct Image_tag : public lsst::afw::image::detail::basic_tag
#include <ImageBase.h>

tag for an Image

template<typename ImageT>
struct image_traits
#include <ImageBase.h>

traits class for image categories

struct Mask_tag : public lsst::afw::image::detail::basic_tag
#include <Mask.h>

tag for a Mask

struct MaskedImage_tag : public lsst::afw::image::detail::basic_tag
#include <MaskedImage.h>

A traits class for MaskedImage.

struct MaskedImagePixel_tag
#include <MaskedImage.h>

A class used to identify classes that represent MaskedImage pixels.

Subclassed by lsst::afw::image::pixel::Pixel< _ImagePixelT, _MaskPixelT, _VariancePixelT >, lsst::afw::image::pixel::SinglePixel< _ImagePixelT, _MaskPixelT, _VariancePixelT >

class StorableMap
#include <StorableMap.h>

A map of Storable supporting strongly-typed access.

A Key for the map is parameterized by both the key type K and a corresponding value type V. The map is indexed uniquely by a value of type K; no two entries in the map may have identical values of Key::getId().

All operations are sensitive to the value type of the key: a contains call requesting a SkyWcs labeled “value”, for example, will report no such object if instead there is a Psf labeled “value”. At present, a StorableMap does not store type information internally, instead relying on RTTI for type checking.

namespace details

Functions

template<typename OperatorT, typename PixelT>
void operate(Image<PixelT> &img, ImageSlice<PixelT> const &slc, typename ImageSlice<PixelT>::ImageSliceType sliceType)

A function to loop over pixels and perform the requested operation

namespace pixel

Functions

template<typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
SinglePixel<ImagePixelT, MaskPixelT, VariancePixelT> makeSinglePixel(ImagePixelT x, MaskPixelT m, VariancePixelT v)

Return a SinglePixel

This function is useful as function overloading will choose the correct return type (cf. std::make_pair()

template<typename ExprT1>
UnaryExpr<ExprT1, std::negate<typename exprTraits<ExprT1>::ImagePixelT>, noop<typename exprTraits<ExprT1>::MaskPixelT>, noop<typename exprTraits<ExprT1>::VariancePixelT>> operator-(ExprT1 e1)

Template for -e1.

template<typename ExprT1, typename ExprT2>
BinaryExpr<ExprT1, ExprT2, std::plus<typename exprTraits<ExprT1>::ImagePixelT>, bitwise_or<typename exprTraits<ExprT1>::MaskPixelT>, variance_plus<typename exprTraits<ExprT1>::VariancePixelT>> operator+(ExprT1 e1, ExprT2 e2)

Template for (e1 + e2)

template<typename ExprT1, typename ExprT2>
ExprT1 operator+=(ExprT1 &e1, ExprT2 e2)

template for e1 += e2

template<typename ExprT1, typename ExprT2>
ExprT1 plus(ExprT1 &lhs, ExprT2 const &rhs, float covariance)

Like operator+(), but assume that covariance’s 2*alpha*sqrt(vx*vy)

Parameters
  • lhs: Left hand value

  • rhs: Right hand value

  • covariance: Assume that covariance is 2*alpha*sqrt(vx*vy) (if variances are known)

template<typename ExprT1, typename ExprT2>
BinaryExpr<ExprT1, ExprT2, std::minus<typename exprTraits<ExprT1>::ImagePixelT>, bitwise_or<typename exprTraits<ExprT1>::MaskPixelT>, variance_plus<typename exprTraits<ExprT1>::VariancePixelT>> operator-(ExprT1 e1, ExprT2 e2)

Template to evaluate (e1 - e2)

template<typename ExprT1, typename ExprT2>
ExprT1 operator-=(ExprT1 &e1, ExprT2 e2)

Template to evaluate e1 -= e2.

template<typename ExprT1, typename ExprT2>
BinaryExpr<ExprT1, ExprT2, std::multiplies<typename exprTraits<ExprT1>::ImagePixelT>, bitwise_or<typename exprTraits<ExprT1>::MaskPixelT>, variance_multiplies<typename exprTraits<ExprT1>::VariancePixelT>> operator*(ExprT1 e1, ExprT2 e2)

Template to evaluate (e1 * e2)

template<typename ExprT1, typename ExprT2>
ExprT1 operator*=(ExprT1 &e1, ExprT2 e2)

Template to evaluate e1 *= e2.

template<typename ExprT1, typename ExprT2>
BinaryExpr<ExprT1, ExprT2, std::divides<typename exprTraits<ExprT1>::ImagePixelT>, bitwise_or<typename exprTraits<ExprT1>::MaskPixelT>, variance_divides<typename exprTraits<ExprT1>::VariancePixelT>> operator/(ExprT1 e1, ExprT2 e2)

Template to evaluate (e1 / e2)

template<typename ExprT1, typename ExprT2>
ExprT1 operator/=(ExprT1 &e1, ExprT2 e2)

Template to evaluate e1 /= e2.

template<typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
std::ostream &operator<<(std::ostream &os, SinglePixel<ImagePixelT, MaskPixelT, VariancePixelT> const &v)

Print a SinglePixel.

template<typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
std::ostream &operator<<(std::ostream &os, Pixel<ImagePixelT, MaskPixelT, VariancePixelT> const &v)

Print a Pixel.

template<typename ExprT1, typename ExprT2, typename BinOp, typename MaskBinOp, typename VarBinOp>
std::ostream &operator<<(std::ostream &os, BinaryExpr<ExprT1, ExprT2, BinOp, MaskBinOp, VarBinOp> const &v)

Evaluate and print a BinaryExpr.

template<typename ExprT1, typename ExprT2, typename ImageBinOp, typename MaskBinOp, typename VarianceBinOp>
class BinaryExpr
#include <Pixel.h>

Class for representing binary operations.

template<typename ExprT1, typename ImageBinOp, typename MaskBinOp, typename VarianceBinOp>
class BinaryExpr<ExprT1, double, ImageBinOp, MaskBinOp, VarianceBinOp>
#include <Pixel.h>

Partial specialization of BinaryExpr when ExprT2 is a double (i.e no mask/variance part)

template<typename T1>
struct bitwise_or : public std::binary_function<T1, T1, T1>
#include <Pixel.h>

bitwise_or doesn’t seem to be in std::

Note

We provide a single-operand version for when the right-hand-side of an expression is a scalar, not a masked pixel,

template<typename ExprT>
struct exprTraits
#include <Pixel.h>

A traits class to return the types of the image/mask/variance.

template<>
struct exprTraits<double>
#include <Pixel.h>

A specialisation of exprTraits for double

template<>
struct exprTraits<float>
#include <Pixel.h>

A specialisation of exprTraits for float

template<>
struct exprTraits<int>
#include <Pixel.h>

A specialisation of exprTraits for int

template<>
struct exprTraits<unsigned short>
#include <Pixel.h>

A specialisation of exprTraits for unsigned short

template<typename T1>
struct noop : public std::unary_function<T1, T1>
#include <Pixel.h>

A noop functor (useful for e.g. masks and variances when changing the sign of the image)

template<typename _ImagePixelT, typename _MaskPixelT, typename _VariancePixelT = double>
class Pixel : public lsst::afw::image::detail::MaskedImagePixel_tag
#include <Pixel.h>

A pixel of a MaskedImage.

template<typename PixelT>
struct PixelTypeTraits
#include <Pixel.h>

Pixel type traits.

template<typename _ImagePixelT, typename _MaskPixelT, typename _VariancePixelT>
struct PixelTypeTraits<SinglePixel<_ImagePixelT, _MaskPixelT, _VariancePixelT>>
#include <Pixel.h>

Specialization for a pixel of a MaskedImage.

template<typename _ImagePixelT, typename _MaskPixelT, typename _VariancePixelT = double>
class SinglePixel : public lsst::afw::image::detail::MaskedImagePixel_tag
#include <Pixel.h>

A single pixel of the same type as a MaskedImage.

template<typename ExprT1, typename ImageBinOp, typename MaskBinOp, typename VarianceBinOp>
class UnaryExpr
#include <Pixel.h>

Class for representing Unary operations.

template<typename T1>
struct variance_divides
#include <Pixel.h>

Calculate the variance when we divide two Pixels

Note

We provide a single-operand version for when the right-hand-side of an expression is a scalar, not a masked pixel,

template<typename T1>
struct variance_multiplies
#include <Pixel.h>

Calculate the variance when we multiply two Pixels

Note

We provide a single-operand version for when the right-hand-side of an expression is a scalar, not a masked pixel,

template<typename T1>
struct variance_plus
#include <Pixel.h>

Calculate the variance when we add (or subtract) two Pixels

Note

We provide a single-operand version for when the right-hand-side of an expression is a scalar, not a masked pixel,

template<typename T1>
struct variance_plus_covar
#include <Pixel.h>

The variance of the sum of a pair of correlated pixels

The covariance is modelled as alpha*sqrt(var_x*var_y)

Note

We provide a single-operand version for when the right-hand-side of an expression is a scalar, not a masked pixel,

namespace python

Functions

void checkBounds(geom::Point2I const &index, geom::Box2I const &bbox)
namespace math

Typedefs

typedef std::vector<std::shared_ptr<Kernel>> KernelList
typedef lsst::afw::image::VariancePixel WeightPixel

Enums

enum UndersampleStyle

Values:

THROW_EXCEPTION
REDUCE_INTERP_ORDER
INCREASE_NXNYSAMPLE
enum Property

control what is calculated

Values:

NOTHING = 0x0

We don’t want anything.

ERRORS = 0x1

Include errors of requested quantities.

NPOINT = 0x2

number of sample points

MEAN = 0x4

estimate sample mean

STDEV = 0x8

estimate sample standard deviation

VARIANCE = 0x10

estimate sample variance

MEDIAN = 0x20

estimate sample median

IQRANGE = 0x40

estimate sample inter-quartile range

MEANCLIP = 0x80

estimate sample N-sigma clipped mean (N set in StatisticsControl, default=3)

STDEVCLIP = 0x100

estimate sample N-sigma clipped stdev (N set in StatisticsControl, default=3)

VARIANCECLIP = 0x200

estimate sample N-sigma clipped variance (N set in StatisticsControl, default=3)

MIN = 0x400

estimate sample minimum

MAX = 0x800

estimate sample maximum

SUM = 0x1000

find sum of pixels in the image

MEANSQUARE = 0x2000

find mean value of square of pixel values

ORMASK = 0x4000

get the or-mask of all pixels used.

NCLIPPED = 0x8000

number of clipped points

NMASKED = 0x10000

number of masked points

Functions

template<typename PixelT>
std::shared_ptr<Approximate<PixelT>> makeApproximate(std::vector<double> const &x, std::vector<double> const &y, image::MaskedImage<PixelT> const &im, lsst::geom::Box2I const &bbox, ApproximateControl const &ctrl)

Construct a new Approximate object, inferring the type from the type of the given MaskedImage.

Parameters
  • x: the x-values of points

  • y: the y-values of points

  • im: The values at (x, y)

  • bbox: Range where approximation should be valid

  • ctrl: desired approximation algorithm

UndersampleStyle stringToUndersampleStyle(std::string const &style)

Conversion function to switch a string to an UndersampleStyle

template<typename ImageT>
std::shared_ptr<Background> makeBackground(ImageT const &img, BackgroundControl const &bgCtrl)

A convenience function that uses function overloading to make the correct type of Background

cf. std::make_pair()

std::shared_ptr<BoundedField> operator*(double const scale, std::shared_ptr<BoundedField const> bf)
template<typename OutImageT, typename InImageT>
void scaledPlus(OutImageT &outImage, double c1, InImageT const &inImage1, double c2, InImageT const &inImage2)

Compute the scaled sum of two images

outImage = c1 inImage1 + c2 inImage2

For example to linearly interpolate between two images set: c1 = 1.0 - fracDist c2 = fracDist where fracDist is the fractional distance of outImage from inImage1: location of outImage - location of inImage1 fracDist = —————————————- location of inImage2 - location of inImage1

Parameters
  • [out] outImage: output image

  • [in] c1: coefficient for image 1

  • [in] inImage1: input image 1

  • [in] c2: coefficient for image 2

  • [in] inImage2: input image 2

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if outImage is not same dimensions as inImage1 and inImage2.

template<typename OutImageT, typename InImageT>
OutImageT::SinglePixel convolveAtAPoint(typename InImageT::const_xy_locator inImageLocator, typename lsst::afw::image::Image<lsst::afw::math::Kernel::Pixel>::const_xy_locator kernelLocator, int kWidth, int kHeight)

Apply convolution kernel to an image at one point

Note

This subroutine sacrifices convenience for performance. The user is expected to figure out the kernel center and adjust the supplied pixel accessors accordingly. For an example of how to do this see convolve().

Parameters
  • inImageLocator: locator for image pixel that overlaps pixel (0,0) of kernel (the origin of the kernel, not its center)

  • kernelLocator: locator for (0,0) pixel of kernel (the origin of the kernel, not its center)

  • kWidth: number of columns in kernel

  • kHeight: number of rows in kernel

template<typename OutImageT, typename InImageT>
OutImageT::SinglePixel convolveAtAPoint(typename InImageT::const_xy_locator inImageLocator, std::vector<lsst::afw::math::Kernel::Pixel> const &kernelColList, std::vector<lsst::afw::math::Kernel::Pixel> const &kernelRowList)

Apply separable convolution kernel to an image at one point

Note

This subroutine sacrifices convenience for performance. The user is expected to figure out the kernel center and adjust the supplied pixel accessors accordingly. For an example of how to do this see convolve().

Parameters
  • inImageLocator: locator for image pixel that overlaps pixel (0,0) of kernel (the origin of the kernel, not its center)

  • kernelXList: kernel column vector

  • kernelYList: kernel row vector

template<typename OutImageT, typename InImageT, typename KernelT>
void convolve(OutImageT &convolvedImage, InImageT const &inImage, KernelT const &kernel, ConvolutionControl const &convolutionControl = ConvolutionControl())

Convolve an Image or MaskedImage with a Kernel, setting pixels of an existing output image.

Various convolution kernels are available, including:

If a kernel is spatially varying, its spatial model is computed at each pixel position on the image (pixel position, not pixel index). At present (2009-09-24) this position is computed relative to the lower left corner of the sub-image, but it will almost certainly change to be the lower left corner of the parent image.

All convolution is performed in real space. This allows convolution to handle masked pixels and spatially varying kernels. Although convolution of an Image with a spatially invariant kernel could, in fact, be performed in Fourier space, the code does not do this.

Note that mask bits are smeared by convolution; all nonzero pixels in the kernel smear the mask, even pixels that have very small values. Larger kernels smear the mask more and are also slower to convolve. Use the smallest kernel that will do the job.

convolvedImage has a border of edge pixels which cannot be computed normally. Normally these pixels are set to the standard edge pixel, as returned by edgePixel(). However, if your code cannot handle nans in the image or infs in the variance, you may set doCopyEdge true, in which case the edge pixels are set to the corresponding pixels of the input image and (if there is a mask) the mask EDGE bit is set.

The border of edge pixels has size:

  • kernel.getCtrX() along the left edge

  • kernel.getCtrY() along the bottom edge

  • kernel.getWidth() - 1 - kernel.getCtrX() along the right edge

  • kernel.getHeight() - 1 - kernel.getCtrY() along the top edge You can obtain a bounding box for the good pixels in the convolved image from a bounding box for the entire image using the Kernel method shrinkBBox.

Convolution has been optimized for the various kinds of kernels, as follows (listed approximately in order of decreasing speed):

  • DeltaFunctionKernel convolution is a simple image shift.

  • SeparableKernel convolution is performed by convolving the input by one of the two functions, then the result by the other function. Thus convolution with a kernel of size nCols x nRows becomes convolution with a kernel of size nCols x 1, followed by convolution with a kernel of size 1 x nRows.

  • Convolution with spatially invariant versions of the other kernels is performed by computing the kernel image once and convolving with that. The code has been optimized for cache performance and so should be fairly efficient.

  • Convolution with a spatially varying LinearCombinationKernel is performed by convolving the image by each basis kernel and combining the result by solving the spatial model. This will be efficient provided the kernel does not contain too many or very large basis kernels.

  • Convolution with spatially varying AnalyticKernel is likely to be slow. The code simply computes the output one pixel at a time by computing the AnalyticKernel at that point and applying it to the input image. This is not favorable for cache performance (especially for large kernels) but avoids recomputing the AnalyticKernel. It is probably possible to do better.

Additional convolution functions include:

  • convolveAtAPoint(): convolve a Kernel to an Image or MaskedImage at a point.

  • basicConvolve(): convolve a Kernel with an Image or MaskedImage, but do not set the edge pixels of the output. Optimization of convolution for different types of Kernel are handled by different specializations of basicConvolve().

afw/examples offers programs that time convolution including timeConvolve and timeSpatiallyVaryingConvolve.

Parameters
  • [out] convolvedImage: convolved image; must be the same size as inImage

  • [in] inImage: image to convolve

  • [in] kernel: convolution kernel

  • [in] convolutionControl: convolution control parameters

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if convolvedImage is not the same size as inImage

  • lsst::pex::exceptions::InvalidParameterError: if inImage is smaller than kernel in columns and/or rows.

  • std::bad_alloc: when allocation of memory fails

template<typename OutImageT, typename InImageT, typename KernelT>
void convolve(OutImageT &convolvedImage, InImageT const &inImage, KernelT const &kernel, bool doNormalize, bool doCopyEdge = false)

Old, deprecated version of convolve.

Parameters
  • [out] convolvedImage: convolved image; must be the same size as inImage

  • [in] inImage: image to convolve

  • [in] kernel: convolution kernel

  • [in] doNormalize: if true, normalize the kernel, else use “as is”

  • [in] doCopyEdge: if false (default), set edge pixels to the standard edge pixel; if true, copy edge pixels from input and set EDGE bit of mask

template<typename ImageT>
ImageT::SinglePixel edgePixel(lsst::afw::image::detail::Image_tag)

Return an off-the-edge pixel appropriate for a given Image type

The value is quiet_NaN if that exists for the pixel type, else 0

template<typename MaskedImageT>
MaskedImageT::SinglePixel edgePixel(lsst::afw::image::detail::MaskedImage_tag)

Return an off-the-edge pixel appropriate for a given MaskedImage type

The components are:

  • image = quiet_NaN if that exists for the pixel type, else 0

  • mask = NO_DATA bit set

  • variance = infinity if that exists for the pixel type, else 0

Exceptions
  • lsst::pex::exceptions::LogicError: Thrown if the global mask plane dictionary does not have a NO_DATA bit.

template<typename OutImageT, typename InImageT>
OutImageT::SinglePixel convolveAtAPoint(typename InImageT::const_xy_locator inImageLocator, std::vector<Kernel::Pixel> const &kernelXList, std::vector<Kernel::Pixel> const &kernelYList)

Apply separable convolution kernel to an image at one point

Note

This subroutine sacrifices convenience for performance. The user is expected to figure out the kernel center and adjust the supplied pixel accessors accordingly. For an example of how to do this see convolve().

Parameters
  • inImageLocator: locator for image pixel that overlaps pixel (0,0) of kernel (the origin of the kernel, not its center)

  • kernelXList: kernel column vector

  • kernelYList: kernel row vector

template<class UF>
UF::result_type int1d(UF const &func, IntRegion<typename UF::result_type> &reg, typename UF::result_type const &abserr = DEFABSERR, typename UF::result_type const &relerr = DEFRELERR)

Front end for the 1d integrator

template<class BF, class YREG>
BF::result_type int2d(BF const &func, IntRegion<typename BF::result_type> &reg, YREG const &yreg, typename BF::result_type const &abserr = DEFABSERR, typename BF::result_type const &relerr = DEFRELERR)

Front end for the 2d integrator

template<class TF, class YREG, class ZREG>
TF::result_type int3d(TF const &func, IntRegion<typename TF::result_type> &reg, YREG const &yreg, ZREG const &zreg, typename TF::result_type const &abserr = DEFABSERR, typename TF::result_type const &relerr = DEFRELERR)

Front end for the 3d integrator

template<class BF>
BF::result_type int2d(BF const &func, IntRegion<typename BF::result_type> &reg, IntRegion<typename BF::result_type> &yreg, typename BF::result_type const &abserr = DEFABSERR, typename BF::result_type const &relerr = DEFRELERR)

Front end for the 2d integrator

template<class TF>
TF::result_type int3d(TF const &func, IntRegion<typename TF::result_type> &reg, IntRegion<typename TF::result_type> &yreg, IntRegion<typename TF::result_type> &zreg, typename TF::result_type const &abserr = DEFABSERR, typename TF::result_type const &relerr = DEFRELERR)

Front end for the 3d integrator

template<typename UnaryFunctionT>
UnaryFunctionT::result_type integrate(UnaryFunctionT func, typename UnaryFunctionT::argument_type const a, typename UnaryFunctionT::argument_type const b, double eps = 1.0e-6)

The 1D integrator

Note

This simply wraps the int1d function above and handles the instantiation of the intRegion.

template<typename BinaryFunctionT>
BinaryFunctionT::result_type integrate2d(BinaryFunctionT func, typename BinaryFunctionT::first_argument_type const x1, typename BinaryFunctionT::first_argument_type const x2, typename BinaryFunctionT::second_argument_type const y1, typename BinaryFunctionT::second_argument_type const y2, double eps = 1.0e-6)

The 2D integrator

Note

Adapted from RHL’s SDSS code

std::shared_ptr<Interpolate> makeInterpolate(std::vector<double> const &x, std::vector<double> const &y, Interpolate::Style const style = Interpolate::AKIMA_SPLINE)

A factory function to make Interpolate objects

Parameters
  • x: the x-values of points

  • y: the values at x[]

  • style: desired interpolator

std::shared_ptr<Interpolate> makeInterpolate(ndarray::Array<double const, 1> const &x, ndarray::Array<double const, 1> const &y, Interpolate::Style const style = Interpolate::AKIMA_SPLINE)
Interpolate::Style stringToInterpStyle(std::string const &style)

Conversion function to switch a string to an Interpolate::Style.

Parameters
  • style: desired type of interpolation

Interpolate::Style lookupMaxInterpStyle(int const n)

Get the highest order Interpolation::Style available for ‘n’ points.

Parameters
  • n: Number of points

int lookupMinInterpPoints(Interpolate::Style const style)

Get the minimum number of points needed to use the requested interpolation style

Parameters
  • style: The style in question

void printKernel(lsst::afw::math::Kernel const &kernel, bool doNormalize, double x = 0, double y = 0, std::string pixelFmt = "%7.3f")

Print the pixel values of a Kernel to std::cout

Rows increase upward and columns to the right; thus the lower left pixel is (0,0).

Parameters
  • kernel: the kernel

  • doNormalize: if true, normalize kernel

  • x: x at which to evaluate kernel

  • y: y at which to evaluate kernel

  • pixelFmt: format for pixel values

template<typename ReturnT>
FitResults minimize(lsst::afw::math::Function1<ReturnT> const &function, std::vector<double> const &initialParameterList, std::vector<double> const &stepSizeList, std::vector<double> const &measurementList, std::vector<double> const &varianceList, std::vector<double> const &xPositionList, double errorDef)

Find the minimum of a function(x)

Uses the Minuit fitting package with a standard definition of chiSq (see MinimizerFunctionBase1).

Return

true if minimum is valid, false otherwise

Parameters
  • function: function(x) to be minimized

  • initialParameterList: initial guess for parameters

  • stepSizeList: step size for each parameter; use 0.0 to fix a parameter

  • measurementList: measured values

  • varianceList: variance for each measurement

  • xPositionList: x position of each measurement

  • errorDef: what is this?

To do:

  • Document stepSizeList better

  • Document errorDef

  • Compute stepSize automatically? (if so, find a different way to fix parameters)

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if any input vector is the wrong length

template<typename ReturnT>
FitResults minimize(lsst::afw::math::Function2<ReturnT> const &function, std::vector<double> const &initialParameterList, std::vector<double> const &stepSizeList, std::vector<double> const &measurementList, std::vector<double> const &varianceList, std::vector<double> const &xPositionList, std::vector<double> const &yPositionList, double errorDef)

Find the minimum of a function(x, y)

Uses the Minuit fitting package with a standard definition of chiSq. (see MinimizerFunctionBase2).

To do:

  • Document stepSizeList better

  • Document errorDef

  • Compute stepSize automatically? (if so, find a different way to fix parameters)

Return

true if minimum is valid, false otherwise

Parameters
  • function: function(x,y) to be minimized

  • initialParameterList: initial guess for parameters

  • stepSizeList: step size for each parameter; use 0.0 to fix a parameter

  • measurementList: measured values

  • varianceList: variance for each measurement

  • xPositionList: x position of each measurement

  • yPositionList: y position of each measurement

  • errorDef: what is this?

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if any input vector is the wrong length

template<typename ImageT>
std::shared_ptr<ImageT> offsetImage(ImageT const &image, float dx, float dy, std::string const &algorithmName = "lanczos5", unsigned int buffer = 0)

Return an image offset by (dx, dy) using the specified algorithm

Note

The image pixels are always offset by a fraction of a pixel and the image origin (XY0) picks is modified to handle the integer portion of the offset. In the special case that the offset in both x and y lies in the range (-1, 1) the origin is not changed. Otherwise the pixels are shifted by (-0.5, 0.5] pixels and the origin shifted accordingly.

Parameters
  • image: The image to offset

  • dx: move the image this far in the column direction

  • dy: move the image this far in the row direction

  • algorithmName: Type of resampling Kernel to use

  • buffer: Width of buffer (border) around kernel image to allow for warping edge effects (pixels). Values < 0 are treated as 0. This is only used during computation; the final image has the same dimensions as the kernel.

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if the algorithm is invalid

template<typename ImageT>
std::shared_ptr<ImageT> rotateImageBy90(ImageT const &image, int nQuarter)

Rotate an image by an integral number of quarter turns

Parameters
  • image: The image to rotate

  • nQuarter: the desired number of quarter turns

template<typename ImageT>
std::shared_ptr<ImageT> flipImage(ImageT const &inImage, bool flipLR, bool flipTB)

Flip an image leftright and/or topbottom

Parameters
  • inImage: The image to flip

  • flipLR: Flip left <> right?

  • flipTB: Flip top <> bottom?

template<typename ImageT>
std::shared_ptr<ImageT> binImage(ImageT const &inImage, int const binX, int const binY, lsst::afw::math::Property const flags = lsst::afw::math::MEAN)

Parameters
  • inImage: The image to bin

  • binX: Output pixels are binX*binY input pixels

  • binY: Output pixels are binX*binY input pixels

  • flags: how to generate super-pixels

template<typename ImageT>
std::shared_ptr<ImageT> binImage(ImageT const &inImage, int const binsize, lsst::afw::math::Property const flags = lsst::afw::math::MEAN)

Parameters
  • inImage: The image to bin

  • binsize: Output pixels are binsize*binsize input pixels

  • flags: how to generate super-pixels

template<typename ImageT>
void randomUniformImage(ImageT *image, Random &rand)

Set image to random numbers uniformly distributed in the range [0, 1)

Parameters
  • [out] image: The image to set

  • [inout] rand: definition of random number algorithm, seed, etc.

template<typename ImageT>
void randomUniformPosImage(ImageT *image, Random &rand)

Set image to random numbers uniformly distributed in the range (0, 1)

Parameters
  • [out] image: The image to set

  • [inout] rand: definition of random number algorithm, seed, etc.

template<typename ImageT>
void randomUniformIntImage(ImageT *image, Random &rand, unsigned long n)

Set image to random integers uniformly distributed in the range 0 … n - 1

Parameters
  • [out] image: The image to set

  • [inout] rand: definition of random number algorithm, seed, etc.

  • [in] n: (exclusive) upper limit for random variates

template<typename ImageT>
void randomFlatImage(ImageT *image, Random &rand, double const a, double const b)

Set image to random numbers uniformly distributed in the range [a, b)

Parameters
  • [out] image: The image to set

  • [inout] rand: definition of random number algorithm, seed, etc.

  • [in] a: (inclusive) lower limit for random variates

  • [in] b: (exclusive) upper limit for random variates

template<typename ImageT>
void randomGaussianImage(ImageT *image, Random &rand)

Set image to random numbers with a gaussian N(0, 1) distribution

Parameters
  • [out] image: The image to set

  • [inout] rand: definition of random number algorithm, seed, etc.

template<typename ImageT>
void randomChisqImage(ImageT *image, Random &rand, double const nu)

Set image to random numbers with a chi^2_{nu} distribution

Parameters
  • [out] image: The image to set

  • [inout] rand: definition of random number algorithm, seed, etc.

  • [in] nu: number of degrees of freedom

template<typename ImageT>
void randomPoissonImage(ImageT *image, Random &rand, double const mu)

Set image to random numbers with a Poisson distribution with mean mu (n.b. not per-pixel)

Parameters
  • [out] image: The image to set

  • [inout] rand: definition of random number algorithm, seed, etc.

  • [in] mu: mean of distribution

template<typename PixelT>
std::shared_ptr<lsst::afw::image::Image<PixelT>> statisticsStack(std::vector<std::shared_ptr<lsst::afw::image::Image<PixelT>>> &images, Property flags, StatisticsControl const &sctrl = StatisticsControl(), std::vector<lsst::afw::image::VariancePixel> const &wvector = std::vector<lsst::afw::image::VariancePixel>(0))

Parameters
  • images: Images to process

  • flags: statistics requested

  • sctrl: Control structure

  • wvector: vector containing weights

A function to compute some statistics of a stack of Images

template<typename PixelT>
void statisticsStack(lsst::afw::image::Image<PixelT> &out, std::vector<std::shared_ptr<lsst::afw::image::Image<PixelT>>> &images, Property flags, StatisticsControl const &sctrl = StatisticsControl(), std::vector<lsst::afw::image::VariancePixel> const &wvector = std::vector<lsst::afw::image::VariancePixel>(0))

Parameters
  • out: Output image

  • images: Images to process

  • flags: statistics requested

  • sctrl: Control structure

  • wvector: vector containing weights

@ brief compute statistical stack of Image. Write to output image in-situ

template<typename PixelT>
std::shared_ptr<lsst::afw::image::MaskedImage<PixelT>> statisticsStack(std::vector<std::shared_ptr<lsst::afw::image::MaskedImage<PixelT>>> &images, Property flags, StatisticsControl const &sctrl, std::vector<lsst::afw::image::VariancePixel> const &wvector, image::MaskPixel clipped, std::vector<std::pair<image::MaskPixel, image::MaskPixel>> const &maskMap)

A function to compute some statistics of a stack of Masked Images

If none of the input images are valid for some pixel, the afwMath::StatisticsControl::getNoGoodPixelsMask() bit(s) are set.

Parameters
  • [in] images: MaskedImages to process.

  • [in] flags: Statistics requested.

  • [in] sctrl: Control structure.

  • [in] wvector: Vector of weights.

  • [in] clipped: Mask to set for pixels that were clipped (NOT rejected due to masks).

  • [in] maskMap: Vector of pairs of mask pixel values; any pixel on an input with any of the bits in .first will result in all of the bits in .second being set on the corresponding pixel on the output.

All the work is done in the function computeMaskedImageStack.

template<typename PixelT>
std::shared_ptr<lsst::afw::image::MaskedImage<PixelT>> statisticsStack(std::vector<std::shared_ptr<lsst::afw::image::MaskedImage<PixelT>>> &images, Property flags, StatisticsControl const &sctrl = StatisticsControl(), std::vector<lsst::afw::image::VariancePixel> const &wvector = std::vector<lsst::afw::image::VariancePixel>(0), image::MaskPixel clipped = 0, image::MaskPixel excuse = 0)

Parameters
  • images: MaskedImages to process

  • flags: statistics requested

  • sctrl: control structure

  • wvector: vector containing weights

  • clipped: bitmask to set if any input was clipped or masked

  • excuse: bitmask to excuse from marking as clipped

A function to compute some statistics of a stack of Masked Images

If none of the input images are valid for some pixel, the afwMath::StatisticsControl::getNoGoodPixelsMask() bit(s) are set.

Delegates to the more general version of statisticsStack taking a maskMap.

template<typename PixelT>
void statisticsStack(lsst::afw::image::MaskedImage<PixelT> &out, std::vector<std::shared_ptr<lsst::afw::image::MaskedImage<PixelT>>> &images, Property flags, StatisticsControl const &sctrl, std::vector<lsst::afw::image::VariancePixel> const &wvector, image::MaskPixel clipped, std::vector<std::pair<image::MaskPixel, image::MaskPixel>> const &maskMap)

A function to compute some statistics of a stack of Masked Images

If none of the input images are valid for some pixel, the afwMath::StatisticsControl::getNoGoodPixelsMask() bit(s) are set.

Parameters
  • [out] out: Output MaskedImage.

  • [in] images: MaskedImages to process.

  • [in] flags: Statistics requested.

  • [in] sctrl: Control structure.

  • [in] wvector: Vector of weights.

  • [in] clipped: Mask to set for pixels that were clipped (NOT rejected due to masks).

  • [in] maskMap: Vector of pairs of mask pixel values; any pixel on an input with any of the bits in .first will result in all of the bits in .second being set on the corresponding pixel on the output.

All the work is done in the function computeMaskedImageStack.

template<typename PixelT>
void statisticsStack(lsst::afw::image::MaskedImage<PixelT> &out, std::vector<std::shared_ptr<lsst::afw::image::MaskedImage<PixelT>>> &images, Property flags, StatisticsControl const &sctrl = StatisticsControl(), std::vector<lsst::afw::image::VariancePixel> const &wvector = std::vector<lsst::afw::image::VariancePixel>(0), image::MaskPixel clipped = 0, image::MaskPixel excuse = 0)

Parameters
  • out: Output image

  • images: MaskedImages to process

  • flags: statistics requested

  • sctrl: control structure

  • wvector: vector containing weights

  • clipped: bitmask to set if any input was clipped or masked

  • excuse: bitmask to excuse from marking as clipped

@ brief compute statistical stack of MaskedImage. Write to output image in-situ

template<typename PixelT>
std::vector<PixelT> statisticsStack(std::vector<std::vector<PixelT>> &vectors, Property flags, StatisticsControl const &sctrl = StatisticsControl(), std::vector<lsst::afw::image::VariancePixel> const &wvector = std::vector<lsst::afw::image::VariancePixel>(0))

Parameters
  • vectors: Vectors to process

  • flags: statistics requested

  • sctrl: control structure

  • wvector: vector containing weights

A function to compute some statistics of a stack of std::vectors

template<typename PixelT>
std::shared_ptr<lsst::afw::image::MaskedImage<PixelT>> statisticsStack(lsst::afw::image::Image<PixelT> const &image, Property flags, char dimension, StatisticsControl const &sctrl = StatisticsControl())

A function to compute statistics on the rows or columns of an image

template<typename PixelT>
std::shared_ptr<lsst::afw::image::MaskedImage<PixelT>> statisticsStack(lsst::afw::image::MaskedImage<PixelT> const &image, Property flags, char dimension, StatisticsControl const &sctrl = StatisticsControl())

A function to compute statistics on the rows or columns of an image

Property stringToStatisticsProperty(std::string const property)

Conversion function to switch a string to a Property (see Statistics.h)

template<typename Pixel>
Statistics makeStatistics(lsst::afw::image::Image<Pixel> const &img, lsst::afw::image::Mask<image::MaskPixel> const &msk, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Handle a watered-down front-end to the constructor (no variance)

template<typename ImageT, typename MaskT, typename VarianceT>
Statistics makeStatistics(ImageT const &img, MaskT const &msk, VarianceT const &var, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Handle a straight front-end to the constructor

template<typename Pixel>
Statistics makeStatistics(lsst::afw::image::MaskedImage<Pixel> const &mimg, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Handle MaskedImages, just pass the getImage() and getMask() values right on through.

template<typename Pixel>
Statistics makeStatistics(lsst::afw::image::MaskedImage<Pixel> const &mimg, lsst::afw::image::Image<WeightPixel> const &weights, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Handle MaskedImages, just pass the getImage() and getMask() values right on through.

Statistics makeStatistics(lsst::afw::image::Mask<lsst::afw::image::MaskPixel> const &msk, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Specialization to handle Masks

Parameters
  • msk: Image (or MaskedImage) whose properties we want

  • flags: Describe what we want to calculate

  • sctrl: Control how things are calculated

template<typename Pixel>
Statistics makeStatistics(lsst::afw::image::Image<Pixel> const &img, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Parameters
  • img: Image (or Image) whose properties we want

  • flags: Describe what we want to calculate

  • sctrl: Control calculation

The makeStatistics() overload to handle regular (non-masked) Images

template<typename EntryT>
Statistics makeStatistics(std::vector<EntryT> const &v, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Parameters
  • v: Image (or MaskedImage) whose properties we want

  • flags: Describe what we want to calculate

  • sctrl: Control calculation

The makeStatistics() overload to handle std::vector<>

template<typename EntryT>
Statistics makeStatistics(std::vector<EntryT> const &v, std::vector<WeightPixel> const &vweights, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Parameters
  • v: Image (or MaskedImage) whose properties we want

  • vweights: Weights

  • flags: Describe what we want to calculate

  • sctrl: Control calculation

The makeStatistics() overload to handle std::vector<>

template<typename EntryT>
Statistics makeStatistics(lsst::afw::math::MaskedVector<EntryT> const &mv, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Parameters
  • mv: MaskedVector

  • flags: Describe what we want to calculate

  • sctrl: Control calculation

The makeStatistics() overload to handle lsst::afw::math::MaskedVector<>

template<typename EntryT>
Statistics makeStatistics(lsst::afw::math::MaskedVector<EntryT> const &mv, std::vector<WeightPixel> const &vweights, int const flags, StatisticsControl const &sctrl = StatisticsControl())

Parameters
  • mv: MaskedVector

  • vweights: weights

  • flags: Describe what we want to calculate

  • sctrl: Control calculation

The makeStatistics() overload to handle lsst::afw::math::MaskedVector<>

std::shared_ptr<SeparableKernel> makeWarpingKernel(std::string name)

Return a warping kernel given its name.

Intended for use with warpImage() and warpExposure().

Allowed names are:

A warping kernel is a subclass of SeparableKernel with the following properties (though for the sake of speed few, if any, of these are enforced):

  • Width and height are even. This is unusual for a kernel, but it is more efficient because if the extra pixel was included it would always have value 0.

  • The center pixels should be adjacent to the kernel center. Again, this avoids extra pixels that are sure to have value 0.

  • It has two parameters: fractional x and fractional row position on the source image. The fractional position is the offset of the pixel position on the source from the center of a nearby source pixel:

    • The pixel whose center is just below or to the left of the source position: 0 <= fractional x and y < 0 and the kernel center is the default (size-1)/2.

    • The pixel whose center is just above or to the right of the source position: -1.0 < fractional x and y <= 0 and the kernel center must be set to (size+1)/2.

template<typename DestExposureT, typename SrcExposureT>
int warpExposure(DestExposureT &destExposure, SrcExposureT const &srcExposure, WarpingControl const &control, typename DestExposureT::MaskedImageT::SinglePixel padValue = lsst::afw::math::edgePixel<typename DestExposureT::MaskedImageT>(typename lsst::afw::image::detail::image_traits<typename DestExposureT::MaskedImageT>::image_category()))

Parameters
  • destExposure: Remapped exposure. Wcs and xy0 are read, MaskedImage is set, and PhotoCalib, Filter and VisitInfo are copied from srcExposure. All other attributes are left alone (including Detector and Psf)

  • srcExposure: Source exposure

  • control: control parameters

  • padValue: use this value for undefined (edge) pixels

Warp (remap) one exposure to another.

This is a convenience wrapper around warpImage().

template<typename DestImageT, typename SrcImageT>
int warpImage(DestImageT &destImage, geom::SkyWcs const &destWcs, SrcImageT const &srcImage, geom::SkyWcs const &srcWcs, WarpingControl const &control, typename DestImageT::SinglePixel padValue = lsst::afw::math::edgePixel<DestImageT>(typename lsst::afw::image::detail::image_traits<DestImageT>::image_category()))

Warp an Image or MaskedImage to a new Wcs. See also convenience function warpExposure() to warp an Exposure.

Parameters
  • destImage: remapped image

  • destWcs: WCS of remapped image

  • srcImage: source image

  • srcWcs: WCS of source image

  • control: control parameters

  • padValue: use this value for undefined (edge) pixels

Edge pixels are set to padValue; these are pixels that cannot be computed because they are too near the edge of srcImage or miss srcImage entirely.

Algorithm Without Interpolation:

Return

the number of valid pixels in destImage (those that are not edge pixels).

For each integer pixel position in the remapped Exposure:

  • The associated pixel position on srcImage is determined using the destination and source WCS

  • The warping kernel’s parameters are set based on the fractional part of the pixel position on srcImage

  • The warping kernel is applied to srcImage at the integer portion of the pixel position to compute the remapped pixel value

  • A flux-conservation factor is determined from the source and destination WCS and is applied to the remapped pixel

The scaling of intensity for relative area of source and destination uses two minor approximations:

  • The area of the sky marked out by a pixel on the destination image corresponds to a parallellogram on the source image.

  • The area varies slowly enough across the image that we can get away with computing the source area shifted by half a pixel up and to the left of the true area.

Algorithm With Interpolation:

Interpolation simply reduces the number of times WCS is used to map between destination and source pixel position. This computation is only made at a grid of points on the destination image, separated by interpLen pixels along rows and columns. All other source pixel positions are determined by linear interpolation between those grid points. Everything else remains the same.

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if destImage overlaps srcImage

  • std::bad_alloc: when allocation of CPU memory fails

Warning

The code that tests for image overlap is not guranteed to work correctly, based on the C++ standard. It is, in theory, possible for the code to report a “false positive”, meaning that it may claim that images overlap when they do not. We don’t believe that any of our current compilers have this problem. If, in the future, this becomes a problem then we will probably have to remove the test and rely on users being careful.

template<typename DestImageT, typename SrcImageT>
int warpImage(DestImageT &destImage, SrcImageT const &srcImage, geom::TransformPoint2ToPoint2 const &srcToDest, WarpingControl const &control, typename DestImageT::SinglePixel padValue = lsst::afw::math::edgePixel<DestImageT>(typename lsst::afw::image::detail::image_traits<DestImageT>::image_category()))

A variant of warpImage that uses a Transform<Point2Endpoint, Point2Endpoint> instead of a pair of WCS to describe the transformation.

Return

the number of good pixels

Parameters
  • [inout] destImage: Destination image; all pixels are set

  • [in] srcImage: Source image

  • [in] srcToDest: Transformation from source to destination pixels, in parent coordinates; the inverse must be defined (and is the only direction used). makeWcsPairTransform(srcWcs, destWcs) is one way to compute this transform.

  • [in] control: Warning control parameters

  • [in] padValue: Value used for pixels in the destination image that are outside the region of pixels that can be computed from the source image

template<typename DestImageT, typename SrcImageT>
int warpCenteredImage(DestImageT &destImage, SrcImageT const &srcImage, lsst::geom::LinearTransform const &linearTransform, lsst::geom::Point2D const &centerPosition, WarpingControl const &control, typename DestImageT::SinglePixel padValue = lsst::afw::math::edgePixel<DestImageT>(typename lsst::afw::image::detail::image_traits<DestImageT>::image_category()))

Parameters
  • destImage: remapped image

  • srcImage: source image

  • linearTransform: linear transformation to apply

  • centerPosition: pixel position for location of linearTransform

  • control: control parameters

  • padValue: use this value for undefined (edge) pixels

Warp an image with a LinearTranform about a specified point.

This enables warping an image of e.g. a PSF without translating the centroid.

Variables

template<typename T>
bool constexpr IS_NOTHROW_INIT = noexcept(static_cast<T>(1.0))

Test that a Function’s return value is nothrow-castable to T

std::complex is an example of a numeric type that does not satisfy this requirement.

double const MOCK_INF = 1.e10
double const DEFABSERR = 1.e-15
double const DEFRELERR = 1.e-6
generic_kernel_tag generic_kernel_tag_
deltafunction_kernel_tag deltafunction_kernel_tag_
class AnalyticKernel : public lsst::afw::table::io::PersistableFacade<AnalyticKernel>, public lsst::afw::math::Kernel
#include <Kernel.h>

A kernel described by a function.

The function’s x, y arguments are as follows:

  • -getCtr() for the lower left corner pixel

  • 0, 0 for the center pixel

  • (getDimensions() - 1) - getCtr() for the upper right pixel

Note: each pixel is set to the value of the kernel function at the center of the pixel (rather than averaging the function over the area of the pixel).

template<typename PixelT>
class Approximate
#include <Approximate.h>

Approximate values for a MaskedImage

class ApproximateControl
#include <Approximate.h>

Control how to make an approximation

Note

the x- and y-order must be the same, due to a limitation of Chebyshev1Function2

class Background
#include <Background.h>

A virtual base class to evaluate image background levels

Subclassed by lsst::afw::math::BackgroundMI

class BackgroundControl
#include <Background.h>

Pass parameters to a Background object

class BackgroundMI : public lsst::afw::math::Background
#include <Background.h>

A class to evaluate image background levels

Break an image up into nx*ny sub-images and use a statistical to estimate the background levels in each square. Then use a user-specified or algorithm to estimate background at a given pixel coordinate.

Methods are available to return the background at a point (inefficiently), or an entire background image. BackgroundControl contains a public StatisticsControl member to allow user control of how the backgrounds are computed.

math::BackgroundControl bctrl(7, 7);  // number of sub-image squares in {x,y}-dimensions
bctrl.sctrl.setNumSigmaClip(5.0);     // use 5-sigma clipping for the sub-image means
std::shared_ptr<math::Background> backobj = math::makeBackground(img, bctrl);
// get a whole background image
Image<PixelT> back = backobj->getImage<PixelT>(math::Interpolate::NATURAL_SPLINE);

// get the background at a pixel at i_x,i_y
double someValue = backobj.getPixel(math::Interpolate::LINEAR, i_x, i_y);

template<typename ReturnT>
class BasePolynomialFunction2 : public lsst::afw::math::Function2<ReturnT>
#include <Function.h>

Base class for 2-dimensional polynomials of the form:

f(x,y) =   c0 f0(x) f0(y)                                        (0th order)
         + c1 f1(x) f0(x) + c2 f0(x) f1(y)                       (1st order)
         + c3 f2(x) f0(y) + c4 f1(x) f1(y) + c5 f0(x) f2(y)      (2nd order)
         + ...

and typically f0(x) = 1

Subclassed by lsst::afw::math::Chebyshev1Function2< ReturnT >, lsst::afw::math::PolynomialFunction2< ReturnT >

class BilinearWarpingKernel : public lsst::afw::math::SeparableKernel
#include <warpExposure.h>

Bilinear warping: fast; good for undersampled data.

The kernel size is 2 x 2.

For more information about warping kernels see makeWarpingKernel

class BoundedField : public lsst::afw::table::io::PersistableFacade<BoundedField>, public lsst::afw::table::io::Persistable
#include <BoundedField.h>

An abstract base class for 2-d functions defined on an integer bounding boxes

Integer bounding boxes (lsst::geom::Box2I) are inclusive of the end pixels (integer positions correspond to the centers of the pixels and include the entirety of those pixels). Thus a BoundedField defined on the box [x0, x1] x [y0, y1] actually covers the range [x0 - 0.5, x1 + 0.5] x [y0 - 0.5, y1 + 0.5].

BoundedField provides a number of ways of accessing the function, all delegating to a single evaluate-at-a-point implementation. The base class does not mandate anything about how the field is constructed, so it’s appropriate for use with e.g. model-fitting results, interpolation results points, or functions known a priori.

Usually, BoundedField will be used to represent functions that correspond to images, for quantities such as aperture corrections, photometric scaling, PSF model parameters, or backgrounds, and its bounding box will be set to match the PARENT bounding box of the image.

Subclassed by lsst::afw::math::ChebyshevBoundedField, lsst::afw::math::PixelAreaBoundedField, lsst::afw::math::ProductBoundedField, lsst::afw::math::TransformBoundedField, lsst::meas::algorithms::CoaddBoundedField

class CandidateVisitor

Subclassed by lsst::ip::diffim::detail::AssessSpatialKernelVisitor< PixelT >, lsst::ip::diffim::detail::BuildSingleKernelVisitor< PixelT >, lsst::ip::diffim::detail::BuildSpatialKernelVisitor< PixelT >, lsst::ip::diffim::detail::KernelPcaVisitor< PixelT >, lsst::ip::diffim::detail::KernelSumVisitor< PixelT >

template<typename ReturnT>
class Chebyshev1Function1 : public lsst::afw::math::Function1<ReturnT>
#include <FunctionLibrary.h>

1-dimensional weighted sum of Chebyshev polynomials of the first kind.

f(x) = c0 T0(x’) + c1 T1(x’) + c2 T2(x’) + … = c0 + c1 T1(x’) + c2 T2(x’) + … where:

  • Tn(x) is the nth Chebyshev function of the first kind: T0(x) = 1 T1(x) = 2 Tn+1(x) = 2xTn(x) + Tn-1(x)

  • x’ is x offset and scaled to range [-1, 1] as x ranges over [minX, maxX]

The function argument must be in the range [minX, maxX].

template<typename ReturnT>
class Chebyshev1Function2 : public lsst::afw::math::BasePolynomialFunction2<ReturnT>
#include <FunctionLibrary.h>

2-dimensional weighted sum of Chebyshev polynomials of the first kind.

f(x,y) = c0 T0(x’) T0(y’) # order 0

  • c1 T1(x’) T0(y’) + c2 T0(x’) T1(y’) # order 1

  • c3 T2(x’) T0(y’) + c4 T1(x’) T1(y’) + c5 T0(x’) T2(y’) # order 2

= c0 # order 0

  • c1 T1(x’) + c2 T1(y’) # order 1

  • c3 T2(x’) + c4 T1(x’) T1(y’) + c5 T2(y’) # order 2

where:

  • Tn(x) is the nth Chebyshev function of the first kind: T0(x) = 1 T1(x) = x Tn+1(x) = 2xTn(x) + Tn-1(x)

  • x’ is x offset and scaled to range [-1, 1] as x ranges over [minX, maxX]

  • y’ is y offset and scaled to range [-1, 1] as y ranges over [minY, maxY]

Return value is incorrect if function arguments are not in the range [minX, maxX], [minY, maxY].

class ChebyshevBoundedField : public lsst::afw::table::io::PersistableFacade<ChebyshevBoundedField>, public lsst::afw::math::BoundedField
#include <ChebyshevBoundedField.h>

A BoundedField based on 2-d Chebyshev polynomials of the first kind.

The 2-d Chebyshev polynomial used here is defined as:

\[ f(x,y) = \sum_i \sum_j a_{i,j} T_i(x) T_j(y) \]

where \(T_n(x)\) is the n-th order Chebyshev polynomial of \(x\) and \(a_{i,j}\) is the corresponding coefficient of the (i,j) polynomial term.

ChebyshevBoundedField supports fitting to gridded and non-gridded data, as well coefficient matrices with different x- and y-order.

There is currently quite a bit of duplication of functionality between ChebyshevBoundedField, ApproximateChebyshev, and Chebyshev1Function2; the intent is that ChebyshevBoundedField will ultimately replace ApproximateChebyshev and should be preferred over Chebyshev1Function2 when the parametrization interface that is part of the Function2 class is not needed.

class ChebyshevBoundedFieldControl
#include <ChebyshevBoundedField.h>

A control object used when fitting ChebyshevBoundedField to data (see ChebyshevBoundedField::fit)

class ConvolutionControl
#include <ConvolveImage.h>

Parameters to control convolution

template<typename T>
class Covariogram
#include <GaussianProcess.h>

The parent class of covariogram functions for use in Gaussian Process interpolation

Each instantiation of a Covariogram will store its own hyper parameters

Subclassed by lsst::afw::math::NeuralNetCovariogram< T >, lsst::afw::math::SquaredExpCovariogram< T >

struct deltafunction_kernel_tag : public lsst::afw::math::generic_kernel_tag
#include <traits.h>

Kernel has only one non-zero pixel.

class DeltaFunctionKernel : public lsst::afw::table::io::PersistableFacade<DeltaFunctionKernel>, public lsst::afw::math::Kernel
#include <Kernel.h>

A kernel that has only one non-zero pixel (of value 1)

It has no adjustable parameters and so cannot be spatially varying.

template<typename ReturnT>
class DoubleGaussianFunction2 : public lsst::afw::math::Function2<ReturnT>
#include <FunctionLibrary.h>

double Guassian (sum of two Gaussians)

Intended for use as a PSF model: the main Gaussian represents the core and the second Gaussian represents the wings.

f(x,y) = A (e^(-r^2 / 2 sigma1^2) + ampl2 e^(-r^2 / 2 sigma2^2)) where:

  • A = 1 / (2 pi (sigma1^2 + ampl2 sigma2^2))

  • r^2 = x^2 + y^2 coefficients c[0] = sigma1, c[1] = sigma2, c[2] = ampl2

struct FitResults
#include <minimize.h>

Results from minimizing a function

class FixedKernel : public lsst::afw::table::io::PersistableFacade<FixedKernel>, public lsst::afw::math::Kernel
#include <Kernel.h>

A kernel created from an Image

It has no adjustable parameters and so cannot be spatially varying.

template<typename ReturnT>
class Function : public lsst::afw::table::io::PersistableFacade<Function<ReturnT>>, public lsst::afw::table::io::Persistable
#include <Function.h>

Basic Function class.

Function objects are functions whose parameters may be read and changed using getParameters and setParameters. They were designed for use with the Kernel class.

These are simple functors with the restrictions that:

  • Function arguments and parameters are double precision

  • The return type is templated

To create a function for a particular equation, subclass Function or (much more likely) Function1 or Function2. Your subclass must:

  • Have one or more constructors, all of which must initialize _params

  • Define operator() with code to compute the function using this->_params or this->getParams() to reference the parameters

  • If the function is a linear combination of parameters then override the function isLinearCombination.

If you wish to cache any information you may use the _isCacheValid flag; this is automatically set false whenever parameters are changed.

Design Notes: The reason these functions exist (rather than using a pre-existing function class, such as Functor in VisualWorkbench) is because the Kernel class requires function objects with a standard interface for setting and getting function parameters.

The reason isLinearCombination exists is to support refactoring LinearCombinationKernels.

Subclassed by lsst::afw::math::Function1< ReturnT >, lsst::afw::math::Function2< ReturnT >

template<typename ReturnT>
class Function1 : public lsst::afw::table::io::PersistableFacade<Function1<ReturnT>>, public lsst::afw::math::Function<ReturnT>
#include <Function.h>

A Function taking one argument.

Subclass and override operator() to do useful work.

Subclassed by lsst::afw::math::Chebyshev1Function1< ReturnT >, lsst::afw::math::GaussianFunction1< ReturnT >, lsst::afw::math::IntegerDeltaFunction1< ReturnT >, lsst::afw::math::LanczosFunction1< ReturnT >, lsst::afw::math::NullFunction1< ReturnT >, lsst::afw::math::PolynomialFunction1< ReturnT >

template<typename ReturnT>
class Function2 : public lsst::afw::table::io::PersistableFacade<Function2<ReturnT>>, public lsst::afw::math::Function<ReturnT>
#include <Function.h>

A Function taking two arguments.

Subclass and override operator() to do useful work.

Subclassed by lsst::afw::math::BasePolynomialFunction2< ReturnT >, lsst::afw::math::DoubleGaussianFunction2< ReturnT >, lsst::afw::math::GaussianFunction2< ReturnT >, lsst::afw::math::IntegerDeltaFunction2< ReturnT >, lsst::afw::math::LanczosFunction2< ReturnT >, lsst::afw::math::NullFunction2< ReturnT >

template<typename ReturnT>
class GaussianFunction1 : public lsst::afw::math::Function1<ReturnT>
#include <FunctionLibrary.h>

1-dimensional Gaussian

f(x) = A e^(-x^2 / 2 sigma^2) where:

  • A = 1 / (sqrt(2 pi) xSigma) coefficient c0 = sigma

template<typename ReturnT>
class GaussianFunction2 : public lsst::afw::math::Function2<ReturnT>
#include <FunctionLibrary.h>

2-dimensional Gaussian

f(x,y) = A e^((-pos1^2 / 2 sigma1^2) - (pos2^2 / 2 sigma2^2)) where:

  • A = 1 / (2 pi sigma1 sigma2)

  • pos1 = cos(angle) x + sin(angle) y

  • pos2 = -sin(angle) x + cos(angle) y coefficients c0 = sigma1, c1 = sigma2, c2 = angle

Note

if sigma1 > sigma2 then angle is the angle of the major axis

template<typename T>
class GaussianProcess
#include <GaussianProcess.h>

Stores values of a function sampled on an image and allows you to interpolate the function to unsampled points

The data will be stored in a KD Tree for easy nearest neighbor searching when interpolating.

The array _function[] will contain the values of the function being interpolated. You can provide a two dimensional array _function[][] if you wish to interpolate a vector of functions. In this case _function[i][j] is the jth function associated with the ith data point. Note: presently, the covariance matrices do not relate elements of _function[i][] to each other, so the variances returned will be identical for all functions evaluated at the same point in parameter space.

_data[i][j] will be the jth component of the ith data point.

_max and _min contain the maximum and minimum values of each dimension in parameter space (if applicable) so that data points can be normalized by _max-_min to keep distances between points reasonable. This is an option specified by calling the relevant constructor.

class GaussianProcessTimer
#include <GaussianProcess.h>

This is a structure for keeping track of how long the interpolation methods spend on different parts of the interpolation

_eigenTime keeps track of how much time is spent using Eigen’s linear algebra packages

_iterationTime keeps track of how much time is spent iterating over matrix indices (this is also a catch-all for time that does not obviously fit in the other categories)

_searchTime keeps track of how much time is spent on nearest neighbor searches (when applicable)

_varianceTime keeps track of how much time is spent calculating the variance of our interpolated function value (note: time spent using Eigen packages for this purpose is tallied here, not in _eigenTime)

_totalTime keeps track of how much time total is spent on interpolations

_interpolationCount keeps track of how many points have been interpolated

struct generic_kernel_tag
#include <traits.h>

Tags carrying information about Kernels Kernel with no special properties.

Subclassed by lsst::afw::math::deltafunction_kernel_tag

template<typename ValueT>
class ImageImposter
#include <Statistics.h>

A vector wrapper to provide a vector with the necessary methods and typedefs to be processed by Statistics as though it were an Image.

template<typename ValueT>
class infinite_iterator : public boost::iterator_adaptor<infinite_iterator<ValueT>, const ValueT *, const ValueT, boost::forward_traversal_tag>
#include <Statistics.h>

This iterator will never increment. It is returned by row_begin() in the MaskImposter class (below) to allow phony mask pixels to be iterated over for non-mask images within Statistics.

template<typename ReturnT>
class IntegerDeltaFunction1 : public lsst::afw::math::Function1<ReturnT>
#include <FunctionLibrary.h>

1-dimensional integer delta function.

f(x) = 1 if x == xo, 0 otherwise.

For use as a kernel function be sure to handle the offset for row and column center; see examples/deltaFunctionKernel for an example.

template<typename ReturnT>
class IntegerDeltaFunction2 : public lsst::afw::math::Function2<ReturnT>
#include <FunctionLibrary.h>

2-dimensional integer delta function.

f(x) = 1 if x == xo and y == yo, 0 otherwise.

For use as a kernel function be sure to handle the offset for row and column center; see examples/deltaFunctionKernel for an example.

template<typename KernelT>
struct is_analyticKernel
#include <traits.h>

traits class to determine if a Kernel is represented as an analytic function

Subclassed by lsst::afw::math::is_analyticKernel< KernelT * >, lsst::afw::math::is_analyticKernel< std::shared_ptr< KernelT > >

template<typename T>
class KdTree
#include <GaussianProcess.h>

The data for GaussianProcess is stored in a KD tree to facilitate nearest-neighbor searches

Note: I have removed the ability to arbitrarily specify a distance function. The KD Tree nearest neighbor search algorithm only makes sense in the case of Euclidean distances, so I have forced KdTree to use Euclidean distances.

class Kernel : public lsst::afw::table::io::PersistableFacade<Kernel>, public lsst::afw::table::io::Persistable
#include <Kernel.h>

Kernels are used for convolution with MaskedImages and (eventually) Images

Kernel is a virtual base class; it cannot be instantiated. The following notes apply to Kernel and to its subclasses.

The template type should usually be float or double; integer kernels should be used with caution because they do not normalize well.

The center pixel of a Kernel is at index: (width-1)/2, (height-1)/2. Thus it is centered along columns/rows if the kernel has an odd number of columns/rows and shifted 1/2 pixel towards 0 otherwise. A kernel should have an odd number of columns and rows unless it is intended to shift an image.

Spatially Varying Kernels

Kernels may optionally vary spatially (so long as they have any kernel parameters). To make a spatially varying kernel, specify a spatial function at construction (you cannot change your mind once the kernel is constructed). You must also specify a set of spatial parameters, and you may do this at construction and/or later by calling setSpatialParameters. The spatial parameters are a vector (one per kernel function parameter) of spatial function parameters. In other words the spatial parameters are a vector of vectors indexed as [kernel parameter][spatial parameter]. The one spatial function is used to compute the kernel parameters at a given spatial position by computing each kernel parameter using its associated vector of spatial function parameters.

The convolve function computes the spatial function at the pixel position (not index) of the image. See the convolve function for details.

Note that if a kernel is spatially varying then you may not set the kernel parameters directly; that is the job of the spatial function! However, you may change the spatial parameters at any time.

Design Notes

The basic design is to use the same kernel class for both spatially varying and spatially invariant kernels. The user either does or does not supply a function describing the spatial variation at creation time. In addition, analytic kernels are described by a user-supplied function of the same basic type as the spatial variation function.

Several other designs were considered, including: A) Use different classes for spatially varying and spatially invariant versions of each kernel. Thus instead of three basic kernel classes (FixedKernel, AnalyticKernel and LinearCombinationKernel) we would have five (since FixedKernel cannot be spatially varying). Robert Lupton argued that was a needless expansion of the class hiearchy and I agreed. B) Construct analytic kernels by defining a subclass of AnalyticKernel that is specific to the desired functional (e.g. GaussianAnalyticKernel). If spatial models are handled the same way then this creates a serious proliferation of kernel classes (even if we only have two different spatial models, e.g. polynomial and Chebyshev polynomial). I felt it made more sense to define the spatial model by some kind of function class (often called a “functor”), and since we needed such a class, I chose to use it for the analytic kernel as well.

However, having a separate function class does introduce some potential inefficiencies. If a function is part of the class it can potentially be evaluated more quickly than calling a function for each pixel or spatial position.

A possible variant on the current design is to define the spatial model and analytic kernel by specifying the functions as template parameters. This has the potential to regain some efficiency in evaluating the functions. However, it would be difficult or impossible to pre-instantiate the desired template classes, a requirement of the LSST coding standards.

Subclassed by lsst::afw::math::AnalyticKernel, lsst::afw::math::DeltaFunctionKernel, lsst::afw::math::FixedKernel, lsst::afw::math::LinearCombinationKernel, lsst::afw::math::SeparableKernel

template<typename KernelT>
struct kernel_traits
#include <traits.h>

template trait class with information about Kernels

template<typename ReturnT>
class LanczosFunction1 : public lsst::afw::math::Function1<ReturnT>
#include <FunctionLibrary.h>

1-dimensional Lanczos function

f(x) = sinc(pi x’) sinc(pi x’ / n) where x’ = x - xOffset and coefficient c0 = xOffset

Warning: the Lanczos function is sometimes forced to 0 if |x’| > n but this implementation does not perform that truncation so as to improve Lanczos kernels.

template<typename ReturnT>
class LanczosFunction2 : public lsst::afw::math::Function2<ReturnT>
#include <FunctionLibrary.h>

2-dimensional separable Lanczos function

f(x, y) = sinc(pi x’) sinc(pi x’ / n) sinc(pi y’) sinc(pi y’ / n) where x’ = x - xOffset and y’ = y - yOffset and coefficients c0 = xOffset, c1 = yOffset

Warning

the Lanczos function is sometimes forced to 0 if |x’| > n or |y’| > n but this implementation does not perform that truncation so as to improve Lanczos kernels.

class LanczosWarpingKernel : public lsst::afw::math::SeparableKernel
#include <warpExposure.h>

Lanczos warping: accurate but slow and can introduce ringing artifacts.

This kernel is the product of two 1-dimensional Lanczos functions. The number of minima and maxima in the 1-dimensional Lanczos function is 2*order + 1. The kernel has one pixel per function minimum or maximum; but as applied to warping, the first or last pixel is always zero and can be omitted. Thus the kernel size is 2*order x 2*order.

For more information about warping kernels see makeWarpingKernel

class LeastSquares
#include <LeastSquares.h>

Solver for linear least-squares problems.

Linear least-squares problems are defined as finding the vector \(x\) that minimizes \(\left|A x - b\right|_2\), with the number of rows of \(A\) generally greater than the number of columns. We call \(A\) the design matrix, \(b\) the data vector, and \(x\) the solution vector. When the rank of \(A\) is equal to the number of columns, we can obtain using the solution using the normal equations:

\[ A^T A x = A^T b \]
If \(A\) is not full-rank, the problem is underconstrained, and we usually wish to solve the minimum-norm least-squares problem, which also minimizes \(|x|_2\). This can be done by computing a pseudo-inverse of \(A\) using an SVD or complete orthogonal factorization of \(A\), or by performing an Eigen decomposition of \(A^T A\).

This class can be constructed from the design matrix and data vector, or from the two terms in the normal equations (below, we call the matrix \(A^TA\) the Fisher matrix, and the vector \(A^T b\) simply the “right-hand side” (RHS) vector). If initialized with the design matrix and data vector, we can still use the normal equations to solve it. The solution via the normal equations is more susceptible to round-off error, but it is also faster, and if the normal equation terms can be computed directly it can be significantly less expensive in terms of memory. The Fisher matrix is a symmetric matrix, and it should be exactly symmetric when provided as input, because which triangle will be used is an implementation detail that is subject to change and may depend on the storage order.

The solver always operates in double precision, and returns all results in double precision. However, it can be initialized from single precision inputs. It isn’t usually a good idea to construct the normal equations in single precision, however, even when the data are single precision.

class LinearCombinationKernel : public lsst::afw::table::io::PersistableFacade<LinearCombinationKernel>, public lsst::afw::math::Kernel
#include <Kernel.h>

A kernel that is a linear combination of fixed basis kernels.

Convolution may be performed by first convolving the image with each fixed kernel, then adding the resulting images using the (possibly spatially varying) kernel coefficients.

The basis kernels are cloned (deep copied) so you may safely modify your own copies.

Warnings:

  • This class does not normalize the individual basis kernels; they are used “as is”.

template<typename ValueT>
class MaskImposter
#include <Statistics.h>

A Mask wrapper to provide an infinite_iterator for Mask::row_begin(). This allows a fake Mask to be passed in to Statistics with a regular (non-masked) Image.

class NearestWarpingKernel : public lsst::afw::math::SeparableKernel
#include <warpExposure.h>

Nearest neighbor warping: fast; good for undersampled data.

The kernel size is 2 x 2.

For more information about warping kernels see makeWarpingKernel

template<typename T>
class NeuralNetCovariogram : public lsst::afw::math::Covariogram<T>
#include <GaussianProcess.h>

a Covariogram that recreates a neural network with one hidden layer and infinite units in that layer

Contains two hyper parameters (_sigma0 and _sigma1) that characterize the expected variance of the function being interpolated

see Rasmussen and Williams (2006) http://www.gaussianprocess.org/gpml/ equation 4.29

template<typename ReturnT>
class NullFunction1 : public lsst::afw::math::Function1<ReturnT>
#include <Function.h>

a class used in function calls to indicate that no Function1 is being provided

template<typename ReturnT>
class NullFunction2 : public lsst::afw::math::Function2<ReturnT>
#include <Function.h>

a class used in function calls to indicate that no Function2 is being provided

class PixelAreaBoundedField : public lsst::afw::math::BoundedField
#include <PixelAreaBoundedField.h>

A BoundedField that evaluate the pixel area of a SkyWcs in angular units.

Typically used to move an image or source flux between surface brightness and fluence.

template<typename ReturnT>
class PolynomialFunction1 : public lsst::afw::math::Function1<ReturnT>
#include <FunctionLibrary.h>

1-dimensional polynomial function.

f(x) = c0 + c1 x + c2 x^2 + … cn-1 x^(n-1)

template<typename ReturnT>
class PolynomialFunction2 : public lsst::afw::math::BasePolynomialFunction2<ReturnT>
#include <FunctionLibrary.h>

2-dimensional polynomial function with cross terms

f(x,y) = c0 (0th order)

  • c1 x + c2 y (1st order)

  • c3 x^2 + c4 x y + c5 y^2 (2nd order)

  • c6 x^3 + c7 x^2 y + c8 x y^2 + c9 y^3 (3rd order)

Intermediate products for the most recent y are cached, so when computing for a set of x, y it is more efficient to change x before you change y.

class ProductBoundedField : public lsst::afw::table::io::PersistableFacade<ProductBoundedField>, public lsst::afw::math::BoundedField
#include <ProductBoundedField.h>

A BoundedField that lazily multiplies a sequence of other BoundedFields.

class Random
#include <Random.h>

A class that can be used to generate sequences of random numbers according to a number of different algorithms. Support for generating random variates from the uniform, Gaussian, Poisson, and chi-squared distributions is provided.

This class is a thin wrapper for the random number generation facilities of GSL, which supports many additional distributions that can easily be added to this class as the need arises.

See

Random number generation in GSL

See

Random number distributions in GSL

class SeparableKernel : public lsst::afw::table::io::PersistableFacade<SeparableKernel>, public lsst::afw::math::Kernel
#include <Kernel.h>

A kernel described by a pair of functions: func(x, y) = colFunc(x) * rowFunc(y)

The function’s x, y arguments are as follows:

  • -getCtr() for the lower left corner pixel

  • 0, 0 for the center pixel

  • (getDimensions() - 1) - getCtr() for the upper right pixel

Note: each pixel is set to the value of the kernel function at the center of the pixel (rather than averaging the function over the area of the pixel).

Subclassed by lsst::afw::math::BilinearWarpingKernel, lsst::afw::math::LanczosWarpingKernel, lsst::afw::math::NearestWarpingKernel

class SpatialCell
#include <SpatialCell.h>

Class to ensure constraints for spatial modeling

A given image is divided up into cells, with each cell represented by an instance of this class. Each cell itself contains a list of instances of classes derived from SpatialCellCandidate. One class member from each cell will be chosen to fit to a spatial model. In case of a poor fit, the next class instance in the list will be fit for. If all instances in a list are rejected from the spatial model, the best one will be used.

See

The SpatialCellSet example in the module documentation.

class SpatialCellCandidate
#include <SpatialCell.h>

Base class for candidate objects in a SpatialCell

Subclassed by lsst::afw::math::SpatialCellImageCandidate

class SpatialCellCandidateIterator
#include <SpatialCell.h>

An iterator that only returns usable members of the SpatialCell

class SpatialCellImageCandidate : public lsst::afw::math::SpatialCellCandidate
#include <SpatialCell.h>

Base class for candidate objects in a SpatialCell that are able to return an Image of some sort (e.g. a PSF or a DIA kernel)

Subclassed by lsst::ip::diffim::KernelCandidate< _PixelT >, lsst::meas::algorithms::PsfCandidate< PixelT >

class SpatialCellSet
#include <SpatialCell.h>

A collection of SpatialCells covering an entire image

template<typename T>
class SquaredExpCovariogram : public lsst::afw::math::Covariogram<T>
#include <GaussianProcess.h>

SquaredExpCovariogram

a Covariogram that falls off as the negative exponent of the square of the distance between the points

Contains one hyper parameter (_ellSquared) encoding the square of the characteristic length scale of the covariogram

class Statistics
#include <Statistics.h>

A class to evaluate image statistics

The basic strategy is to construct a Statistics object from an Image and a statement of what we want to know. The desired results can then be returned using Statistics methods. A StatisticsControl object is used to pass parameters. The statistics currently implemented are listed in the enum Properties in Statistics.h.

 // sets NumSigclip (3.0), and NumIter (3) for clipping
 lsst::afw::math::StatisticsControl sctrl(3.0, 3);

 sctrl.setNumSigmaClip(4.0);            // reset number of standard deviations for N-sigma clipping
 sctrl.setNumIter(5);                   // reset number of iterations for N-sigma clipping
 sctrl.setAndMask(0x1);                 // ignore pixels with these mask bits set
 sctrl.setNanSafe(true);                // check for NaNs & Infs, a bit slower (default=true)

 lsst::afw::math::Statistics statobj =
     lsst::afw::math::makeStatistics(*img, afwMath::NPOINT |
                                           afwMath::MEAN | afwMath::MEANCLIP, sctrl);
 double const n = statobj.getValue(lsst::afw::math::NPOINT);
 std::pair<double, double> const mean =
                                  statobj.getResult(lsst::afw::math::MEAN); // Returns (value, error)
 double const meanError = statobj.getError(lsst::afw::math::MEAN);                // just the error

Note

Factory function: We used a helper function, makeStatistics, rather that the constructor directly so that the compiler could deduce the types cf. std::make_pair()

Note

Inputs: The class Statistics is templated, and makeStatistics() can take either: (1) an image, (2) a maskedImage, or (3) a std::vector<> Overloaded makeStatistics() functions then wrap what they were passed in Image/Mask-like classes and call the Statistics constructor.

Note

Clipping: The clipping is done iteratively with numSigmaClip and numIter specified in the StatisticsControl object. The first clip (ie. the first iteration) is performed at: median +/- numSigmaClip*IQ_TO_STDEV*IQR, where IQ_TO_STDEV=~0.74 is the conversion factor between the IQR and sigma for a Gaussian distribution. All subsequent iterations perform clips at mean +/- numSigmaClip*stdev.

class StatisticsControl
#include <Statistics.h>

Pass parameters to a Statistics object

A class to pass parameters which control how the stats are calculated.

class TransformBoundedField : public lsst::afw::table::io::PersistableFacade<TransformBoundedField>, public lsst::afw::math::BoundedField
#include <TransformBoundedField.h>

A BoundedField based on geom::Transform<Poin2Endpoint, GenericEndpoint<1>>.

TransformBoundedField supports arbitrary transforms.

class WarpingControl
#include <warpExposure.h>

Parameters to control convolution

Note

padValue is not member of this class to avoid making this a templated class.

namespace detail

Functions

template<typename OutImageT, typename InImageT>
void basicConvolve(OutImageT &convolvedImage, InImageT const &inImage, lsst::afw::math::Kernel const &kernel, lsst::afw::math::ConvolutionControl const &convolutionControl)

Low-level convolution function that does not set edge pixels.

convolvedImage must be the same size as inImage. convolvedImage has a border in which the output pixels are not set. This border has size:

  • kernel.getCtrX() along the left edge

  • kernel.getCtrY() along the bottom edge

  • kernel.getWidth() - 1 - kernel.getCtrX() along the right edge

  • kernel.getHeight() - 1 - kernel.getCtrY() along the top edge

Parameters
  • [out] convolvedImage: convolved image

  • [in] inImage: image to convolve

  • [in] kernel: convolution kernel

  • [in] convolutionControl: convolution control parameters

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if convolvedImage dimensions != inImage dimensions

  • lsst::pex::exceptions::InvalidParameterError: if inImage smaller than kernel in width or height

  • lsst::pex::exceptions::InvalidParameterError: if kernel width or height < 1

  • std::bad_alloc: when allocation of CPU memory fails

template<typename OutImageT, typename InImageT>
void basicConvolve(OutImageT &convolvedImage, InImageT const &inImage, lsst::afw::math::DeltaFunctionKernel const &kernel, lsst::afw::math::ConvolutionControl const &convolutionControl)

A version of basicConvolve that should be used when convolving delta function kernels

Parameters
  • [out] convolvedImage: convolved image

  • [in] inImage: image to convolve

  • [in] kernel: convolution kernel

  • [in] convolutionControl: convolution control parameters

template<typename OutImageT, typename InImageT>
void basicConvolve(OutImageT &convolvedImage, InImageT const &inImage, lsst::afw::math::LinearCombinationKernel const &kernel, lsst::afw::math::ConvolutionControl const &convolutionControl)

A version of basicConvolve that should be used when convolving a LinearCombinationKernel

The Algorithm:

  • If the kernel is spatially varying and contains only DeltaFunctionKernels then convolves the input Image by each basis kernel in turn, solves the spatial model for that component and adds in the appropriate amount of the convolved image.

  • In all other cases uses normal convolution

Parameters
  • [out] convolvedImage: convolved image

  • [in] inImage: image to convolve

  • [in] kernel: convolution kernel

  • [in] convolutionControl: convolution control parameters

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if convolvedImage dimensions != inImage dimensions

  • lsst::pex::exceptions::InvalidParameterError: if inImage smaller than kernel in width or height

  • lsst::pex::exceptions::InvalidParameterError: if kernel width or height < 1

  • std::bad_alloc: when allocation of CPU memory fails

template<typename OutImageT, typename InImageT>
void basicConvolve(OutImageT &convolvedImage, InImageT const &inImage, lsst::afw::math::SeparableKernel const &kernel, lsst::afw::math::ConvolutionControl const &convolutionControl)

A version of basicConvolve that should be used when convolving separable kernels

Parameters
  • [out] convolvedImage: convolved image

  • [in] inImage: image to convolve

  • [in] kernel: convolution kernel

  • [in] convolutionControl: convolution control parameters

template<typename OutImageT, typename InImageT>
void convolveWithBruteForce(OutImageT &convolvedImage, InImageT const &inImage, lsst::afw::math::Kernel const &kernel, lsst::afw::math::ConvolutionControl const &convolutionControl)

Convolve an Image or MaskedImage with a Kernel by computing the kernel image at every point. (If the kernel is not spatially varying then only compute it once).

convolvedImage must be the same size as inImage. convolvedImage has a border in which the output pixels are not set. This border has size:

  • kernel.getCtrX() along the left edge

  • kernel.getCtrY() along the bottom edge

  • kernel.getWidth() - 1 - kernel.getCtrX() along the right edge

  • kernel.getHeight() - 1 - kernel.getCtrY() along the top edge

Warning

Low-level convolution function that does not set edge pixels.

Parameters
  • [out] convolvedImage: convolved image

  • [in] inImage: image to convolve

  • [in] kernel: convolution kernel

  • [in] convolutionControl: convolution control parameters

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if convolvedImage dimensions != inImage dimensions

  • lsst::pex::exceptions::InvalidParameterError: if inImage smaller than kernel in width or height

  • lsst::pex::exceptions::InvalidParameterError: if kernel width or height < 1

  • std::bad_alloc: when allocation of CPU memory fails

template<typename OutImageT, typename InImageT>
void convolveWithInterpolation(OutImageT &outImage, InImageT const &inImage, lsst::afw::math::Kernel const &kernel, ConvolutionControl const &convolutionControl)

Convolve an Image or MaskedImage with a spatially varying Kernel using linear interpolation.

This is a low-level convolution function that does not set edge pixels.

The algorithm is as follows:

  • divide the image into regions whose size is no larger than maxInterpolationDistance

  • for each region:

    • convolve it using convolveRegionWithInterpolation (which see)

Note that this routine will also work with spatially invariant kernels, but not efficiently.

Parameters
  • [out] outImage: convolved image = inImage convolved with kernel

  • [in] inImage: input image

  • [in] kernel: convolution kernel

  • [in] convolutionControl: convolution control parameters

Exceptions
  • lsst::pex::exceptions::InvalidParameterError: if outImage is not the same size as inImage

template<typename OutImageT, typename InImageT>
void convolveRegionWithInterpolation(OutImageT &outImage, InImageT const &inImage, KernelImagesForRegion const &region, ConvolveWithInterpolationWorkingImages &workingImages)

Convolve a region of an Image or MaskedImage with a spatially varying Kernel using interpolation.

This is a low-level convolution function that does not set edge pixels.

Warning

: this is a low-level routine that performs no bounds checking.

Parameters
  • [out] outImage: convolved image = inImage convolved with kernel

  • [in] inImage: input image

  • [in] region: kernel image region over which to convolve

  • [in] workingImages: working kernel images

struct ConvolveWithInterpolationWorkingImages
#include <Convolve.h>

kernel images used by convolveRegionWithInterpolation

class KernelImagesForRegion
#include <Convolve.h>

A collection of Kernel images for special locations on a rectangular region of an image

See the Location enum for a list of those special locations.

This is a low-level helper class for recursive convolving with interpolation. Many of these objects may be created during a convolution, and many will share kernel images. It uses shared pointers to kernels and kernel images for increased speed and decreased memory usage (at the expense of safety). Note that null pointers are NOT acceptable for the constructors!

Warning

The kernel images along the top and right edges are computed one row or column past the bounding box. This allows abutting KernelImagesForRegion to share corner and edge kernel images, which is useful when dividing a KernelImagesForRegion into subregions.

Warning

The bounding box for the region applies to the parent image.

Also note that it uses lazy evaluation: images are computed when they are wanted.

class RowOfKernelImagesForRegion
#include <Convolve.h>

A row of KernelImagesForRegion

Intended for iterating over subregions of a KernelImagesForRegion using computeNextRow.

class Spline

Subclassed by lsst::afw::math::detail::SmoothedSpline, lsst::afw::math::detail::TautSpline

struct TrapezoidalPacker
#include <TrapezoidalPacker.h>

A helper class ChebyshevBoundedField, for mapping trapezoidal matrices to 1-d arrays.

This class is not Swigged, and should not be included by any other .h files (including lsst/afw/math/detail.h); it’s for internal use by ChebyshevBoundedField only, and it’s only in a header file instead of that .cc file only so it can be unit tested.

We characterize the matrices by their number of columns (nx) and rows (ny), and the number of complete rows minus one (m).

This splits up the matrix into a rectangular part, in which the number of columns is the same for each row, and a wide trapezoidal or triangular part, in which the number of columns decreases by one for each row.

Here are some examples of how this class handles different kinds of matrices:

A wide trapezoidal matrix with orderX=4, orderY=3: nx=5, ny=4, m=0

0 1 2 3 4 5 6 7 8 9 10 11 12 13

A tall trapezoidal matrix with orderX=2, orderY=4 nx=3, ny=5, m=2

0 1 2 3 4 5 6 7 8 9 10 11

A triangular matrix with orderX=3, orderY=3 nx=4, ny=5, m=0

0 1 2 3 4 5 6 7 8 9

A wide rectangular matrix with orderX=3, orderY=2 nx=4, ny=3, m=3

0 1 2 3 4 5 6 7 8 9 10 11

A tall rectangular matrix with orderX=2, orderY=3 nx=3, ny=4, m=4

0 1 2 3 4 5 6 7 8 9 10 11

template<typename DestImageT, typename SrcImageT>
class WarpAtOnePoint
#include <WarpAtOnePoint.h>

A functor that computes one warped pixel

namespace details

Functions

template<class T>
T norm(const T &x)
template<class T>
T real(const T &x)
template<class T>
T Epsilon()
template<class T>
T MinRep()
template<class T>
T rescale_error(T err, T const &resabs, T const &resasc)
template<class UF>
bool intGKPNA(UF const &func, IntRegion<typename UF::result_type> &reg, typename UF::result_type const epsabs, typename UF::result_type const epsrel, std::map<typename UF::result_type, typename UF::result_type> *fxmap = 0)

Non-adaptive integration of the function f over the region ‘reg’.

Note

The algorithm computes first a Gaussian quadrature value then successive Kronrod/Patterson extensions to this result. The functions terminates when the difference between successive approximations (rescaled according to rescale_error) is less than either epsabs or epsrel * I, where I is the latest estimate of the integral. The order of the Gauss/Kronron/Patterson scheme is determined by which file is included above. Currently schemes starting with order 1 and order 10 are calculated. There seems to be little practical difference in the integration times using the two schemes, so I haven’t bothered to calculate any more.

template<class UF>
void intGKP(UF const &func, IntRegion<typename UF::result_type> &reg, typename UF::result_type const epsabs, typename UF::result_type const epsrel, std::map<typename UF::result_type, typename UF::result_type> *fxmap = 0)

An adaptive integration algorithm which computes the integral of f over the region reg.

The area and estimated error are returned as reg.Area() and reg.Err() If desired, *retx and *retf return std::vectors of x,f(x) respectively They only include the evaluations in the non-adaptive pass, so they do not give an accurate estimate of the number of function evaluations.

Note

First the non-adaptive GKP algorithm is tried. If that is not accurate enough (according to the absolute and relative accuracies, epsabs and epsrel), the region is split in half, and each new region is integrated. The routine continues by successively splitting the subregion which gave the largest absolute error until the integral converges.

template<class UF>
AuxFunc1<UF> Aux1(UF uf)

Auxiliary function 1

template<class UF>
AuxFunc2<UF> Aux2(UF uf)

Auxiliary function 2

template<class BF, class Tp>
binder2_1<BF> bind21(const BF &oper, const Tp &x)
template<class TF, class Tp>
binder3_1<TF> bind31(const TF &oper, const Tp &x)
int gkp_n(int level)
template<class T>
const std::vector<T> &gkp_x(int level)
template<class T>
const std::vector<T> &gkp_wa(int level)
template<class T>
const std::vector<T> &gkp_wb(int level)

Variables

const int NGKPLEVELS = 5
template<class UF>
struct AuxFunc1 : public std::unary_function<UF::argument_type, UF::result_type>
#include <Integrate.h>

Auxiliary struct 1

template<class T>
struct ConstantReg1 : public std::unary_function<T, IntRegion<T>>
#include <Integrate.h>

Helpers for constant regions for int2d, int3d:

template<typename BinaryFunctionT>
class FunctionWrapper : public std::unary_function<BinaryFunctionT::second_argument_type, BinaryFunctionT::result_type>
#include <Integrate.h>

Wrap an integrand in a call to a 1D integrator: romberg()

When romberg2D() is called, it wraps the integrand it was given in a FunctionWrapper functor. This wrapper calls romberg() on the integrand to get a 1D (along the x-coord, for constant y) result . romberg2D() then calls romberg() with the FunctionWrapper functor as an integrand.

namespace table

Unnamed Group

typedef lsst::geom::Angle Angle
typedef lsst::geom::SpherePoint SpherePoint

Unnamed Group

template<typename RecordT, typename Catalog, typename T>
std::shared_ptr<RecordT> _Catalog_find(Catalog const &catalog, T const &value, Key<T> const &key)
template<typename Catalog, typename T>
int _Catalog_lower_bound(Catalog const &catalog, T const &value, Key<T> const &key)
template<typename Catalog, typename T>
int _Catalog_upper_bound(Catalog const &catalog, T const &value, Key<T> const &key)
template<typename Catalog, typename T>
std::pair<int, int> _Catalog_equal_range(Catalog const &catalog, T const &value, Key<T> const &key)

Typedefs

typedef PointKey<int> Point2IKey
typedef PointKey<double> Point2DKey
using Box2IKey = BoxKey<lsst::geom::Box2I>
using Box2DKey = BoxKey<lsst::geom::Box2D>
typedef ColumnViewT<ExposureRecord> ExposureColumnView
typedef ExposureCatalogT<ExposureRecord> ExposureCatalog
typedef ExposureCatalogT<ExposureRecord const> ConstExposureCatalog
typedef CatalogT<BaseRecord> BaseCatalog
typedef CatalogT<BaseRecord const> ConstBaseCatalog
typedef ColumnViewT<SimpleRecord> SimpleColumnView
typedef SortedCatalogT<SimpleRecord> SimpleCatalog
typedef SortedCatalogT<SimpleRecord const> ConstSimpleCatalog
typedef SourceColumnViewT<SourceRecord> SourceColumnView
typedef SortedCatalogT<SourceRecord> SourceCatalog
typedef SortedCatalogT<SourceRecord const> ConstSourceCatalog
typedef ColumnViewT<AmpInfoRecord> AmpInfoColumnView
typedef CatalogT<AmpInfoRecord> AmpInfoCatalog
typedef CatalogT<AmpInfoRecord const> ConstAmpInfoCatalog
typedef Match<SimpleRecord, SimpleRecord> SimpleMatch
typedef Match<SimpleRecord, SourceRecord> ReferenceMatch
typedef Match<SourceRecord, SourceRecord> SourceMatch
typedef std::vector<SimpleMatch> SimpleMatchVector
typedef std::vector<ReferenceMatch> ReferenceMatchVector
typedef std::vector<SourceMatch> SourceMatchVector
typedef std::int64_t RecordId

Type used for unique IDs for records.

FITS isn’t fond of uint64, so we can save a lot of pain by using signed ints here unless we really need unsigned.

typedef lsst::afw::detection::Footprint Footprint
typedef boost::mpl::vector<RecordId, std::uint16_t, std::int32_t, float, double, lsst::geom::Angle, std::uint8_t> ScalarFieldTypes

An MPL vector of scalar field types.

typedef boost::mpl::vector<RecordId, std::uint16_t, std::int32_t, float, double, lsst::geom::Angle, std::uint8_t, Flag, std::string, Array<std::uint16_t>, Array<int>, Array<float>, Array<double>, Array<std::uint8_t>> FieldTypes

An MPL vector of all field types.

Enums

enum CoordinateType

Enum used to set units for geometric FunctorKeys.

Values:

PIXEL
CELESTIAL
enum SourceFitsFlags

Bitflags to be passed to SourceCatalog::readFits and SourceCatalog::writeFits

Note that these flags may also be passed when reading/writing SourceCatalogs via the Butler, by passing a “flags” key/value pair as part of the data ID.

Values:

SOURCE_IO_NO_FOOTPRINTS = 0x1

Do not read/write footprints at all.

SOURCE_IO_NO_HEAVY_FOOTPRINTS = 0x2

Read/write heavy footprints as non-heavy footprints.

Functions

SourceMatchVector matchXy(SourceCatalog const &cat1, SourceCatalog const &cat2, double radius, MatchControl const &mc = MatchControl())

Parameters
  • cat1: first catalog

  • cat2: second catalog

  • radius: match radius (pixels)

  • mc: how to do the matching (obeys MatchControl::findOnlyClosest)

Compute all tuples (s1,s2,d) where s1 belings to cat1, s2 belongs to cat2 and d, the distance between s1 and s2, in pixels, is at most radius. If cat1 and cat2 are identical, then this call is equivalent to matchXy(cat1,radius). The match is performed in pixel space (2d cartesian).

SourceMatchVector matchXy(SourceCatalog const &cat, double radius, MatchControl const &mc = MatchControl())

Parameters
  • cat: the catalog to self-match

  • radius: match radius (pixels)

  • mc: how to do the matching (obeys MatchControl::symmetricMatch)

Compute all tuples (s1,s2,d) where s1 != s2, s1 and s2 both belong to cat, and d, the distance between s1 and s2, in pixels, is at most radius. The match is performed in pixel space (2d cartesian).

SourceMatchVector matchXy(SourceCatalog const &cat1, SourceCatalog const &cat2, double radius, bool closest)

Compute all tuples (s1,s2,d) where s1 belings to cat1, s2 belongs to cat2 and d, the distance between s1 and s2, in pixels, is at most radius. If cat1 and cat2 are identical, then this call is equivalent to matchXy(cat1,radius). The match is performed in pixel space (2d cartesian).

Parameters
  • [in] cat1: first catalog

  • [in] cat2: second catalog

  • [in] radius: match radius (pixels)

  • [in] closest: if true then just return the closest match

SourceMatchVector matchXy(SourceCatalog const &cat, double radius, bool symmetric)

Compute all tuples (s1,s2,d) where s1 != s2, s1 and s2 both belong to cat, and d, the distance between s1 and s2, in pixels, is at most radius. The match is performed in pixel space (2d cartesian).

Parameters
  • [in] cat: the catalog to self-match

  • [in] radius: match radius (pixels)

  • [in] symmetric: if cat to true symmetric matches are produced: i.e. if (s1, s2, d) is reported, then so is (s2, s1, d).

template<typename Cat1, typename Cat2>
std::vector<Match<typename Cat1::Record, typename Cat2::Record>> matchRaDec(Cat1 const &cat1, Cat2 const &cat2, lsst::geom::Angle radius, MatchControl const &mc = MatchControl())

Parameters
  • cat1: first catalog

  • cat2: second catalog

  • radius: match radius

  • mc: how to do the matching (obeys MatchControl::findOnlyClosest)

Compute all tuples (s1,s2,d) where s1 belings to cat1, s2 belongs to cat2 and d, the distance between s1 and s2, is at most radius. If cat1 and cat2 are identical, then this call is equivalent to matchRaDec(cat1,radius). The match is performed in ra, dec space.

This is instantiated for Simple-Simple, Simple-Source, and Source-Source catalog combinations.

template<typename Cat>
std::vector<Match<typename Cat::Record, typename Cat::Record>> matchRaDec(Cat const &cat, lsst::geom::Angle radius, MatchControl const &mc = MatchControl())

Parameters
  • cat: the catalog to self-match

  • radius: match radius

  • mc: how to do the matching (obeys MatchControl::symmetricMatch)

template<typename Cat1, typename Cat2>
std::vector<Match<typename Cat1::Record, typename Cat2::Record>> matchRaDec(Cat1 const &cat1, Cat2 const &cat2, lsst::geom::Angle radius, bool closest)

Compute all tuples (s1,s2,d) where s1 belings to cat1, s2 belongs to cat2 and d, the distance between s1 and s2, is at most radius. If cat1 and cat2 are identical, then this call is equivalent to matchRaDec(cat1,radius). The match is performed in ra, dec space.

This is instantiated for Simple-Simple, Simple-Source, and Source-Source catalog combinations.

Parameters
  • [in] cat1: first catalog

  • [in] cat2: second catalog

  • [in] radius: match radius

  • [in] closest: if true then just return the closest match

template<typename Cat>
std::vector<Match<typename Cat::Record, typename Cat::Record>> matchRaDec(Cat const &cat, lsst::geom::Angle radius, bool symmetric)

Compute all tuples (s1,s2,d) where s1 != s2, s1 and s2 both belong to cat, and d, the distance between s1 and s2, is at most radius. The match is performed in ra, dec space.

This is instantiated for Simple and Source catalogs.

Parameters
  • [in] cat: the catalog to self-match

  • [in] radius: match radius

  • [in] symmetric: if cat to true symmetric matches are produced: i.e. if (s1, s2, d) is reported, then so is (s2, s1, d).

template<typename Record1, typename Record2>
BaseCatalog packMatches(std::vector<Match<Record1, Record2>> const &matches)

Return a table representation of a MatchVector that can be used to persist it.

The schema of the returned object has “first” (RecordId), “second” (RecordID), and “distance” (double) fields.

Parameters
  • [in] matches: A std::vector of Match objects to convert to table form.

template<typename Cat1, typename Cat2>
std::vector<Match<typename Cat1::Record, typename Cat2::Record>> unpackMatches(BaseCatalog const &matches, Cat1 const &cat1, Cat2 const &cat2)

Reconstruct a MatchVector from a BaseCatalog representation of the matches and a pair of catalogs.

If an ID cannot be found in the given tables, that pointer will be set to null in the returned match vector.

Note

The first and second catalog arguments must be sorted in ascending ID order on input; this will allow us to use binary search algorithms to find the records referred to by the match table.

This is instantiated for Simple-Simple, Simple-Source, and Source-Source catalog combinations.

Parameters
  • [in] matches: A normalized BaseCatalog representation, as produced by packMatches.

  • [in] cat1: A CatalogT containing the records used on the ‘first’ side of the match, sorted by ascending ID.

  • [in] cat2: A CatalogT containing the records used on the ‘second’ side of the match, sorted by ascending ID. May be the same as first.

template<typename ReferenceCollection>
void updateRefCentroids(geom::SkyWcs const &wcs, ReferenceCollection &refList)

Update centroids in a collection of reference objects

Template Parameters
  • RefCollection: Type of sequence of reference objects, e.g. lsst::afw::table::SimpleCatalog or std::vector<std::shared_ptr<lsst::afw::table::SimpleRecord>>

Parameters
  • [in] wcs: WCS to map from sky to pixels

  • [inout] refList: Collection of reference objects. The schema must have three fields:

    • ”coord”: a field containing an ICRS lsst::afw::SpherePoint; this field is read

    • ”centroid”: a field containing lsst::geom::Point2D; this field is written

    • ”hasCentroid”: a flag; this field is written

Exceptions
  • lsst::pex::exceptions::NotFoundError: if refList’s schema does not have the required fields.

template<typename SourceCollection>
void updateSourceCoords(geom::SkyWcs const &wcs, SourceCollection &sourceList)

Update sky coordinates in a collection of source objects

Template Parameters
  • SourceCollection: Type of sequence of sources, e.g. lsst::afw::table::SourceCatalog or std::vector<std::shared_ptr<lsst::afw::table::SourceRecord>>

Parameters
  • [in] wcs: WCS to map from pixels to sky

  • [inout] sourceList: Collection of sources. The schema must have two fields:

    • ”slot_Centroid”: a field containing lsst::geom::Point2D; this field is read

    • ”coord”: a field containing an ICRS lsst::afw::SpherePoint; this field is written

Exceptions
  • lsst::pex::exceptions::NotFoundError: if refList’s schema does not have the required fields.

class AliasMap
#include <AliasMap.h>

Mapping class that holds aliases for a Schema

Aliases need not be complete, but they must match to the beginning of a field name to be useful. For example, if “a_b_c” is a true field name, “x_->a_b” is a valid alias that will cause “x_y_c” to map to “a_b_c”, but “y_z->b_c” will not cause “a_y_z” to be matched.

Aliases are not checked to see if they match any existing fields, and if an alias has the same name as a field name, it will take precedence and hide the true field.

Unlike the other components of a Schema, aliases can be modified and removed, even after a Table has been constructed from the Schema.

AliasMaps are shared when Schemas are copy-constructed, but can be separated manually by calling Schema::disconnectAliases() or Schema::setAliasMap(). In addition, the AliasMap is deep-copied when used to construct a Table (or Catalog).

In order to allow Tables to react to changes in aliases (which may be used to define cached Keys held by the table, as in SourceTable’s “slots” mechanism), an AliasMap that is part of a Schema held by a Table will hold a pointer to that Table, and call BaseTable::handleAliasChanges() when its aliases are set or removed.

template<typename T>
class Array
#include <misc.h>

Tag types used to declare specialized field types.

See the documentation for specializations of FieldBase and KeyBase for more information.

template<typename T>
class ArrayKey : public lsst::afw::table::FunctorKey<ndarray::Array<T const, 1, 1>>, public lsst::afw::table::ReferenceFunctorKey<ndarray::ArrayRef<T, 1, 1>>, public lsst::afw::table::ConstReferenceFunctorKey<ndarray::ArrayRef<T const, 1, 1>>
#include <arrays.h>

A FunctorKey used to get or set a ndarray::Array from a sequence of scalar Keys.

ArrayKey operates on the convention that arrays are defined by a set of contiguous scalar fields (i.e. added to the Schema in order, with no interruption) of the same type, with a common field name prefix and “_0”, “_1” etc. suffixes.

class BaseColumnView
#include <BaseColumnView.h>

Column-wise view into a sequence of records that have been allocated contiguously.

A BaseColumnView can be created from any iterator range that dereferences to records, as long as those records’ field data is contiguous in memory. In practice, that means they must have been created from the same table, and be in the same order they were created (with no deletions). It also requires that those records be allocated in the same block, which can be guaranteed with BaseTable::preallocate().

Geometric (point and shape) fields cannot be accessed through a BaseColumnView, but their scalar components can be.

BaseColumnView and its subclasses are always non-const views into a catalog, and so cannot be obtained from a catalog-of-const (trying this results in an exception, not a compilation error). As a result, all its accessors return arrays of non-const elements, even though they are themselves const member functions. This is no different from a shared_ptr<T>’s get() member function returning a non-const T*, even though get() is a const member function.

Subclassed by lsst::afw::table::ColumnViewT< RecordT >

class BaseRecord
#include <BaseRecord.h>

Base class for all records.

BaseRecord is a polymorphic base class that provides the core record interface: access to fields and links back to the table it is associated with. Field access is provided by the templated get, set, and operator[] member functions. As templates they are nonvirtual and cannot be overridden by subclasses. The implementations for these accessors is in the FieldBase template specializations.

Each subclass of BaseRecord should be paired with a subclass of BaseTable. All record creation goes through a table, as the table allocates the memory used to store a record’s fields and holds the Schema instance that defines those fields.

Records are noncopyable, and are hence usually passed by shared_ptr or [const-]reference.

Subclassed by lsst::afw::detection::PeakRecord, lsst::afw::table::ExposureRecord, lsst::afw::table::SimpleRecord

class BaseTable : public std::enable_shared_from_this<BaseTable>
#include <BaseTable.h>

Base class for all tables.

Tables have two largely distinct purposes:

  • They serve as factories for records, allocating their field data in blocks.

  • They carry additional information (such as the schema) that should be shared by multiple records.

It’s mostly a matter of convenience that we use the same class to serve both needs.

Tables do not actually maintain a list of all the records they have allocated - but those records hold a pointer back to the table. This allows the work of holding and iterating over records to be delegated to templated container classes (such as CatalogT) while allowing tables to be polymorphic, non-template classes. In some sense, then, it may make more sense to think of a table as a combination factory and “container header”.

Tables are always created in shared_ptrs (a requirement of enable_shared_from_this). BaseTable provides a make static member function to create a new table, and most derived table classes should do the same.

Each table class should be associated with a particular record class (1-to-1). Each table instance may be associated with many record instances.

Subclassed by lsst::afw::detection::PeakTable, lsst::afw::table::ExposureTable, lsst::afw::table::SimpleTable

class BitsColumn
#include <BaseColumnView.h>

A packed representation of a collection of Flag field columns.

The packing of bits here is not necessarily the same as the packing using in the actual table, as the latter may contain more than 64 bits spread across multiple integers.

A BitsColumn can only be constructed by calling BaseColumnView::getBits().

template<typename Box>
class BoxKey : public lsst::afw::table::FunctorKey<Box>
#include <aggregates.h>

A FunctorKey used to get or set a lsst::geom::Box2I or Box2D from a (min, max) pair of PointKeys.

The Box2IKey and Box2DKey typedefs should be preferred to using the template name directly.

template<typename BaseT>
class CatalogIterator : public boost::iterator_adaptor<CatalogIterator<BaseT>, BaseT, BaseT::value_type::element_type>
#include <Catalog.h>

Iterator class for CatalogT.

Iterators dereference to record references or const references, even though the CatalogT container is based on a vector of shared_ptr internally. This is usually very convenient (and is one of the reasons for having a custom container class in the first place).

Sometimes, however, we’d like to get a shared_ptr from an iterator (especially because records are noncopyable). With that in mind, CatalogIterator is implicitly convertible to the shared_ptr type it holds internally, and can also be assigned a shared_ptr to set the pointer in the underlying container. This conversion makes sense from the perspective that both iterators and smart pointers mimic the interface of pointers and provide the same interface to get at the underlying record.

template<typename RecordT>
class CatalogT
#include <Catalog.h>

A custom container class for records, based on std::vector.

CatalogT wraps a std::vector<std::shared_ptr<RecordT>> in an interface that looks more like a std::vector<RecordT>; its iterators and accessors return references or const references, rather than pointers, making them easier to use. It also holds a table, which is used to allocate new records and determine the schema, but no checking is done to ensure that records added to the catalog use the same table or indeed have the same schema.

Because a CatalogT is holds shared_ptrs internally, many of its operations can be either shallow or deep, with new deep copies allocated by the catalog’s table object. New records can be also be inserted by pointer (shallow) or by value (deep).

The constness of records is determined by the constness of the first template parameter to CatalogT; a container instance is always either const or non-const in that respect (like smart pointers). Also like smart pointers, const member functions (and by extension, const_iterators) do not allow the underlying pointers to be changed, while non-const member functions and iterators do.

CatalogT does not permit empty (null) pointers as elements. As a result, CatalogT has no resize member function.

CatalogT has a very different interface in Python; it mimics Python’s list instead of C++’s std::vector. It is also considerably simpler, because it doesn’t need to deal with iterator ranges or the distinction between references and shared_ptrs to records. See the Python docstring for more information.

Subclassed by lsst::afw::table::SortedCatalogT< RecordT >

class CentroidSlotDefinition : public lsst::afw::table::SlotDefinition
#include <slots.h>

SlotDefinition specialization for centroids.

template<typename RecordT>
class ColumnViewT : public lsst::afw::table::BaseColumnView

Subclassed by lsst::afw::table::SourceColumnViewT< RecordT >

template<typename T>
class ConstReferenceFunctorKey
#include <FunctorKey.h>

Base class for objects that can return a const reference to part of a record, but are not a true Key

Objects that inherit from ConstReferenceFunctorKey can be passed to BaseRecord::operator[], just as true Keys can, but the record will simply pass itself to ReferenceFunctorKey::getConstReference().

Note

We’d combine this with the ReferenceFunctorKey interface if it weren’t for the fact that we can’t pass multiple template arguments to a Swig macro if either contains commas, and we’d need that to wrap a combined interface base class.

class CoordKey : public lsst::afw::table::FunctorKey<lsst::geom::SpherePoint>
#include <aggregates.h>

A FunctorKey used to get or set celestial coordinates from a pair of lsst::geom::Angle keys.

Coords are always stored and returned in the ICRS system. Coords in other systems may be assigned, but this will result in a conversion to ICRS.

class EllipseKey : public lsst::afw::table::FunctorKey<lsst::afw::geom::ellipses::Ellipse>
#include <aggregates.h>

A FunctorKey used to get or set a geom::ellipses::Ellipse from an (xx,yy,xy,x,y) tuple of Keys.

template<typename RecordT>
class ExposureCatalogT : public lsst::afw::table::SortedCatalogT<RecordT>
#include <Exposure.h>

Custom catalog class for ExposureRecord/Table.

We don’t expect to subclass ExposureRecord/Table, so unlike other Catalogs we can (and do) define some ExposureCatalogT member functions in Exposure.cc where the explicit instantiation is done.

class ExposureRecord : public lsst::afw::table::BaseRecord
#include <Exposure.h>

Record class used to store exposure metadata.

class ExposureTable : public lsst::afw::table::BaseTable
#include <Exposure.h>

Table class used to store exposure metadata.

Record class used to store exposure metadata.

template<typename T>
struct Field : public lsst::afw::table::FieldBase<T>
#include <Field.h>

A description of a field in a table.

Field combines a type with the field name, documentation, units, and in some cases, the size of the field.

Specializations for different field types are inherited through FieldBase; see the documentation for those specializations for additional information about particular field types.

template<typename T>
struct FieldBase
#include <FieldBase.h>

Field base class default implementation (used for numeric scalars and lsst::geom::Angle).

Subclassed by lsst::afw::table::Key< afw::table::Array< Scalar > >, lsst::afw::table::Key< afw::table::Flag >, lsst::afw::table::Key< afw::table::RecordId >, lsst::afw::table::Key< CentroidElement >, lsst::afw::table::Key< double >, lsst::afw::table::Key< Element >, lsst::afw::table::Key< ErrElement >, lsst::afw::table::Key< float >, lsst::afw::table::Key< FluxErrElement >, lsst::afw::table::Key< int >, lsst::afw::table::Key< lsst::afw::table::Array< int > >, lsst::afw::table::Key< lsst::afw::table::Array< Scalar > >, lsst::afw::table::Key< lsst::geom::Angle >, lsst::afw::table::Key< Mag >, lsst::afw::table::Key< MagErrElement >, lsst::afw::table::Key< meas::base::Flux >, lsst::afw::table::Key< RecordId >, lsst::afw::table::Key< Scalar >, lsst::afw::table::Field< T >, lsst::afw::table::Key< T >

template<typename U>
struct FieldBase<Array<U>>
#include <FieldBase.h>

Field base class specialization for arrays.

The Array tag is used for both fixed-length (same size in every record, accessible via ColumnView) and variable-length arrays; variable-length arrays are initialized with a size of 0. Ideally, we’d use complete different tag classes for those two very different types, but boost::variant and boost::mpl put a limit of 20 on the number of field types, and we’re running out. In a future reimplementation of afw::table, we should fix this.

template<>
struct FieldBase<Flag>
#include <Flag.h>

Specialization for Flag fields.

Flag fields are handled specially in many places, because their keys have both an offset into an integer element and the bit in that element; while other fields have one or more elements per field, Flags have multiple fields per element. This means we can’t put all the custom code for Flag in FieldBase, and because Flags have an explicit Key specialization, we put the record access implementation in Key.

Subclassed by lsst::afw::table::Field< Flag >, lsst::afw::table::Key< Flag >

template<>
struct FieldBase<std::string>
#include <FieldBase.h>

Field base class specialization for strings.

Subclassed by lsst::afw::table::Key< std::string >

class FluxSlotDefinition : public lsst::afw::table::SlotDefinition
#include <slots.h>

SlotDefinition specialization for fluxes.

template<typename T>
class FunctorKey : public lsst::afw::table::OutputFunctorKey<T>, public lsst::afw::table::InputFunctorKey<T>
#include <FunctorKey.h>

Convenience base class that combines the OutputFunctorKey and InputFunctorKey

Most objects that can set a calculated or compound value from a record can also get that value back, so we provide this class to aggregate those interfaces.

class IdFactory
#include <IdFactory.h>

A polymorphic functor base class for generating record IDs for a table.

The IDs produced by an IdFactory need not be sequential, but they must be unique, both with respect to the IDs it generates itself and those passed to it via the notify() member function. Valid IDs must be nonzero, as zero is used to indicate null in some contexts.

template<typename T>
class InputFunctorKey
#include <FunctorKey.h>

Base class for objects that can set a value on a record, but are not a true Key themselves.

Objects that inherit from InputFunctorKey can be passed to BaseRecord::set(), just as true Keys can, but the record will simply pass itself to OutputFunctorKey::set() along with the value that was passed.

Subclassed by lsst::afw::table::FunctorKey< T >

template<typename T>
class Key : public lsst::afw::table::KeyBase<T>, public lsst::afw::table::FieldBase<T>
#include <Key.h>

A class used as a handle to a particular field in a table.

All access to table data ultimately goes through Key objects, which know (via an internal offset) how to address and cast the internal data buffer of a record or table.

Keys can be obtained from a Schema by name:

schema.find("myfield").key

and are also returned when a new field is added. Compound and array keys also provide accessors to retrieve scalar keys to their elements (see the documentation for the KeyBase specializations), even though these element keys do not correspond to a field that exists in any Schema. For example:

Schema schema;
Key< Array<float> > arrayKey = schema.addField< Array<float> >("array", "docs for array", 5);
Key< Point<int> > pointKey = schema.addField< Point<int> >("point", "docs for point");
Key<float> elementKey = arrayKey[3];
Key<int> xKey = pointKey.getX();
std::shared_ptr<BaseTable> table = BaseTable::make(schema);
std::shared_ptr<BaseRecord> record = table.makeRecord();
assert(&record[arrayKey][3] == &record[elementKey3]);
assert(record.get(pointKey).getX() == record[xKey]);

Key inherits from FieldBase to allow a key for a dynamically-sized field to know its size without needing to specialize Key itself or hold a full Field object.

template<>
class Key<Flag> : public lsst::afw::table::KeyBase<Flag>, public lsst::afw::table::FieldBase<Flag>
#include <Flag.h>

Key specialization for Flag.

Flag fields are special; their keys need to contain not only the offset to the integer element they share with other Flag fields, but also their position in that shared field.

Flag fields operate mostly like a bool field, but they do not support reference access, and internally they are packed into an integer shared by multiple fields so the marginal cost of each Flag field is only one bit.

template<typename T>
class KeyBase
#include <KeyBase.h>

A base class for Key that allows subfield keys to be extracted for some field types.

Subclassed by lsst::afw::table::Key< afw::table::Array< Scalar > >, lsst::afw::table::Key< afw::table::Flag >, lsst::afw::table::Key< afw::table::RecordId >, lsst::afw::table::Key< CentroidElement >, lsst::afw::table::Key< double >, lsst::afw::table::Key< Element >, lsst::afw::table::Key< ErrElement >, lsst::afw::table::Key< float >, lsst::afw::table::Key< FluxErrElement >, lsst::afw::table::Key< int >, lsst::afw::table::Key< lsst::afw::table::Array< int > >, lsst::afw::table::Key< lsst::afw::table::Array< Scalar > >, lsst::afw::table::Key< lsst::geom::Angle >, lsst::afw::table::Key< Mag >, lsst::afw::table::Key< MagErrElement >, lsst::afw::table::Key< meas::base::Flux >, lsst::afw::table::Key< RecordId >, lsst::afw::table::Key< Scalar >, lsst::afw::table::Key< std::string >, lsst::afw::table::Key< T >

template<typename U>
class KeyBase<Array<U>>
#include <KeyBase.h>

KeyBase specialization for Arrays.

template<>
class KeyBase<Flag>
#include <Flag.h>

A base class for Key that allows the underlying storage field to be extracted.

Subclassed by lsst::afw::table::Key< Flag >

template<typename Record1, typename Record2>
struct Match
#include <Match.h>

Lightweight representation of a geometric match between two records.

This is a template so it can hold derived record classes without a lot of casting and properly use lsst::geom::Angle for the distance when we do spherical coordinate matches.

class MatchControl
#include <Match.h>

Pass parameters to algorithms that match list of sources

template<typename T>
class OutputFunctorKey
#include <FunctorKey.h>

Base class for objects that can extract a value from a record, but are not a true Key themselves.

Objects that inherit from OutputFunctorKey can be passed to BaseRecord::get(), just as true Keys can, but the record will simply pass itself to OutputFunctorKey::get() and return the result.

Subclassed by lsst::afw::table::FunctorKey< T >

template<typename T>
class PointKey : public lsst::afw::table::FunctorKey<lsst::geom::Point<T, 2>>
#include <aggregates.h>

A FunctorKey used to get or set a lsst::geom::Point from an (x,y) pair of int or double Keys.

class QuadrupoleKey : public lsst::afw::table::FunctorKey<lsst::afw::geom::ellipses::Quadrupole>
#include <aggregates.h>

A FunctorKey used to get or set a geom::ellipses::Quadrupole from a tuple of constituent Keys.

template<typename T>
class ReferenceFunctorKey
#include <FunctorKey.h>

Base class for objects that can return a non-const reference to part of a record, but are not a true Key

Objects that inherit from ReferenceFunctorKey can be passed to BaseRecord::operator[], just as true Keys can, but the record will simply pass itself to ReferenceFunctorKey::getReference().

Note

We’d combine this with the ConstReferenceFunctorKey interface if it weren’t for the fact that we can’t pass multiple template arguments to a Swig macro if either contains commas, and we’d need that to wrap a combined interface base class.

class Schema
#include <Schema.h>

Defines the fields and offsets for a table.

Schema behaves like a container of SchemaItem objects, mapping a descriptive Field object with the Key object used to access record and ColumnView values. A Schema is the most important ingredient in creating a table.

Because offsets for fields are assigned when the field is added to the Schema, Schemas do not support removing fields, though they do allow renaming.

Field names in Schemas are expected to be underscore-separated names (e.g. ‘a_b_c’, but see afwTableFieldNames for the full conventions, including when to use underscores vs. CamelCase). The SubSchema class and Schema::operator[] provide a heirarchical interface to these names, but are implemented entirely as string splitting/joining operations that ultimately forward to member functions that operate on the fully-qualified field name, so there is no requirement that names be separated by underscores, and no performance advantage to using a SubSchema.

A SchemaMapper object can be used to define a relationship between two Schemas to be used when copying values from one table to another or loading/saving selected fields to disk.

Schema uses copy-on-write, and hence should always be held by value rather than smart pointer. When creating a Python interface, functions that return Schema by const reference should be converted to return by value (returnCopy) to ensure proper memory management and encapsulation.

template<typename T>
struct SchemaItem
#include <SchemaImpl.h>

A simple pair-like struct for mapping a Field (name and description) with a Key (used for actual data access).

class SchemaMapper
#include <SchemaMapper.h>

A mapping between the keys of two Schemas, used to copy data between them.

SchemaMapper is initialized with its input Schema, and contains member functions to add mapped or unmapped fields to the output Schema.

class ShapeSlotDefinition : public lsst::afw::table::SlotDefinition
#include <slots.h>

SlotDefinition specialization for shapes.

class SimpleRecord : public lsst::afw::table::BaseRecord
#include <Simple.h>

Record class that must contain a unique ID field and a celestial coordinate field.

SimpleTable / SimpleRecord are intended to be the base class for records representing astronomical objects. In additional to the minimal schema and the convenience accessors it allows, a SimpleTable may hold an IdFactory object that is used to assign unique IDs to new records.

Subclassed by lsst::afw::table::SourceRecord

class SimpleTable : public lsst::afw::table::BaseTable
#include <Simple.h>

Table class that must contain a unique ID field and a celestial coordinate field.

Record class that must contain a unique ID field and a celestial coordinate field.

SimpleTable / SimpleRecord are intended to be the base class for records representing astronomical objects. In additional to the minimal schema and the convenience accessors it allows, a SimpleTable may hold an IdFactory object that is used to assign unique IDs to new records.

Subclassed by lsst::afw::table::SourceTable

class SlotDefinition
#include <slots.h>

Base class for helper classes that define slots on SourceTable/SourceRecord.

Each type of slot corresponds to a subclass of SlotDefinition, and each actual slot corresponds to a particular field name prefix. For instance, to look up the centroid slot, we look for fields named “slot_Centroid_x” and “slot_Centroid_y”. Instead of actually naming a particular field that, however, we use Schema’s alias mechanism (see AliasMap) to make these field name lookups resolve to the name of other fields. The actual definition of the slots is thus managed by the Schema’s AliasMap, though a SourceTable object will cache Keys for the various slots to make sure accessing slot values is efficient (more precisely, when you set an alias related to a slot on an AliasMap, any table it corresponds to will receive a notification that it should update its Keys). These cached Keys are actually stored within the SlotDefinition (as data members of derived classes).

Note that the uncertainty and failure flag components of slots are not required; a slot may have only a measurement defined, or a measurement and either one of these (but not both). A slot may not have only an uncertainty and/or a a failure flag, however.

A SlotDefinition instance is not just an internal object used by SourceTable; it can also be used to inspect the slots via SourceTable::getXxxSlot(), which is now the preferred way to access the Keys that slots correspond to. SlotDefinition objects should only be constructed by SourceTable, however.

Subclassed by lsst::afw::table::CentroidSlotDefinition, lsst::afw::table::FluxSlotDefinition, lsst::afw::table::ShapeSlotDefinition

struct SlotSuite
#include <slots.h>

An aggregate containing all of the current slots used in SourceTable.

This is essentially for internal use by SourceTable only; it is defined here to keep the source code for the slot mechanism in one place as much as possible.

template<typename RecordT>
class SortedCatalogT : public lsst::afw::table::CatalogT<RecordT>
#include <SortedCatalog.h>

Custom catalog class for record/table subclasses that are guaranteed to have an ID, and should generally be sorted by that ID.

For a record/table pair to be used with SortedCatalogT, the table class must provide a static getIdKey() member function that returns the key to the ID field.

Subclassed by lsst::afw::table::ExposureCatalogT< RecordT >

class SourceRecord : public lsst::afw::table::SimpleRecord
#include <Source.h>

Record class that contains measurements made on a single exposure.

Sources provide four additions to SimpleRecord / SimpleRecord:

  • Specific fields that must always be present, with specialized getters. The schema for a SourceTable should always be constructed by starting with the result of SourceTable::makeMinimalSchema.

  • A shared_ptr to a Footprint for each record.

  • A system of aliases (called slots) in which a SourceTable instance stores keys for particular measurements (a centroid, a shape, and a number of different fluxes) and SourceRecord uses this keys to provide custom getters and setters. These are not separate fields, but rather aliases that can point to custom fields. See the SlotDefinition hierarchy for more information.

class SourceTable : public lsst::afw::table::SimpleTable
#include <Source.h>

Table class that contains measurements made on a single exposure.

Record class that contains measurements made on a single exposure.

Sources provide four additions to SimpleRecord / SimpleRecord:

  • Specific fields that must always be present, with specialized getters. The schema for a SourceTable should always be constructed by starting with the result of SourceTable::makeMinimalSchema.

  • A shared_ptr to a Footprint for each record.

  • A system of aliases (called slots) in which a SourceTable instance stores keys for particular measurements (a centroid, a shape, and a number of different fluxes) and SourceRecord uses this keys to provide custom getters and setters. These are not separate fields, but rather aliases that can point to custom fields. See the SlotDefinition hierarchy for more information.

class SubSchema
#include <Schema.h>

A proxy type for name lookups in a Schema.

Elements of schema names are assumed to be separated by underscores (“a_b_c”); an incomplete lookup is one that does not resolve to a field. Not that even complete lookups can have nested names; a Point field, for instance, has “x” and “y” nested names.

This proxy object is implicitly convertible to both the appropriate Key type and the appropriate Field type, if the name is a complete one, and supports additional find() operations for nested names.

SubSchema is implemented as a proxy that essentially calls Schema::find after concatenating strings. It does not provide any performance advantage over using Schema::find directly. It is also lazy, so looking up a name prefix that does not exist within the schema is not considered an error until the proxy is used.

Some examples:

Schema schema(false);
Key<int> a_i = schema.addField<int>("a_i", "integer field");
Key< Point<double> > a_p = schema.addField< Point<double> >("a_p", "point field");

assert(schema["a_i"] == a_i);
SubSchema a = schema["a"];
assert(a["i"] == a_i);
Field<int> f_a_i = schema["a_i"];
assert(f_a_i.getDoc() == "integer field");
assert(schema["a_i"] == "a_i");
assert(schema.find("a_p_x") == a_p.getX());

namespace detail

Functions

int indexCovariance(int i, int j)

Defines the ordering of packed covariance matrices.

This storage is equivalent to LAPACK ‘UPLO=U’.

int computeCovariancePackedSize(int size)

Defines the packed size of a covariance matrices.

struct FlagExtractor
#include <BaseColumnView.h>

Functor to compute a flag bit, used to create an ndarray expression template for flag columns.

struct RecordData
#include <BaseTable.h>

Helper struct that contains the information passed from BaseTable to BaseRecord at construction.

This can’t be a nested class of either of those two classes for dependency reasons, but it should nevertheless be considered opaque by all derived Table and Record classes.

class SchemaImpl
#include <SchemaImpl.h>

A private implementation class to hide the messy details of Schema.

This can’t be a real pimpl class, because some of the most important functionality is in the forEach function, a templated function we can’t explicitly instantiate in a source file. But putting all the details here draws a clear line between what users should look at (Schema) and what they shouldn’t (this).

Because Schema holds SchemaImpl by shared pointer, one SchemaImpl can be shared between multiple Schemas (and SubSchemas), which implement copy-on-write by creating a new SchemaImpl if the pointer they have isn’t unique when they are modified.

class SchemaMapperImpl
#include <SchemaMapperImpl.h>

A private implementation class to hide the messy details of SchemaMapper.

This class is very similar in spirit to SchemaImpl; look there for more information (though SchemaMapper is not copy-on-write).

namespace io

Functions

LSST_EXCEPTION_TYPE(PersistenceError, lsst::pex::exceptions::IoError, lsst::afw::table::io::PersistenceError)

An exception thrown when problems occur during persistence. An exception thrown when an InputArchive’s contents do not make sense.

This is the exception thrown by the LSST_ARCHIVE_ASSERT macro.

struct ArchiveIndexSchema
#include <ArchiveIndexSchema.h>

Schema for the index catalog that specifies where objects are stored in the data catalogs.

Each row in the index catalog corresponds to a combination of an object and a data catalog, and contains the range of rows used by that object in the catalog (in the ‘row0’ and ‘nrows’ fields). The ‘cat.archive’ field indicates which catalog in the archive the index entry refers to (where 0 is the index itself, and 1 is the first data catalog), and ‘cat.persistable’ refers to which catalog the index entry refers to from the perspective of the saved object.

An object may thus have more than one row in the index, but the ‘id’ and ‘name’ fields must be the same for all index entires that correspond to a single object. These contain, respectively, the unique ID returned by OutputArchive::put and the name returned by Persistable::getPersistenceName() and used by InputArchive to look up a PersistableFactory in the registry.

class CatalogVector : public std::vector<BaseCatalog>
#include <CatalogVector.h>

A vector of catalogs used by Persistable.

This should really be thought of as just a typedef, but we can’t forward-declare a typedef to a template class, so we use a trivial subclass instead. That may seem like a dirty hack, but it has a huge benefit in keeping compilation times down: it keeps us from needing to include Catalog.h in Persistable.h, which otherwise would pull all of the afw::table headers into the header of any class that wanted to make use of a Persistable subclass.

CatalogVector is also used in such limited circumstances that we don’t really have to worry about the fact that std::vector doesn’t have a virtual destructor and that we only have default and copy constructors for CatalogVector.

class FitsColumnReader
#include <FitsSchemaInputMapper.h>

Polymorphic reader interface used to read different kinds of objects from one or more FITS binary table columns.

class FitsReader
#include <FitsReader.h>

A utility class for reading FITS binary tables.

FitsReader itself provides the implementation for reading standard FITS binary tables (with a limited subset of FITS column types), but it also allows subclasses to be used instead, depending on what’s actually in the FITS file. If the FITS header has the key “AFW_TABLE” with a value other than “BASE”, FitsReader::apply consults a registry of subclasses to retreive one corresponding to that key. This means the type of records/tables loaded correctly depends on the file itself, rather than the caller. For instance, if you load a FITS table corresponding to a saved SourceCatalog using BaseCatalog::readFits, you’ll actually get a BaseCatalog whose record are actually SourceRecords and whose table is actually a SourceTable. On the other hand, if you try to load a non-Source FITS table into a SourceCatalog, you’ll get an exception when it tries to dynamic_cast the table to a SourceTable.

class FitsSchemaInputMapper
#include <FitsSchemaInputMapper.h>

A class that describes a mapping from a FITS binary table to an afw::table Schema.

A FitsSchemaInputMapper is created every time a FITS binary table is read into an afw::table catalog, allowing limited customization of the mapping between on-disk FITS table columns an in-memory fields by subclasses of BaseTable.

The object is constructed from a daf::base::PropertyList that represents the FITS header, which is used to populate a custom container of FitsSchemaItems. These can then be retrieved by name or column number via the find() methods, allowing the user to create custom readers for columns or groups of columns via addColumnReader(). They can also be removed from the “regular” fields via the erase() method. Those regular fields are filled in by the finalize() method, which automatically generates mappings for any FitsSchemaItems that have not been removed by calls to erase(). Once finalize() has been called, readRecord() may be called repeatedly to read FITS rows into record objects according to the mapping that has been defined.

struct FitsSchemaItem
#include <FitsSchemaInputMapper.h>

A structure that describes a field as a collection of related strings read from the FITS header.

class FitsWriter
#include <FitsWriter.h>

Writer object for FITS binary tables.

FitsWriter itself provides support for writing FITS binary tables from base containers. Derived record/base pairs should derive their own writer from FitsWriter and reimplement BaseTable::makeFitsWriter to return it. Subclasses will usually delegate most of the work back to FitsWriter.

class InputArchive
#include <InputArchive.h>

A multi-catalog archive object used to load table::io::Persistable objects.

An InputArchive can be constructed directly from the catalogs produced by OutputArchive, or more usefully, read from a multi-extension FITS file.

See

OutputArchive

class OutputArchive
#include <OutputArchive.h>

A multi-catalog archive object used to save table::io::Persistable objects.

OutputArchive should generally be used directly only by objects that do not themselves inherit from Persistable, but contain many objects that do (such as Exposure). It provides an interface for adding objects to the archive (put()), transforming them into catalogs that can be retrieved directly or written to a FITS file. The first catalog is an index that indicates which rows of the subsequent catalogs correspond to each object.

See getIndexCatalog() for a more detailed description of the index.

class OutputArchiveHandle
#include <OutputArchive.h>

An object passed to Persistable::write to allow it to persist itself.

OutputArchiveHandle provides an interface to add additional catalogs and save nested Persistables to the same archive.

class Persistable
#include <Persistable.h>

A base class for objects that can be persisted via afw::table::io Archive classes.

Inheriting from Persistable provides a public API for reading/writing individual objects to FITS that is fully defined in the base class, with derived classes only needing to implement persistence to catalogs. It is expected that objects that contain multiple persistables (such as Exposures) will create their own InputArchives and OutputArchives, and use these to avoid writing the same object twice (which would otherwise be a big concern for future objects like ExposureCatalog and CoaddPsf).

Generally speaking, an abstract base class that inherits from Persistable should also inherit from PersistableFacade<Base>. A concrete class that inherits (possibly indirectly) from Persistable should inherit from PersistableFacade<Derived> (though this just provides a slightly nicer interface to users), implement isPersistable(), getPersistenceName(), getPythonModule(), and write(), and define a subclass of PersistenceFactory. Inheritance from PersistableFacade should always precede inheritance from Persistable.

Persistable has no pure virtual member functions, and instead contains a default implementation that throws LogicError when the user attempts to save an object for which persistence has not actually been implemented.

Subclassed by lsst::afw::math::Function< Kernel::Pixel >, lsst::afw::cameraGeom::DetectorCollection, lsst::afw::cameraGeom::TransformMap, lsst::afw::detection::Footprint, lsst::afw::geom::Transform< FromEndpoint, ToEndpoint >, lsst::afw::math::BoundedField, lsst::afw::math::Function< ReturnT >, lsst::afw::math::Kernel, lsst::meas::modelfit::Mixture, lsst::afw::geom::Transform< afw::geom::Point2Endpoint, afw::geom::GenericEndpoint >

template<typename T>
class PersistableFacade
#include <Persistable.h>

A CRTP facade class for subclasses of Persistable.

Derived classes should generally inherit from PersistableFacade at all levels, but only inherit from Persistable via the base class of each hierarchy. For example, with Psfs:

class Psf: public PersistableFacade<Psf>, public Persistable { ... };
class DoubleGaussianPsf: public PersistableFacade<DoubleGaussianPsf>, public Psf { ... };

Inheriting from PersistableFacade is not required for any classes but the base of each hierarchy, but doing so can save users from having to do some dynamic_casts.

Note

PersistableFacade should usually be the first class in a list of base classes; if it appears after a base class that inherits from different specialization of PersistableFacade, those base class member functions will hide the desired ones.

class PersistableFactory
#include <Persistable.h>

A base class for factory classes used to reconstruct objects from records.

Classes that inherit from Persistable should also subclass PersistableFactory, and instantiate exactly one instance of the derived factory with static duration (usually the class and instance are both defined in an anonymous namespace in a source file).

Subclassed by lsst::meas::algorithms::KernelPsfFactory< T, K >

namespace python

Functions

template<typename T>
void declarePersistableFacade(pybind11::module &module, std::string const &suffix)

Wraps an instantiation of PersistableFacade.

Pybind11 shall assume that PersistableFacade is managed using std::shared_ptr, as this is required for compatibility with existing subclasses of PersistableFacade. This means that wrapping will only work if new classes also use std::shared_ptr as their holder type.

Template Parameters
Parameters
  • module: The pybind11 module that shall contain PersistableFacade<T>

  • suffix: A string to disambiguate this class from other PersistableFacades. The Python name of this class shall be PersistableFacade<suffix>.

template<typename Class, typename ...Args>
void addPersistableMethods(pybind11::class_<Class, Args...> &cls)

Add table::io::Persistable and PersistableFacade methods to the pybind11 wrapper for a class

Use this instead of declarePersistableFacade to avoid circular import issues in Python; it allows your class to be used without importing lsst.afw.table.

Use as follows:

  • When declaring the pybind11 class that wraps your Class do not list table::io::PersistableFacade<Class> and table::io::Persistable as subclasses.

  • Call this function to wrap the methods that make your object persistable.

namespace python

Typedefs

using PyCatalog = pybind11::class_<CatalogT<Record>, std::shared_ptr<CatalogT<Record>>>
using PyColumnView = pybind11::class_<ColumnViewT<Record>, std::shared_ptr<ColumnViewT<Record>>, BaseColumnView>
using PySortedCatalog = pybind11::class_<SortedCatalogT<Record>, std::shared_ptr<SortedCatalogT<Record>>, CatalogT<Record>>

Functions

template<typename T, typename Record>
ndarray::Array<typename Field<T>::Value const, 1, 1> _getArrayFromCatalog(CatalogT<Record> const &catalog, Key<T> const &key)

Extract a column from a potentially non-contiguous Catalog.

Parameters
  • catalog: Catalog

  • key: Key to column to extract

template<typename Record>
ndarray::Array<double const, 1, 1> _getArrayFromCatalog(CatalogT<Record> const &catalog, Key<lsst::geom::Angle> const &key)

Parameters
  • catalog: Catalog

  • key: Key to column to extract

template<typename T, typename Record>
void declareCatalogOverloads(PyCatalog<Record> &cls)

Declare field-type-specific overloaded catalog member functions for one field type

Template Parameters
Parameters
  • [in] cls: Catalog pybind11 class.

template<typename Record>
PyCatalog<Record> declareCatalog(utils::python::WrapperCollection &wrappers, std::string const &name, bool isBase = false)

Wrap an instantiation of lsst::afw::table::CatalogT<Record>.

In addition to calling this method you must call addCatalogMethods on the class object in Python.

Template Parameters
Parameters
  • [in] wrappers: Package manager class will be added to.

  • [in] name: Name prefix of the record type, e.g. “Base” or “Simple”.

  • [in] isBase: Whether this instantiation is only being used as a base class (used to set the class name).

template<typename Record>
PyColumnView<Record> declareColumnView(utils::python::WrapperCollection &wrappers, std::string const &name, bool isBase = false)

Declare member and static functions for a given instantiation of lsst::afw::table::ColumnViewT<RecordT>.

Template Parameters
Parameters
  • [in] wrappers: Package manager class will be added to.

  • [in] name: Name prefix of the record type, e.g. “Base” or “Simple”.

  • [in] isBase: Whether this instantiation is only being used as a base class (used to set the class name).

template<typename Record>
PySortedCatalog<Record> declareSortedCatalog(utils::python::WrapperCollection &wrappers, std::string const &name, bool isBase = false)

Wrap an instantiation of lsst::afw::table::SortedCatalogT<Record>.

In addition to calling this method (which also instantiates and wraps the CatalogT base class), you must call addCatalogMethods on the class object in Python.

Template Parameters
Parameters
  • [in] wrappers: Package manager class will be added to.

  • [in] name: Name prefix of the record type, e.g. “Base” or “Simple”.

  • [in] isBase: Whether this instantiation is only being used as a base class (used to set the class name).

namespace typehandling

Functions

template<typename V, typename K>
constexpr Key<K, V> makeKey(K const &id)

Factory function for Key, to enable type parameter inference.

Provides the same exception safety as the copy-constructor of

K.
Return

a key of the desired type

Parameters
  • id: the key ID to create.

Calling this function prevents you from having to explicitly name the key type:

auto key = makeKey<int>("foo");

template<typename K, typename V>
std::ostream &operator<<(std::ostream &os, Key<K, V> const &key)

Output operator for Key.

The output will use C++ template notation for the key; for example, a key “foo” pointing to an int may print as "foo<int>".

Provides basic exception safety if the output operator of

K is exception-safe.
Return

a reference to os

Parameters
  • os: the desired output stream

  • key: the key to print

Warning

the type name is compiler-specific and may be mangled or unintuitive; for example, some compilers say “i” instead of “int”

void swap(PolymorphicValue &lhs, PolymorphicValue &rhs)

Swap specialization for PolymorphicValue.

std::string declareGenericMapRestrictions(std::string const &className, std::string const &keyName)
LSST_EXCEPTION_TYPE (UnsupportedOperationException, pex::exceptions::RuntimeError, lsst::afw::typehandling::UnsupportedOperationException) class Storable std::ostream& lsst::afw::typehandling::operator<<(std::ostream & os, Storable const & storable)

Exception thrown by Storable operations for unimplemented operations.

As with all RuntimeError, callers should assume that this exception may be thrown at any time. Interface supporting iteration over heterogenous containers.

Storable may be subclassed by either C++ or Python classes. Many operations defined by Storable are optional, and may throw UnsupportedOperationException if they are not defined.

Note

Any C++ subclass X of Storable that supports Python subclasses must have a pybind11 wrapper that uses StorableHelper<X> (or a subclass) and lsst::utils::python::PySharedPtr. Output operator for Storable.

Return

a reference to os

Parameters
  • os: the desired output stream

  • storable: the object to print

Exceptions
  • UnsupportedOperationException: Thrown if storable does not have an implementation of Storable::toString.

template<typename K>
class GenericMap
#include <GenericMap.h>

Interface for a heterogeneous map.

Objects of type GenericMap cannot necessarily have keys added or removed, although mutable values can be modified as usual. In Python, a GenericMap behaves like a collections.abc.Mapping. See MutableGenericMap for a GenericMap that must allow insertions and deletions.

A

Key for the map is parameterized by both the key type K and a corresponding value type V. The map is indexed uniquely by a value of type K; no two entries in the map may have identical values of Key::getId().
Template Parameters
  • K: the key type of the map.

All operations are sensitive to the value type of the key: a contains call requesting an integer labeled “value”, for example, will report no such integer if instead there is a string labeled “value”. For Python compatibility, a GenericMap does not store type information internally, instead relying on RTTI for type checking.

All subclasses must guarantee, as a class invariant, that every value in the map is implicitly nothrow-convertible to the type indicated by its key. For example, MutableGenericMap ensures this by appropriately templating all operations that create new key-value pairs.

A GenericMap may contain primitive types, strings, Storable, and shared pointers to Storable as values. It does not support unique pointers to Storable because such pointers are read destructively. For safety reasons, it may not contain references, C-style pointers, or arrays to any type. Due to implementation restrictions, const types (except pointers to const Storable) are not currently supported.

Subclassed by lsst::afw::typehandling::MutableGenericMap< K >

template<typename K, typename V>
class Key
#include <Key.h>

Key for type-safe lookup in a GenericMap.

Key objects are equality-comparable, hashable, sortable, or printable if and only if K is comparable, hashable, sortable, or printable, respectively. Key can be used in compile-time expressions if and only if K can (in particular, Key<std::string, V> cannot).

Template Parameters
  • K: the logical type of the key (e.g., a string)

  • V: the type of the value mapped to this key

template<typename K>
class MutableGenericMap : public lsst::afw::typehandling::GenericMap<K>
#include <GenericMap.h>

Interface for a GenericMap that allows element addition and removal.

In Python, a MutableGenericMap behaves like a collections.abc.MutableMapping.

Note

Unlike standard library maps, this class does not support operator[] or insert_or_assign. This is because these operations would have surprising behavior when dealing with keys of different types but the same Key::getId().

Subclassed by lsst::afw::typehandling::SimpleGenericMap< K >

class PolymorphicValue
#include <PolymorphicValue.h>

Container that passes Storable objects by value while preserving type.

This class is implicitly convertible to and from a reference to Storable, but behaves like a value: changing the internal Storable changes the object’s state, and copying the object creates a new Storable.

Note

While a PolymorphicValue is always initialized with a Storable, it may become empty if it is the source of a move-construction or move-assignment. Conversion of an empty value to Storable& throws.

template<typename K>
class SimpleGenericMap : public lsst::afw::typehandling::MutableGenericMap<K>
#include <SimpleGenericMap.h>

A GenericMap that allows insertion and deletion of arbitrary values.

In Python, a SimpleGenericMap behaves like a dict. In particular, it will iterate over keys in the order they were added.

Template Parameters
  • K: the key type of the map. Must be hashable.

template<class Base = Storable>
class StorableHelper : public Base
#include <python.h>

“Trampoline” for Storable to let it be used as a base class in Python.

Subclasses of Storable that are wrapped in pybind11 should have a similar helper that subclasses StorableHelper<subclass>. This helper can be skipped if the subclass neither adds any virtual methods nor implements any abstract methods.

See

pybind11 documentation

Template Parameters
  • Base: the exact (most specific) class being wrapped

namespace detail

Variables

template<typename, typename = void>
constexpr bool IS_SMART_PTR = false
namespace test

Functions

BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestConstAt, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestAt, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestEquals, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestConstVisitor, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestModifyingVoidVisitor, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestModifyingReturningVisitor, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestMutableEquals, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestSize, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestMutableSize, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestWeakContains, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestContains, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestKeys, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestKeyOrder, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestClearIdempotent, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestClear, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestInsertInt, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestWeakInsertInt, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestInsertString, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestWeakInsertString, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestInsertStorable, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestInterleavedInserts, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestErase, GenericMapFactory)
BOOST_TEST_CASE_TEMPLATE_FUNCTION(TestInsertEraseInsert, GenericMapFactory)
template<class GenericMapFactory>
void addGenericMapTestCases(boost::unit_test::test_suite *const suite)

Create generic test cases for a specific GenericMap implementation.

Template Parameters
  • GenericMapFactory: a subclass of GenericFactory that creates the desired implementation. Must be default-constructible.

Parameters
  • suite: the test suite to add the tests to.

template<class GenericMapFactory>
void addMutableGenericMapTestCases(boost::unit_test::test_suite *const suite)

Create generic test cases for a specific MutableGenericMap implementation.

The tests will include all those added by addGenericMapTestCases.

Template Parameters
  • GenericMapFactory: a subclass of GenericFactory that creates the desired implementation. Must be default-constructible.

Parameters
  • suite: the test suite to add the tests to.

template<class GenericMapFactory>
void addGenericMapTestCases()

Create generic test cases for a specific GenericMap implementation.

The tests will be added to the master test suite.

Template Parameters
  • GenericMapFactory: a subclass of GenericFactory that creates the desired implementation. Must be default-constructible.

template<class GenericMapFactory>
void addMutableGenericMapTestCases()

Create generic test cases for a specific MutableGenericMap implementation.

The tests will be added to the master test suite. They will include all tests added by addGenericMapTestCases.

Template Parameters
  • GenericMapFactory: a subclass of GenericFactory that creates the desired implementation. Must be default-constructible.

class GenericFactory
#include <test.h>

Abstract factory that creates GenericMap and MutableGenericMap instances as needed.

namespace base

Functions

std::string libraryExtension()

Return filename extension for libraries

Typically “.so” for Linux and “.dylib” for Mac.

std::string getLibraryFilename(std::string const &name)

Get filename for library

We’ll add the typical filename extension for the platform unless the user specifies a “.so” or “.dylib” extension.

bool canLoadLibrary(std::string const &libName)

Parameters
  • libName: Library name

Return whether we can load a library

The proper filename extension will be added to the library name unless one is specified.

template<typename T>
T *loadSymbol(std::string const &libName, std::string const &symName)

Parameters
  • libName: Library name (NOT including “.so” or “.dylib”)

  • symName: Symbol name

Load a symbol from a dynamic library

The proper filename extension will be added to the library name unless one is specified.

No mangling is performed on the symbol name.

bool haveThreads()

Are threaded packages available?

void setNumThreads(unsigned int numThreads)

Set number of threads to use

Exceptions

unsigned int getNumThreads()

Get maximum number of threads we might use

Returns the maximum value of the number of threads being used by the threading libraries that are available.

bool disableImplicitThreading()

Disable threading that has not been set explicitly

Some threaded packages implicitly use multiple threads if the user doesn’t explicitly state the number of desired threads. However, this can interfere with operations that are parallelised at a higher level. This function will disable threading unless the user has explicitly specified the number of desired threads through environment variables.

This behavior may be disabled by setting the environment variable specified by allowEnvvar.

This is principally intended for Linux machines (we explicitly load .so dynamic libraries); MacOS has its own way of doing threading (Grand Central Dispatch) that throttles threads to avoid overwhelming the machine.

@ return whether we disabled threading

std::map<std::string, std::string> getRuntimeVersions()

Return version strings for dependencies

It is not clever, and only returns versions of packages declared in an internal list.

Returns a map of product:version.

std::string getCfitsioVersion()
std::string getFftwVersion()
std::string getWcslibVersion()
std::string getGslVersion()

Variables

bool const haveOpenBlas

Is OpenBLAS available?

bool const haveMkl

Is MKL available?

std::string const allowEnvvar = "LSST_ALLOW_IMPLICIT_THREADS"

Environment variable to allow implicit threading

Used by disableImplicitThreading.

class LibraryException : public runtime_error
#include <library.h>

Unable to load library.

class ModuleImporter
#include <ModuleImporter.h>

Base class that defines an interface for importing Python modules.

The default implementation (defined in the source file) simply returns false, indicating that it can’t import the given module. The functional implementation is in the ioLib Swig module, which is installed when that module is imported. That machinery keeps us from calling Python C-API functions from standalone C++ binaries that aren’t linked with Python.

class NoThreadsException : public runtime_error
#include <threads.h>

No threading library is available.

namespace coadd
namespace utils

Functions

template<typename CoaddPixelT, typename WeightPixelT>
lsst::geom::Box2I addToCoadd(lsst::afw::image::Image<CoaddPixelT> &coadd, lsst::afw::image::Image<WeightPixelT> &weightMap, lsst::afw::image::Image<CoaddPixelT> const &image, WeightPixelT weight)

add good pixels from an image to a coadd and associated weight map

Parameters
  • coadd: coadd to be modified

  • weightMap: weight map to be modified; this is the sum of weights of all images contributing each pixel of the coadd

  • image: image to add to coadd

  • weight: relative weight of this image

The images are assumed to be registered to the same wcs and parent origin, thus: coadd[i+coadd.x0, j+coadd.y0] += image[i+image.x0, j+image.y0] weightMap[i+weightMap.x0, j+weightMap.y0] += weight for all good image pixels that overlap a coadd pixel. Good pixels are those that are not NaN (thus they do include +/- inf).

Return

overlapBBox: overlapping bounding box, relative to parent image (hence xy0 is taken into account)

Exceptions
  • pexExcept::InvalidParameterError: if coadd and weightMap dimensions or xy0 do not match.

template<typename CoaddPixelT, typename WeightPixelT>
lsst::geom::Box2I addToCoadd(lsst::afw::image::MaskedImage<CoaddPixelT, lsst::afw::image::MaskPixel, lsst::afw::image::VariancePixel> &coadd, lsst::afw::image::Image<WeightPixelT> &weightMap, lsst::afw::image::MaskedImage<CoaddPixelT, lsst::afw::image::MaskPixel, lsst::afw::image::VariancePixel> const &maskedImage, lsst::afw::image::MaskPixel const badPixelMask, WeightPixelT weight)

add good pixels from a masked image to a coadd image and associated weight map

Parameters
  • coadd: coadd to be modified

  • weightMap: weight map to be modified; this is the sum of weights of all images contributing each pixel of the coadd

  • maskedImage: masked image to add to coadd

  • badPixelMask: skip input pixel if input mask & badPixelMask !=0

  • weight: relative weight of this image

The images are assumed to be registered to the same wcs and parent origin, thus: coadd[i+coadd.x0, j+coadd.y0] += image[i+image.x0, j+image.y0] weightMap[i+weightMap.x0, j+weightMap.y0] += weight for all good image pixels that overlap a coadd pixel. Good pixels are those for which mask & badPixelMask == 0.

Return

overlapBBox: overlapping bounding box, relative to parent image (hence xy0 is taken into account)

Exceptions
  • pexExcept::InvalidParameterError: if coadd and weightMap dimensions or xy0 do not match.

template<typename ImagePixelT>
int copyGoodPixels(lsst::afw::image::Image<ImagePixelT> &destImage, lsst::afw::image::Image<ImagePixelT> const &srcImage)

copy good pixels from one image to another

Parameters
  • destImage: image to be modified

  • srcImage: image to copy

Good pixels are those that are not NaN (thus they do include +/- inf).

Only the overlapping pixels (relative to the parent) are copied; thus the images do not have to be the same size.

Return

number of pixels copied

template<typename ImagePixelT>
int copyGoodPixels(lsst::afw::image::MaskedImage<ImagePixelT, lsst::afw::image::MaskPixel, lsst::afw::image::VariancePixel> &destImage, lsst::afw::image::MaskedImage<ImagePixelT, lsst::afw::image::MaskPixel, lsst::afw::image::VariancePixel> const &srcImage, lsst::afw::image::MaskPixel const badPixelMask)

copy good pixels from one masked image to another

Parameters
  • destImage: image to be modified

  • srcImage: image to copy

  • badPixelMask: skip input pixel if src mask & badPixelMask != 0

Good pixels are those for which mask & badPixelMask == 0.

Only the overlapping pixels (relative to the parent) are copied; thus the images do not have to be the same size.

Return

number of pixels copied

template<typename WeightPixelT>
void setCoaddEdgeBits(lsst::afw::image::Mask<lsst::afw::image::MaskPixel> &coaddMask, lsst::afw::image::Image<WeightPixelT> const &weightMap)

set edge bits of coadd mask based on weight map

Parameters
  • coaddMask: mask of coadd

  • weightMap: weight map

Set pixels in the image to the edge pixel when the corresponding pixel in the weight map is zero. The edge pixel is image=nan, variance=inf, mask=NO_DATA for masked images and image=nan for plain images.

Exceptions
  • pexExcept::InvalidParameterError: if the dimensions of coaddMask and weightMap do not match.

namespace ip
namespace diffim

Functions

lsst::afw::math::KernelList makeDeltaFunctionBasisList(int width, int height)

Build a set of Delta Function basis kernels.

Note

Total number of basis functions is width*height

Parameters
  • width: Width of basis set (cols)

  • height: Height of basis set (rows)

Eigen::MatrixXd makeRegularizationMatrix(lsst::daf::base::PropertySet const &ps)

Build a regularization matrix for Delta function kernels.

Note

Calls either makeForwardDifferenceMatrix or makeCentralDifferenceMatrix based on the PropertySet config.

Parameters
  • ps: PropertySet dictating which type of matrix to make

Eigen::MatrixXd makeForwardDifferenceMatrix(int width, int height, std::vector<int> const &orders, float borderPenalty, bool fitForBackground)

Build a forward difference regularization matrix for Delta function kernels.

Parameters
  • width: Width of basis set you want to regularize

  • height: Height of basis set you want to regularize

  • orders: Which derivatives to penalize (1,2,3)

  • borderPenalty: Amount of penalty (if any) to apply to border pixels; > 0

  • fitForBackground: Fit for differential background?

Eigen::MatrixXd makeCentralDifferenceMatrix(int width, int height, int stencil, float borderPenalty, bool fitForBackground)

Build a central difference Laplacian regularization matrix for Delta function kernels.

Parameters
  • width: Width of basis set you want to regularize

  • height: Height of basis set you want to regularize

  • stencil: Which type of Laplacian approximation to use

  • borderPenalty: Amount of penalty (if any) to apply to border pixels; > 0

  • fitForBackground: Fit for differential background?

lsst::afw::math::KernelList renormalizeKernelList(lsst::afw::math::KernelList const &kernelListIn)

Renormalize a list of basis kernels.

Note

Renormalization means make Ksum_0 = 1.0, Ksum_i = 0.0, K_i.dot.K_i = 1.0

Note

Output list of shared pointers to FixedKernels

Note

Images are checked for their current kernel sum. If it is larger than std::numeric_limits<double>::epsilon(), the kernel is first divided by the kernel sum, giving it a kSum of 1.0, and then the first (normalized) component is subtracted from it, giving it a kSum of 0.0.

Parameters
  • kernelListIn: input list of basis kernels

lsst::afw::math::KernelList makeAlardLuptonBasisList(int halfWidth, int nGauss, std::vector<double> const &sigGauss, std::vector<int> const &degGauss)

Build a set of Alard/Lupton basis kernels.

Note

Should consider implementing as SeparableKernels for additional speed, but this will make the normalization a bit more complicated

Parameters
  • halfWidth: size is 2*N + 1

  • nGauss: number of gaussians

  • sigGauss: Widths of the Gaussian Kernels

  • degGauss: Local spatial variation of bases

template<typename PixelT, typename BackgroundT>
lsst::afw::image::MaskedImage<PixelT> convolveAndSubtract(lsst::afw::image::MaskedImage<PixelT> const &templateImage, lsst::afw::image::MaskedImage<PixelT> const &scienceMaskedImage, lsst::afw::math::Kernel const &convolutionKernel, BackgroundT background, bool invert = true)

Execute fundamental task of convolving template and subtracting it from science image.

Note

This version accepts a MaskedImage for the template

Parameters
  • templateImage: MaskedImage to apply convolutionKernel to

  • scienceMaskedImage: MaskedImage from which convolved templateImage is subtracted

  • convolutionKernel: Kernel to apply to templateImage

  • background: Background scalar or function to subtract after convolution

  • invert: Invert the output difference image

template<typename PixelT, typename BackgroundT>
lsst::afw::image::MaskedImage<PixelT> convolveAndSubtract(lsst::afw::image::Image<PixelT> const &templateImage, lsst::afw::image::MaskedImage<PixelT> const &scienceMaskedImage, lsst::afw::math::Kernel const &convolutionKernel, BackgroundT background, bool invert = true)

Execute fundamental task of convolving template and subtracting it from science image.

Note

This version accepts an Image for the template, and is thus faster during convolution

Parameters
  • templateImage: Image to apply convolutionKernel to

  • scienceMaskedImage: MaskedImage from which convolved templateImage is subtracted

  • convolutionKernel: Kernel to apply to templateImage

  • background: Background scalar or function to subtract after convolution

  • invert: Invert the output difference image

template<typename PixelT>
Eigen::MatrixXd imageToEigenMatrix(lsst::afw::image::Image<PixelT> const &img)

Turns a 2-d Image into a 2-d Eigen Matrix.

Parameters
  • img: Image whose pixel values are read into an Eigen::MatrixXd

Eigen::MatrixXi maskToEigenMatrix(lsst::afw::image::Mask<lsst::afw::image::MaskPixel> const &mask)
template<typename PixelT>
std::shared_ptr<KernelCandidate<PixelT>> makeKernelCandidate(float const xCenter, float const yCenter, std::shared_ptr<afw::image::MaskedImage<PixelT>> const &templateMaskedImage, std::shared_ptr<afw::image::MaskedImage<PixelT>> const &scienceMaskedImage, daf::base::PropertySet const &ps)

Return a KernelCandidate pointer of the right sort.

Parameters
  • xCenter: X-center of candidate

  • yCenter: Y-center of candidate

  • templateMaskedImage: Template subimage

  • scienceMaskedImage: Science image subimage

  • ps: PropertySet for creation of rating

template<typename PixelT>
std::shared_ptr<KernelCandidate<PixelT>> makeKernelCandidate(std::shared_ptr<afw::table::SourceRecord> const &source, std::shared_ptr<afw::image::MaskedImage<PixelT>> const &templateMaskedImage, std::shared_ptr<afw::image::MaskedImage<PixelT>> const &scienceMaskedImage, daf::base::PropertySet const &ps)

Return a KernelCandidate pointer of the right sort.

Parameters

class DipoleCentroidAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <DipoleAlgorithms.h>

Intermediate base class for algorithms that compute a centroid.

Subclassed by lsst::ip::diffim::NaiveDipoleCentroid

class DipoleFluxAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <DipoleAlgorithms.h>

Intermediate base class for algorithms that compute a flux.

Subclassed by lsst::ip::diffim::NaiveDipoleFlux, lsst::ip::diffim::PsfDipoleFlux

class DipoleFluxControl

Subclassed by lsst::ip::diffim::PsfDipoleFluxControl

template<typename MaskT>
class FindSetBits
#include <FindSetBits.h>

Class to accumulate Mask bits.

Note

Search through a Mask for any set bits.

template<typename PixelT>
class ImageStatistics
#include <ImageStatistics.h>

Class to calculate difference image statistics.

Note

Find mean and unbiased variance of pixel residuals in units of sqrt(variance)

template<typename _PixelT>
class KernelCandidate : public lsst::afw::math::SpatialCellImageCandidate
#include <KernelCandidate.h>

Class stored in SpatialCells for spatial Kernel fitting.

Note

KernelCandidate is a single Kernel derived around a source. We’ll assign them to sets of SpatialCells; these sets will then be used to fit a spatial model to the Kernel.

template<typename PixelT>
class KernelCandidateDetection
#include <KernelCandidateDetection.h>

Search through images for Footprints with no masked pixels.

Note

Runs detection on the template; searches through both images for masked pixels

Parameters
  • templateMaskedImage: MaskedImage that will be convolved with kernel

  • scienceMaskedImage: MaskedImage to subtract convolved template from

  • ps: PropertySet for operations; in particular object detection

class KernelSolution

Subclassed by lsst::ip::diffim::SpatialKernelSolution, lsst::ip::diffim::StaticKernelSolution< InputT >

class NaiveDipoleCentroid : public lsst::ip::diffim::DipoleCentroidAlgorithm
#include <DipoleAlgorithms.h>

Intermediate base class for algorithms that compute a centroid.

class PsfDipoleFlux : public lsst::ip::diffim::DipoleFluxAlgorithm
#include <DipoleAlgorithms.h>

Implementation of Psf dipole flux

class PsfDipoleFluxControl : public lsst::ip::diffim::DipoleFluxControl
#include <DipoleAlgorithms.h>

C++ control object for PSF dipole fluxes.

template<typename InputT>
class StaticKernelSolution : public lsst::ip::diffim::KernelSolution

Subclassed by lsst::ip::diffim::MaskedKernelSolution< InputT >, lsst::ip::diffim::RegularizedKernelSolution< InputT >

namespace detail

Functions

template<typename PixelT>
std::shared_ptr<AssessSpatialKernelVisitor<PixelT>> makeAssessSpatialKernelVisitor(std::shared_ptr<lsst::afw::math::LinearCombinationKernel> spatialKernel, lsst::afw::math::Kernel::SpatialFunctionPtr spatialBackground, lsst::daf::base::PropertySet const &ps)
template<typename PixelT>
std::shared_ptr<BuildSingleKernelVisitor<PixelT>> makeBuildSingleKernelVisitor(lsst::afw::math::KernelList const &basisList, lsst::daf::base::PropertySet const &ps)
template<typename PixelT>
std::shared_ptr<BuildSingleKernelVisitor<PixelT>> makeBuildSingleKernelVisitor(lsst::afw::math::KernelList const &basisList, lsst::daf::base::PropertySet const &ps, Eigen::MatrixXd const &hMat)
template<typename PixelT>
std::shared_ptr<BuildSpatialKernelVisitor<PixelT>> makeBuildSpatialKernelVisitor(lsst::afw::math::KernelList const &basisList, lsst::geom::Box2I const &regionBBox, lsst::daf::base::PropertySet const &ps)
template<typename PixelT>
std::shared_ptr<KernelPcaVisitor<PixelT>> makeKernelPcaVisitor(std::shared_ptr<KernelPca<typename KernelPcaVisitor<PixelT>::ImageT>> imagePca)
template<typename PixelT>
std::shared_ptr<KernelSumVisitor<PixelT>> makeKernelSumVisitor(lsst::daf::base::PropertySet const &ps)
namespace isr

Functions

template<typename PixelT>
int applyLookupTable(afw::image::Image<PixelT> &image, ndarray::Array<PixelT, 1, 1> const &table, PixelT indOffset)

Add the values in a lookup table to an image, e.g. for non-linearity correction

The algorithm is as follows: numOutOfRange = 0 For each i,j of the image: lookupInd = int(indOffset + image[i,j]) if lookupInd not in range [0, table.size() - 1]: set lookupInd to nearest edge and increment numOutOfRange image[i,j] += table[lookupInd] return numOutOfRange

Return

the number of pixels whose values were out of range

Parameters
  • [inout] image: image to which to add the values; modified in place

  • [in] table: lookup table

  • [in] indOffset: scalar added to image value before truncating to lookup column

template<typename PixelT>
size_t maskNans(afw::image::MaskedImage<PixelT> const &mi, afw::image::MaskPixel maskVal, afw::image::MaskPixel allow = 0)

Parameters
  • mi: Input image

  • maskVal: Bit mask value to give a NaN

  • allow: Retain NANs with this bit mask (0 to mask all NANs)

Mask NANs in an image

NANs in the image or variance that are not already masked by the ‘allow’ value are masked with the ‘maskVal’.

Return

Number of pixels masked

template<typename ImagePixelT, typename FunctionT>
void fitOverscanImage(std::shared_ptr<lsst::afw::math::Function1<FunctionT>> &overscanFunction, lsst::afw::image::MaskedImage<ImagePixelT> const &overscan, double ssize = 1., int sigma = 1)
namespace jointcal

Typedefs

using RefFluxMapType = std::map<std::string, std::vector<double>>
typedef void() lsst::jointcal::AstrometryTransformFun(const double, const double, double &, double &, const void *)

signature of the user-provided routine that actually does the coordinate transform for UserTransform.

typedef StarList<BaseStar> BaseStarList
typedef BaseStarList::const_iterator BaseStarCIterator
typedef BaseStarList::iterator BaseStarIterator
typedef std::list<std::shared_ptr<CcdImage>> CcdImageList
typedef int VisitIdType
typedef int CcdIdType
typedef FittedStarList::const_iterator FittedStarCIterator
typedef FittedStarList::iterator FittedStarIterator
typedef MeasuredStarList::const_iterator MeasuredStarCIterator
typedef MeasuredStarList::iterator MeasuredStarIterator
typedef RefStarList::const_iterator RefStarCIterator
typedef RefStarList::iterator RefStarIterator
typedef std::list<StarMatch>::iterator StarMatchIterator
typedef std::list<StarMatch>::const_iterator StarMatchCIterator
typedef Eigen::Triplet<double> Trip

Enums

enum MinimizeResult

Return value of minimize()

Values:

Converged
Chi2Increased
Failed
NonFinite

Functions

std::ostream &operator<<(std::ostream &stream, AstrometryTransform const &transform)

Delegates to transform.dump()

std::unique_ptr<AstrometryTransform> compose(AstrometryTransform const &left, AstrometryTransform const &right)

Returns a pointer to a composition of transforms, representing left(right()).

Deletion of returned value to be done by caller.

If left->composeAndReduce(right) returns NULL, build a AstrometryTransformComposition and return it. This routine implements “run-time” compositions. When there is a possible “reduction” (e.g. compositions of polynomials), compose detects it and returns a genuine AstrometryTransform.

Return

The composed transform.

std::unique_ptr<AstrometryTransform> compose(AstrometryTransform const &left, AstrometryTransformIdentity const &right)
bool isIntegerShift(const AstrometryTransform *transform)

Shorthand test to tell if a transform is a simple integer shift.

std::shared_ptr<AstrometryTransformPolynomial> inversePolyTransform(AstrometryTransform const &forward, Frame const &domain, double const precision, std::size_t maxOrder = 9, std::size_t nSteps = 50)

Approximate the inverse by a polynomial, to some precision.

Return

A polynomial that best approximates forward.

Parameters
  • forward: Transform to be inverted.

  • [in] domain: The domain of forward.

  • [in] precision: Require that \(chi2 / (nsteps^2) < precision^2\).

  • [in] maxOrder: The maximum order allowed of the inverse polynomial.

  • [in] nSteps: The number of sample points per axis (nSteps^2 total points).

AstrometryTransformLinear normalizeCoordinatesTransform(const Frame &frame)
std::unique_ptr<AstrometryTransform> astrometryTransformRead(const std::string &fileName)

The virtual constructor from a file.

std::unique_ptr<AstrometryTransform> astrometryTransformRead(std::istream &s)

The virtual constructor from a file.

std::ostream &operator<<(std::ostream &out, CcdImageKey const &key)
BaseStarList &Fitted2Base(FittedStarList &This)
BaseStarList *Fitted2Base(FittedStarList *This)
const BaseStarList &Fitted2Base(const FittedStarList &This)
const BaseStarList *Fitted2Base(const FittedStarList *This)
std::unique_ptr<StarMatchList> matchSearchRotShift(BaseStarList &list1, BaseStarList &list2, const MatchConditions &conditions)

searches a geometrical transformation that goes from list1 to list2.

The found transformation is a field of the returned object, as well as the star pairs (the matches) that were constructed. (see StarMatchList class definition for more details). The various cuts are contained in conditions (see listmatch.h) for its contents. This routine searches a transformation that involves a shift and a rotation.

std::unique_ptr<StarMatchList> matchSearchRotShiftFlip(BaseStarList &list1, BaseStarList &list2, const MatchConditions &conditions)

same as above but searches also a flipped solution.

std::unique_ptr<StarMatchList> listMatchCollect(const BaseStarList &list1, const BaseStarList &list2, const AstrometryTransform *guess, const double maxDist)

assembles star matches.

It picks stars in list1, transforms them through guess, and collects closest star in list2, and builds a match if closer than maxDist).

std::unique_ptr<StarMatchList> listMatchCollect(const BaseStarList &list1, const BaseStarList &list2, const double maxDist)

same as before except that the transform is the identity

std::unique_ptr<AstrometryTransformLinear> listMatchupShift(const BaseStarList &list1, const BaseStarList &list2, const AstrometryTransform &transform, double maxShift, double binSize = 0)

searches for a 2 dimensional shift using a very crude histogram method.

std::unique_ptr<AstrometryTransform> listMatchCombinatorial(const BaseStarList &list1, const BaseStarList &list2, const MatchConditions &conditions = MatchConditions())
std::unique_ptr<AstrometryTransform> listMatchRefine(const BaseStarList &list1, const BaseStarList &list2, std::unique_ptr<AstrometryTransform> transform, const int maxOrder = 3)
BaseStarList &Measured2Base(MeasuredStarList &This)
BaseStarList *Measured2Base(MeasuredStarList *This)
const BaseStarList &Measured2Base(const MeasuredStarList &This)
const BaseStarList *Measured2Base(const MeasuredStarList *This)
std::ostream &operator<<(std::ostream &stream, const Point &point)

BaseStarList &Ref2Base(RefStarList &This)
BaseStarList *Ref2Base(RefStarList *This)
const BaseStarList &Ref2Base(const RefStarList &This)
const BaseStarList *Ref2Base(const RefStarList *This)
template<class Star>
std::ostream &operator<<(std::ostream &stream, const StarList<Star> &list)

enables

std::cout << my_list;

bool compareStar1(const StarMatch &one, const StarMatch &two)
bool sameStar1(const StarMatch &one, const StarMatch &two)
bool compareStar2(const StarMatch &one, const StarMatch &two)
bool sameStar2(const StarMatch &one, const StarMatch &two)
std::ostream &operator<<(std::ostream &stream, const StarMatch &match)
std::ostream &operator<<(std::ostream &stream, const StarMatchList &starMatchList)

A std::list of star matches,.

To be used as the argument to AstrometryTransform::fit routines. There is as well a StarMatch::fit routine which fits a polynomial by default, although the transform may be user-provided. The StarMatchList::refineTransform is a convenient tool to reject outliers. Given two catalogs, one can assemble a StarMatchList using utilities such as listMatchCollect. StarMatchList’s have write capabilities. NStarMatchList is a generalization of this 2-match to n-matches.

double computeDist2(const StarMatchList &S, const AstrometryTransform &transform)

sum of distance squared

double computeChi2(const StarMatchList &L, const AstrometryTransform &transform)

the actual chi2

class Associations
#include <Associations.h>

The class that implements the relations between MeasuredStar and FittedStar.

class AstrometryFit : public lsst::jointcal::FitterBase
#include <AstrometryFit.h>

Class that handles the astrometric least squares problem.

This is the class that actually computes the quantities required to carry out a LS astrometric fit wrt distortion mappings and coordinates of common objects. Namely it computes the Jacobian and gradient of the chi2 (w.r.t. parameters), and the Chi2 itself. It interfaces with the actual modelling of distortions via a mimimum virtual interface AstrometryModel, and the actual mappings via an other virtual interface : Mapping.

In short AstrometryFit aims at computing derivatives of least quares. The terms of the chi2 are of two kinds:

kind 1 -> (T(X_M) - p(F))^T W (T(X_M) - p(F))

with X_M is a measured (2d) position in CCD coordinates, F refers to the position of the object in some space, defined in practise by p. There is one such term per measurement. The default setup would be that p is the projection from sky to some tangent plane and hence T maps the CCD coordinates onto this TP. p is obtained via the DistorsionModel and can be different for all CcdImage’s. Depending on what is beeing fitted, one could imagine cases where the projector p is the same for all CcdImages.

Kind 2 -> (p’(F)-p’(R))^T W_R (p’(F)-p’(R)) R refers to some externally-provided reference object position, and p’ to some projector from sky to some plane. The reference objects define the overall coordinate frame, which is required when all T and all F are fitted simultaneously. There is one such term per external reference object. There can be more F (fitted) objects than R (reference) objects.

In the same framework, one can fit relative transforms between images by setting p = Identity for all input CcdImages and not fitting T for one of the CcdImage’s. One does not need reference object and would then naturally not have any Kind 2 terms.

class AstrometryMapping
#include <AstrometryMapping.h>

virtual class needed in the abstraction of the distortion model

Subclassed by lsst::jointcal::ChipVisitAstrometryMapping, lsst::jointcal::SimpleAstrometryMapping

class AstrometryModel
#include <AstrometryModel.h>

Interface between AstrometryFit and the combinations of Mappings from pixels to some tangent plane (aka distortions).

Parameters
  • log: Logger to send messages to, to keep names consistent when logging.

Subclassed by lsst::jointcal::ConstrainedAstrometryModel, lsst::jointcal::SimpleAstrometryModel

class AstrometryTransform
#include <AstrometryTransform.h>

a virtual (interface) class for geometric transformations.

We implement here One AstrometryTransform interface class, and actual derived classes. Composition in the usual (mathematical) sense is provided using compose(), and some classes (e.g. AstrometryTransformLinear

) handle a * operator. Generic inversion by iteration exists, but it is at least 10 times slower than the corresponding “direct

transformation”. If a transform has an analytical inverse, then providing inverseTransform is obviously a very good idea. Before resorting to inverseTransform, consider using

StarMatchList::inverseTransform(). AstrometryTransformLinear::inverted() and TanPixelToRaDec::inverted() exist. The classes also provide derivation and linear approximation.

Subclassed by lsst::jointcal::AstrometryTransformIdentity, lsst::jointcal::AstrometryTransformPolynomial, lsst::jointcal::AstrometryTransformSkyWcs, lsst::jointcal::BaseTanWcs, lsst::jointcal::TanRaDecToPixel, lsst::jointcal::UserTransform

class AstrometryTransformIdentity : public lsst::jointcal::AstrometryTransform
#include <AstrometryTransform.h>

A do-nothing transformation. It anyway has dummy routines to mimick a AstrometryTransform.

class AstrometryTransformLinear : public lsst::jointcal::AstrometryTransformPolynomial
#include <AstrometryTransform.h>

implements the linear transformations (6 real coefficients).

Subclassed by lsst::jointcal::AstrometryTransformLinearRot, lsst::jointcal::AstrometryTransformLinearScale, lsst::jointcal::AstrometryTransformLinearShift

class AstrometryTransformLinearRot : public lsst::jointcal::AstrometryTransformLinear
#include <AstrometryTransform.h>

just here to provide a specialized constructor, and fit.

class AstrometryTransformLinearScale : public lsst::jointcal::AstrometryTransformLinear
#include <AstrometryTransform.h>

just here to provide specialized constructors. AstrometryTransformLinear fit routine.

class AstrometryTransformLinearShift : public lsst::jointcal::AstrometryTransformLinear
#include <AstrometryTransform.h>

just here to provide a specialized constructor, and fit.

class AstrometryTransformPolynomial : public lsst::jointcal::AstrometryTransform
#include <AstrometryTransform.h>

Polynomial transformation class.

Subclassed by lsst::jointcal::AstrometryTransformLinear

class AstrometryTransformSkyWcs : public lsst::jointcal::AstrometryTransform
#include <AstrometryTransform.h>

A AstrometryTransform that holds a SkyWcs

This is intended to hold the initial estimate for the WCS. It need not be TAN-SIP, nor exactly representable as a FITS WCS.

AstrometryTransformSkyWcs does not inherit from BaseTanWcs for two reasons:

  • There is no need.

  • It is not clear how to implement all of the BaseTanWcs interface, especially corrections.

class BaseStar : public lsst::jointcal::FatPoint
#include <BaseStar.h>

The base class for handling stars. Used by all matching routines.

Subclassed by lsst::jointcal::FittedStar, lsst::jointcal::MeasuredStar, lsst::jointcal::RefStar

class BaseTanWcs : public lsst::jointcal::AstrometryTransform

Subclassed by lsst::jointcal::TanPixelToRaDec, lsst::jointcal::TanSipPixelToRaDec

class CcdImage
#include <CcdImage.h>

Handler of an actual image from a single CCD. NOTE: could possibly be replaced with a subclass of afw.image.Exposure?

struct CcdImageKey
#include <CcdImage.h>

For hashing a ccdImage: the pair of (visit, ccd) IDs should be unique to each ccdImage.

class Chi2Accumulator
#include <Chi2.h>

Base class for Chi2Statistic and Chi2List, to allow addEntry inside Fitter for either class.

Essentially a mixin.

Subclassed by lsst::jointcal::Chi2List, lsst::jointcal::Chi2Statistic

class Chi2List : public lsst::jointcal::Chi2Accumulator, public std::vector<Chi2Star>
#include <Chi2.h>

Structure to accumulate the chi2 contributions per each star (to help find outliers).

class Chi2Statistic : public lsst::jointcal::Chi2Accumulator
#include <Chi2.h>

Simple structure to accumulate chi2 and ndof.

class ChipVisitAstrometryMapping : public lsst::jointcal::AstrometryMapping
#include <ChipVisitAstrometryMapping.h>

The mapping with two transforms in a row.

class ChipVisitPhotometryMapping : public lsst::jointcal::PhotometryMappingBase
#include <PhotometryMapping.h>

A two-level photometric transform: one for the ccd and one for the visit.

Subclassed by lsst::jointcal::ChipVisitFluxMapping, lsst::jointcal::ChipVisitMagnitudeMapping

class ConstrainedAstrometryModel : public lsst::jointcal::AstrometryModel
#include <ConstrainedAstrometryModel.h>

A multi-component model, fitting mappings for sensors and visits simultaneously.

This is the model used to fit mappings as the combination of a transformation depending on the chip number (instrument model) and a transformation per visit (anamorphism). The two-transformation Mapping required for this model is ChipVisitAstrometryMapping. This modeling of distortions is meant for a set of images from a single mosaic imager.

Parameters
  • ccdImageList: The exposures that will be fit.

  • projectionHandler: The projection from “Sky” (where the “true” coordinates live) to “Tangent Plane” (where the fitting occurs).

  • chipOrder: The polynomial order of the pixel->focal plane mapping for each sensor.

  • visitOrder: The polynomial order of the focal plane->tangent plane mapping for each visit.

class ConstrainedPhotometryModel : public lsst::jointcal::PhotometryModel
#include <ConstrainedPhotometryModel.h>

Photometry model with constraints, \(M(x,y) = M_CCD(x,y)*M_visit(u,v)\)

This model consists of the following components:

  • A spatially invariant zero point per CCD, constrained across all visits, \(M_CCD\).

  • A Chebyshev polynomial ( \(a_ij*T_i(x)*T_j(y)\) ) per visit, constrained across all CCDs, \(M_visit\).

Because this model’s parameters are degenerate under multiplication by a constant, \(M=(a*M_CCD)*(1/a*M_visit)\), we hold one CCD’s zero point fixed to remove that degeneracy.

Subclassed by lsst::jointcal::ConstrainedFluxModel, lsst::jointcal::ConstrainedMagnitudeModel

class FastFinder
#include <FastFinder.h>

Fast locator in starlists.

This is an auxillary class for matching objects from starlists. It allows to locate rapidly the closest objects from a given position. The very simple strategy is to sort objects according to 1 coordinate x, and to build an index that allows to select the objects with the x coordinate inside an interval. Then every slice in x is sorted according to y, which enables a fast scan inside a x slice. listMatchCollect takes about 10ms (PC 450 MHz, optimized “-O4”) for a match between lists of about 2000 objects each, which is fast enough for our needs. The same “locator” is used in listMatchupShift, to avoid scanning the whole input lists. Timing on listMatchCollect and listMatchupShift indicates a gain in speed by more than one order of magnitude after implementation of this FastFinder.

class FatPoint : public lsst::jointcal::Point
#include <FatPoint.h>

A Point with uncertainties.

Subclassed by lsst::jointcal::BaseStar

class FittedStar : public lsst::jointcal::BaseStar, public lsst::jointcal::PmBlock
#include <FittedStar.h>

The objects which have been measured several times.

MeasuredStars from different CcdImages that represent the same on-sky object all point to one FittedStar.

class FittedStarList : public lsst::jointcal::StarList<FittedStar>
#include <FittedStar.h>

A list of FittedStar s. Such a list is typically constructed by Associations.

class FitterBase
#include <FitterBase.h>

Base class for fitters.

Implements minimize and findOutliers. Chi2, residual, derivative, etc. calculations must be implemented in the child class via the virtual methods.

Subclassed by lsst::jointcal::AstrometryFit, lsst::jointcal::PhotometryFit

class FluxTransformChebyshev : public lsst::jointcal::PhotometryTransformChebyshev
#include <PhotometryTransform.h>

nth-order 2d Chebyshev photometry transform, times the input flux.

class FluxTransformSpatiallyInvariant : public lsst::jointcal::PhotometryTransformSpatiallyInvariant
#include <PhotometryTransform.h>

Photometric offset independent of position, defined as (fluxMag0)^-1.

initialCalibFlux * SpatiallyInvariantTransform -> correctedFlux

class Frame
#include <Frame.h>

rectangle with sides parallel to axes.

when Frame’s are used to define subparts of images, xMin and xMax refer to the first and last pixels in the subimage

class IdentityProjectionHandler : public lsst::jointcal::ProjectionHandler
#include <ProjectionHandler.h>

The simplest implementation of ProjectionHandler. Means that coordinates of objects are expressed in the same space as the arrival mapping space. This is useful for fitting transform rms between images.

class MagnitudeTransformChebyshev : public lsst::jointcal::PhotometryTransformChebyshev
#include <PhotometryTransform.h>

nth-order 2d Chebyshev photometry transform, plus the input flux.

class MagnitudeTransformSpatiallyInvariant : public lsst::jointcal::PhotometryTransformSpatiallyInvariant
#include <PhotometryTransform.h>

Photometric offset independent of position, defined as -2.5 * log(flux / fluxMag0).

initialMagnitude + SpatiallyInvariantTransform -> correctedMagnitude

struct MatchConditions
#include <ListMatch.h>

Parameters to be provided to combinatorial searches.

class MeasuredStar : public lsst::jointcal::BaseStar
#include <MeasuredStar.h>

objects measured on actual images. Coordinates and uncertainties are expressed in pixel image frame. Flux expressed in ADU/s.

class MeasuredStarList : public lsst::jointcal::StarList<MeasuredStar>
#include <MeasuredStar.h>

A list of MeasuredStar. They are usually filled in Associations::createCcdImage.

class OneTPPerVisitHandler : public lsst::jointcal::ProjectionHandler
#include <ProjectionHandler.h>

A projection handler in which all CCDs from the same visit have the same tangent point.

We arbitrarily chose that all chips from a same visit have the same tangent point.

class PhotometryFit : public lsst::jointcal::FitterBase
#include <PhotometryFit.h>

Class that handles the photometric least squares problem.

class PhotometryMapping : public lsst::jointcal::PhotometryMappingBase
#include <PhotometryMapping.h>

A mapping containing a single photometryTransform.

class PhotometryMappingBase
#include <PhotometryMapping.h>

Relates transform(s) to their position in the fitting matrix and allows interaction with the transform(s).

Subclassed by lsst::jointcal::ChipVisitPhotometryMapping, lsst::jointcal::PhotometryMapping

class PhotometryModel

Subclassed by lsst::jointcal::ConstrainedPhotometryModel, lsst::jointcal::SimplePhotometryModel

class PhotometryTransform
#include <PhotometryTransform.h>

A photometric transform, defined in terms of the input flux or magnitude.

Unit agnostic: a higher level Model must keep track of the units going into and out of of its Transforms.

See

lsst::afw::image::PhotoCalib

Subclassed by lsst::jointcal::PhotometryTransformChebyshev, lsst::jointcal::PhotometryTransformSpatiallyInvariant

class PhotometryTransformChebyshev : public lsst::jointcal::PhotometryTransform
#include <PhotometryTransform.h>

nth-order 2d Chebyshev photometry transform.

The 2-d Chebyshev polynomial used here is defined as:

\[ f(x,y) = \sum_i \sum_j a_{i,j} T_i(x) T_j(y) \]

where \(T_n(x)\) is the n-th order Chebyshev polynomial of \(x\) and \(a_{i,j}\) is the corresponding coefficient of the (i,j) polynomial term.

Note that the polynomial order=n means that the highest terms will be of the form:

\[ a_{0,n}*x^n*y^0, a_{n-1,1}*x^(n-1)*y^1, ..., a_{1,n-1}*x^1*y^(n-1), a_{n,0}*x^0*y^n \]

Subclassed by lsst::jointcal::FluxTransformChebyshev, lsst::jointcal::MagnitudeTransformChebyshev

class PhotometryTransformSpatiallyInvariant : public lsst::jointcal::PhotometryTransform
#include <PhotometryTransform.h>

Photometry offset independent of position. Abstract class.

Subclassed by lsst::jointcal::FluxTransformSpatiallyInvariant, lsst::jointcal::MagnitudeTransformSpatiallyInvariant

struct PmBlock
#include <FittedStar.h>

objects whose position is going to be fitted. Coordinates in Common Tangent Plane.

Subclassed by lsst::jointcal::FittedStar

class Point
#include <Point.h>

A point in a plane.

Subclassed by lsst::jointcal::FatPoint

struct ProjectionHandler
#include <ProjectionHandler.h>

This is a virtual class that allows a lot of freedom in the choice of the projection from “Sky” (where coodinates are reported) to tangent plane (where they are compared to transformed measurements)

Subclassed by lsst::jointcal::IdentityProjectionHandler, lsst::jointcal::OneTPPerVisitHandler

class RefStar : public lsst::jointcal::BaseStar
#include <RefStar.h>

Objects used as position anchors, typically USNO stars. Coordinate system defined by user. The Common Tangent Plane seems a good idea.

class SimpleAstrometryMapping : public lsst::jointcal::AstrometryMapping

Subclassed by lsst::jointcal::SimplePolyMapping

class SimpleAstrometryModel : public lsst::jointcal::AstrometryModel
#include <SimpleAstrometryModel.h>

A model where there is one independent transform per CcdImage.

This modeling of distortions can even accommodate images set mixing instruments

Parameters
  • ccdImageList: The exposures that will be fit.

  • projectionHandler: The projection from “Sky” (where the “true” coordinates live) to “Tangent Plane” (where the fitting occurs).

  • initFromWCS: Initialize the model parameters from the original exposure Wcs parameters?

  • nNotFit: How many exposure to hold fixed and not be fit? (the first n will be selected) .

  • order: The polynomial order of each exposure’s pixel-tangent plane mapping.

class SimplePhotometryModel : public lsst::jointcal::PhotometryModel
#include <SimplePhotometryModel.h>

Photometric response model which has a single photometric factor per CcdImage.

Subclassed by lsst::jointcal::SimpleFluxModel, lsst::jointcal::SimpleMagnitudeModel

class SimplePolyMapping : public lsst::jointcal::SimpleAstrometryMapping
#include <SimpleAstrometryMapping.h>

Mapping implementation for a polynomial transformation.

class SparseHisto4d
#include <Histo4d.h>

A class to histogram in 4 dimensions. Uses Sparse storage. The number of bin is limited to 256 per dimension. Used in ListMatch.cc

template<class Star>
class StarList : public std::list<std::shared_ptr<Star>>
#include <StarList.h>

std::lists of Stars.

It is a template class, which means that the Star type remains undefined until a user defines it. The std::list related operations (insertion, sort, traversal) are to be carried out using STL list operations. Most of the Star operations rely on routines to be provided in the Star class, usually user defined. The instanciation of this class for BaseStar (i.e. the replacement of the formal parameter ‘Star’ by ‘BaseStar’) is called BaseStarList. Take care: what is stored is pointers on Star’s and NOT Star’s. This implies that Stars being inserted in the std::list have to be obtained using ‘new’.

class StarMatch
#include <StarMatch.h>

A hanger for star associations.

class TanPixelToRaDec : public lsst::jointcal::BaseTanWcs
#include <AstrometryTransform.h>

The transformation that handles pixels to sideral transformations (Gnomonic, possibly with polynomial distortions).

class TanRaDecToPixel : public lsst::jointcal::AstrometryTransform
#include <AstrometryTransform.h>

This one is the Tangent Plane (called gnomonic) projection (from celestial sphere to tangent plane)

this transform does not implement corrections, since they are defined the other way around (from pixels to sky), and not invertible analytically. The inversion of tangent point WCS (TanPixelToRaDec) is obtained via inverseTransform().

class TanSipPixelToRaDec : public lsst::jointcal::BaseTanWcs
#include <AstrometryTransform.h>

Implements the (forward) SIP distorsion scheme.

class UserTransform : public lsst::jointcal::AstrometryTransform
#include <AstrometryTransform.h>

A run-time transform that allows users to define a AstrometryTransform with minimal coding (just the apply routine).

namespace log

Functions

unsigned lwpID()

Function which returns LWP ID on platforms which support it.

On all other platforms a small incremental integer number (counting number of threads) is returned. This function can be used to produce more human-friendly thread ID for logging instead of regular t format.

class Log
#include <Log.h>

This static class includes a variety of methods for interacting with the the logging module. These methods are not meant for direct use. Rather, they are used by the LOG* macros and the SWIG interface declared in logInterface.h.

namespace meas
namespace algorithms

Functions

std::shared_ptr<afw::image::TransmissionCurve const> makeCoaddTransmissionCurve(std::shared_ptr<afw::geom::SkyWcs const> coaddWcs, afw::table::ExposureCatalog const &inputSensors)

Create a TransmissionCurve that represents the effective throughput on a coadd.

Return

a new TransmissionCurve object.

Parameters
  • [in] coaddWcs: WCS that relates the coadd coordinate system to the sky.

  • [in] inputSensors: A catalog containing the WCSs, bounding boxes and polygons, coaddition weights (in a field called ‘weight’), and TransmissionCurves of the sensor-level images that went into the coadd.

Exceptions
  • NotFoundError: Thrown if the ‘weight’ field does not exist in the schema.

  • InvalidParameterError: Thrown if one or more inputs do not have a TransmissionCurve or a Wcs (ValidPolygons may be null to indicate no spatial restrictions other than the bounding box).

template<typename MaskedImageT>
std::vector<std::shared_ptr<afw::detection::Footprint>> findCosmicRays(MaskedImageT &image, afw::detection::Psf const &psf, double const bkgd, daf::base::PropertySet const &ps, bool const keep = false)
template<typename ExposureT>
PTR(ExposurePatch<ExposureT>)

Factory function for ExposurePatch.

CONST_PTR(afw::detection::Footprint)
template<typename MaskedImageT>
void interpolateOverDefects(MaskedImageT &image, afw::detection::Psf const &psf, std::vector<Defect::Ptr> &badList, double fallbackValue = 0.0, bool useFallbackValueAtEdge = false)
template<typename PixelT>std::shared_ptr<PsfCandidate<PixelT> > lsst::meas::algorithms::makePsfCandidate(PTR( afw::table::SourceRecord ) const & source, PTR( afw::image::Exposure < PixelT >) image)

Parameters
  • source: The detected Source

  • image: The image wherein lies the object

Return a PsfCandidate of the right sort

Cf. std::make_pair

template<typename PixelT>
std::pair<std::shared_ptr<afw::math::LinearCombinationKernel>, std::vector<double>> createKernelFromPsfCandidates(afw::math::SpatialCellSet const &psfCells, geom::Extent2I const &dims, geom::Point2I const &xy0, int const nEigenComponents, int const spatialOrder, int const ksize, int const nStarPerCell = -1, bool const constantWeight = true, int const border = 3)
template<typename PixelT>
int countPsfCandidates(afw::math::SpatialCellSet const &psfCells, int const nStarPerCell = -1)
template<typename PixelT>
std::pair<bool, double> fitSpatialKernelFromPsfCandidates(afw::math::Kernel *kernel, afw::math::SpatialCellSet const &psfCells, int const nStarPerCell = -1, double const tolerance = 1e-5, double const lambda = 0.0)
template<typename PixelT>
std::pair<bool, double> fitSpatialKernelFromPsfCandidates(afw::math::Kernel *kernel, afw::math::SpatialCellSet const &psfCells, bool const doNonLinearFit, int const nStarPerCell = -1, double const tolerance = 1e-5, double const lambda = 0.0)
template<typename ImageT>
double subtractPsf(afw::detection::Psf const &psf, ImageT *data, double x, double y, double psfFlux = std::numeric_limits<double>::quiet_NaN())
template<typename Image>
std::pair<std::vector<double>, afw::math::KernelList> fitKernelParamsToImage(afw::math::LinearCombinationKernel const &kernel, Image const &image, geom::Point2D const &pos)
template<typename Image>
std::pair<std::shared_ptr<afw::math::Kernel>, std::pair<double, double>> fitKernelToImage(afw::math::LinearCombinationKernel const &kernel, Image const &image, geom::Point2D const &pos)

Variables

geom::Point2D const& lsst::meas::algorithms::center{ return std::make_shared<ExposurePatch<ExposureT> >(exp, foot, center)
afw::detection::Footprint const &standardFoot
afw::detection::Footprint const geom::Point2D const& lsst::meas::algorithms::standardCenter
afw::detection::Footprint const geom::Point2D const afw::geom::SkyWcs const& lsst::meas::algorithms::standardWcs{ return std::make_shared<ExposurePatch<ExposureT> >(exp, standardFoot, standardCenter, standardWcs)
struct CoaddBoundedFieldElement
#include <CoaddBoundedField.h>

Struct used to hold one Exposure’s data in a CoaddBoundedField.

class CoaddPsf : public lsst::afw::table::io::PersistableFacade<CoaddPsf>, public lsst::meas::algorithms::ImagePsf
#include <CoaddPsf.h>

CoaddPsf is the Psf derived to be used for non-PSF-matched Coadd images.

It incorporates the logic of James Jee’s Stackfit algorithm for estimating the Psf of coadd by coadding the images of the Psf models of each input exposure.

class Defect : public lsst::afw::image::DefectBase
#include <Interp.h>

Encapsulate information about a bad portion of a detector.

class DoubleGaussianPsf : public lsst::afw::table::io::PersistableFacade<DoubleGaussianPsf>, public lsst::meas::algorithms::KernelPsf
#include <DoubleGaussianPsf.h>

Represent a Psf as a circularly symmetrical double Gaussian.

template<typename ExposureT>
class ExposurePatch
#include <ExposurePatch.h>

A convenience container for the exposure, peak and footprint that will be measured.

This is more useful than a std::pair or similar.

class ImagePsf : public lsst::afw::table::io::PersistableFacade<ImagePsf>, public lsst::afw::detection::Psf
#include <ImagePsf.h>

An intermediate base class for Psfs that use an image representation.

ImagePsf exists only to provide implementations of doComputeApertureFlux and doComputeShape for its derived classes. These implementations use the SincFlux and SdssShape algorithms defined in meas_algorithms, and hence could not be included with the Psf base class in afw.

Subclassed by lsst::meas::algorithms::CoaddPsf, lsst::meas::algorithms::KernelPsf, lsst::meas::algorithms::WarpedPsf, lsst::meas::extensions::psfex::PsfexPsf

class KernelPsf : public lsst::afw::table::io::PersistableFacade<KernelPsf>, public lsst::meas::algorithms::ImagePsf
#include <KernelPsf.h>

A Psf defined by a Kernel.

Subclassed by lsst::meas::algorithms::DoubleGaussianPsf, lsst::meas::algorithms::PcaPsf, lsst::meas::algorithms::SingleGaussianPsf

template<typename T = KernelPsf, typename K = afw::math::Kernel>
class KernelPsfFactory : public lsst::afw::table::io::PersistableFactory
#include <KernelPsfFactory.h>

A PersistableFactory for KernelPsf and its subclasses.

If a KernelPsf subclass has no data members other than its kernel, table persistence for it can be implemented simply by reimplementing getPersistenceName() and registering a specialization of KernelPsfFactory.

Template Parameters
  • T: KernelPsf subclass the factory will construct.

  • K: Kernel subclass the Psf constructor requires.

struct KernelPsfPersistenceHelper
#include <KernelPsfFactory.h>

A read-only singleton struct containing the schema and key used in persistence for KernelPsf.

class PcaPsf : public lsst::afw::table::io::PersistableFacade<PcaPsf>, public lsst::meas::algorithms::KernelPsf
#include <PcaPsf.h>

Represent a PSF as a linear combination of PCA (== Karhunen-Loeve) basis functions.

template<typename PixelT>
class PsfCandidate : public lsst::afw::math::SpatialCellImageCandidate
#include <PsfCandidate.h>

Class stored in SpatialCells for spatial Psf fitting.

PsfCandidate is a detection that may turn out to be a PSF. We’ll assign them to sets of SpatialCells; these sets will then be used to fit a spatial model to the PSF.

class SingleGaussianPsf : public lsst::afw::table::io::PersistableFacade<SingleGaussianPsf>, public lsst::meas::algorithms::KernelPsf
#include <SingleGaussianPsf.h>

Represent a PSF as a circularly symmetrical Gaussian.

class WarpedPsf : public lsst::meas::algorithms::ImagePsf
#include <WarpedPsf.h>

A Psf class that maps an arbitrary Psf through a coordinate transformation.

If K_0(x,x’) is the unwarped PSF, and f is the coordinate transform, then the warped PSF is defined by

K(f(x),f(x’)) = K_0(x,x’) (*)

We linearize the coordinate transform in the vicinity of the point where the PSF is computed. The definition (*) does not include the Jacobian of the transformation, since the afw convention is that PSF’s are normalized to have integral 1 anyway.

namespace interp

Functions

template<typename MaskedImageT>
std::pair<bool, typename MaskedImageT::Image::Pixel> singlePixel(int x, int y, MaskedImageT const &image, bool horizontal, double minval)

Variables

double const lpc_1_c1 = 0.7737

LPC coefficients for sigma = 1, S/N = infty

double const lpc_1_c2 = -0.2737
double const lpc_1s2_c1 = 0.7358

LPC coefficients for sigma = 1/sqrt(2), S/N = infty. These are the coeffs to use when interpolating at 45degrees to the row/column

double const lpc_1s2_c2 = -0.2358
double const min2GaussianBias = -0.5641895835

Mean value of the minimum of two N(0,1) variates.

namespace astrom

Typedefs

typedef std::vector<RecordProxy> ProxyVector

Functions

template<typename MatchT>
afw::math::Statistics makeMatchStatistics(std::vector<MatchT> const &matchList, int const flags, afw::math::StatisticsControl const &sctrl = afw::math::StatisticsControl())

Compute statistics of the distance field of a match list

Parameters
  • [in] matchList: list of matchList between reference objects and sources; fields read:

    • distance: distance between source and reference object, in arbitrary units; the resulting statistics have the same units as distance

  • [in] flags: what to calculate; OR constants such as lsst::afw::math::MEAN, MEANCLIP, STDDEV, MEDIAN, defined in lsst/afw/math/Statitics.h’s Property enum

  • [in] sctrl: statistics configuration

template<typename MatchT>
afw::math::Statistics makeMatchStatisticsInPixels(afw::geom::SkyWcs const &wcs, std::vector<MatchT> const &matchList, int const flags, afw::math::StatisticsControl const &sctrl = afw::math::StatisticsControl())

Compute statistics of on-detector radial separation for a match list, in pixels

Parameters
  • [in] wcs: WCS describing pixel to sky transformation

  • [in] matchList: list of matchList between reference objects and sources; fields read:

    • first: reference object; only the coord is read

    • second: source; only the centroid is read

  • [in] flags: what to calculate; OR constants such as lsst::afw::math::MEAN, MEANCLIP, STDDEV, MEDIAN, defined in lsst/afw/math/Statitics.h’s Property enum

  • [in] sctrl: statistics configuration

template<typename MatchT>
afw::math::Statistics makeMatchStatisticsInRadians(afw::geom::SkyWcs const &wcs, std::vector<MatchT> const &matchList, int const flags, afw::math::StatisticsControl const &sctrl = afw::math::StatisticsControl())

Compute statistics of on-sky radial separation for a match list, in radians

Parameters
  • [in] wcs: WCS describing pixel to sky transformation

  • [in] matchList: list of matchList between reference objects and sources; fields read:

    • first: reference object; only the coord is read

    • second: source; only the centroid is read

  • [in] flags: what to calculate; OR constants such as lsst::afw::math::MEAN, MEANCLIP, STDDEV, MEDIAN, defined in lsst/afw/math/Statitics.h’s Property enum

  • [in] sctrl: statistics configuration

ProxyVector makeProxies(afw::table::SourceCatalog const &sourceCat, afw::geom::SkyWcs const &distortedWcs, afw::geom::SkyWcs const &tanWcs)
ProxyVector makeProxies(afw::table::SimpleCatalog const &posRefCat, afw::geom::SkyWcs const &tanWcs)
afw::table::ReferenceMatchVector matchOptimisticB(afw::table::SimpleCatalog const &posRefCat, afw::table::SourceCatalog const &sourceCat, MatchOptimisticBControl const &control, afw::geom::SkyWcs const &wcs, int posRefBegInd = 0, bool verbose = false)

Match sources to stars in a position reference catalog using optimistic pattern matching B

Optimistic Pattern Matching is described in V. Tabur 2007, PASA, 24, 189-198 “Fast Algorithms for Matching CCD Images to a Stellar Catalogue”

Return

a list of matches; the d field may be set, but you should not rely on it

Parameters
  • [in] posRefCat: catalog of position reference stars; fields read:

    • ”coord”

    • control.refFluxField

  • [in] sourceCat: catalog of detected sources; fields read:

    • ”Centroid_x”

    • ”Centroid_y”

    • control.refFluxField

  • [in] wcs: estimated WCS

  • [in] control: control object

  • [in] posRefBegInd: index of first start to use in posRefCat

  • [in] verbose: true to print diagnostic information to std::cout

PolynomialTransform compose(geom::AffineTransform const &t1, PolynomialTransform const &t2)

Return a PolynomialTransform that is equivalent to the composition t1(t2())

The returned composition would be exact in ideal arithmetic, but may suffer from significant round-off error for high-order polynomials.

PolynomialTransform compose(PolynomialTransform const &t1, geom::AffineTransform const &t2)

Return a PolynomialTransform that is equivalent to the composition t1(t2())

The returned composition would be exact in ideal arithmetic, but may suffer from significant round-off error for high-order polynomials.

std::shared_ptr<afw::geom::SkyWcs> makeWcs(SipForwardTransform const &sipForward, SipReverseTransform const &sipReverse, geom::SpherePoint const &skyOrigin)

Create a new TAN SIP Wcs from a pair of SIP transforms and the sky origin.

Parameters
  • [in] sipForward: Mapping from pixel coordinates to intermediate world coordinates.

  • [in] sipReverse: Mapping from intermediate world coordinates to pixel coordinates.

  • [in] skyOrigin: ICRS position of the gnomonic projection that maps sky coordinates to intermediate world coordinates (CRVAL).

Exceptions
  • pex::exceptions::InvalidParameterError: if the forward and reverse SIP transforms have different CRPIX values or CD matrices.

std::shared_ptr<afw::geom::SkyWcs> transformWcsPixels(afw::geom::SkyWcs const &wcs, geom::AffineTransform const &s)

Create a new SkyWcs whose pixel coordinate system has been transformed via an affine transform.

Return

a new Wcs that satisfies the following:

newWcs = transformWcsPixels(wcs, s);
assert(newWcs.skyToPixel(sky), s(wcs.skyToPixel(sky)));
assert(newWcs.pixelToSky(pixel), wcs.pixelToSky(s.inverted()(pixel)));
for all sky coordinates sky and pixel coordinates pixel.

Parameters
  • [in] wcs: Original SkyWcs object.

  • [in] s: AffineTransform to apply to the pixel coordinate system.

std::shared_ptr<afw::geom::SkyWcs> rotateWcsPixelsBy90(afw::geom::SkyWcs const &wcs, int nQuarter, geom::Extent2I const &dimensions)

Return a new SkyWcs that represents a rotation of the image it corresponds to about the image’s center.

Parameters
  • [in] wcs: Original SkyWcs to be rotated.

  • [in] nQuarter: Number of 90 degree rotations (positive is counterclockwise).

  • [in] dimensions: Width and height of the image.

class OutlierRejectionControl
#include <ScaledPolynomialTransformFitter.h>

Control object for outlier rejection in ScaledPolynomialTransformFitter.

See ScaledPolynomialTransformFitter::rejectOutliers for more information.

class PolynomialTransform
#include <PolynomialTransform.h>

A 2-d coordinate transform represented by a pair of standard polynomials (one for each coordinate).

PolynomialTransform instances should be confined to a single thread.

struct RecordProxy
#include <matchOptimisticB.h>

A wrapper around a SimpleRecord or SourceRecord that allows us to record a pixel position in a way that is independent of the record type.

class ScaledPolynomialTransform
#include <PolynomialTransform.h>

A 2-d coordinate transform represented by a lazy composition of an AffineTransform, a PolynomialTransform, and another AffineTransform.

ScaledPolynomialTransform instances should be confined to a single thread.

class ScaledPolynomialTransformFitter
#include <ScaledPolynomialTransformFitter.h>

A fitter class for scaled polynomial transforms

This class allows for iteration between actual fitting, outlier rejection, and estimation of intrinsic scatter. It also provides access to the current model for debugging via an afw::table::BaseCatalog that contains the input values, output values, and the best-fit-transformed input values.

ScaledPolynomialTransformFitter has two public construction methods:

  • fromMatches fits a transform that maps intermediate world coordinates to pixel coordinates, using as inputs a match of reference coordinates to measured source positions. This sets up the fitter to do outlier rejection and intrinsic scatter estimation.

  • fromGrid fits an inverse to an existing transform, using the to-be-inverted transform to populate a grid of positions. Because the to-be-inverted transform is assumed to be known exactly, fitters initialized with this method have no need for outlier rejection or scatter estimation.

In either case, the fitter creates affine transforms that map the input and output data points onto [-1, 1]. It then fits a polynomial transform that, when composed with the input scaling transform and the inverse of the output scaling transform, maps the input data points to the output data points.

The fitter can be used in an outlier-rejection loop with the following pattern (with user-defined convergence criteria):

while (true) {
    fitter.fit();
    if (converged) break;
    fitter.updateModel();
    fitter.computeIntrinsicScatter();
    fitter.rejectOutliers();
}
This pattern fits a model, uses that model to transform the input points, estimates intrinsic scatter from the differences between model-transformed points and output data points, and finally rejects outliers by sigma-clipping those differences before repeating.

ScaledPolynomialTransformFitter instances should be confined to a single thread.

class SipForwardTransform : public lsst::meas::astrom::SipTransformBase
#include <SipTransform.h>

A transform that maps pixel coordinates to intermediate world coordinates according to the SIP convention.

The SIP forward transform is defined as

\[\begin{split} \left[\begin{array}{ c } x \\ y \end{array}\right] = \mathbf{Z} \left[\begin{array}{ c } (u - u_0) + {\displaystyle\sum_{p,q}^{2 \le p + q \le N}} \mathrm{A}_{p,q} (u-u_0)^p (v-v_0)^q \\ (v - v_0) + {\displaystyle\sum_{p,q}^{2 \le p + q \le N}} \mathrm{B}_{p,q} (u-u_0)^p (v-v_0)^q \end{array}\right] \end{split}\]
where
  • \((u,v)\) are pixel coordinates (zero-indexed).

  • \((x,y)\) are “intermediate world coordinates” the result of applying the gnomonic (TAN) projection at sky origin CRVAL to sky coordinates).

  • \(\mathbf{Z}\) is the \(2 \times 2\) linear transform ( \(\mathrm{CD}\)) matrix.

  • \((u_0,v_0)\) is the pixel origin \(\mathrm{CRPIX}\) (but zero-indexed; the FITS standard is 1-indexed).

  • \(\mathrm{A}\), \(\mathrm{B}\) are the polynomial coefficients of the forward transform.

The SIP convention encourages (but does not require) nulling the zeroth- and first-order elements of \(\mathrm{A}\) and \(\mathrm{B}\), which ensures the representation of a given transform is unique. This also makes fitting a SIP transform to data a nonlinear operation, as well as making the conversion from standard polynomial transforms to SIP form impossible in general. Accordingly, this class does not attempt to null low-order polynomial terms at all when converting from other transforms.

SipForwardTransform instances should be confined to a single thread.

class SipReverseTransform : public lsst::meas::astrom::SipTransformBase
#include <SipTransform.h>

A transform that maps intermediate world coordinates to pixel coordinates according to the SIP convention.

The SIP reverse transform is defined as

\[\begin{split} \left[\begin{array}{ c } u \\ v \end{array}\right] = \left[\begin{array}{ c } u_0 + U + {\displaystyle\sum_{p,q}^{0 \le p + q \le N}} \mathrm{AP}_{p,q} U^p V^q \\ v_0 + V + {\displaystyle\sum_{p,q}^{0 \le p + q \le N}} \mathrm{BP}_{p,q} U^p V^q \\ \end{array}\right] \end{split}\]
with
\[\begin{split} \left[\begin{array}{ c } U \\ V \end{array}\right] = \mathbf{Z}^{-1} \left[\begin{array}{ c } x \\ y \end{array}\right] \end{split}\]
and
  • \((u,v)\) are pixel coordinates.

  • \((x,y)\) are “intermediate world coordinates” the result of applying the gnomonic (TAN) projection at sky origin CRVAL to sky coordinates).

  • \(\mathbf{Z}\) is the \(2 \times 2\) linear transform ( \(\mathrm{CD}\)) matrix.

  • \((u_0,v_0)\) is the pixel origin \(\mathrm{CRPIX}\) (but zero-indexed; the FITS standard is 1-indexed).

  • \(\mathrm{AP}\), \(\mathrm{BP}\) are the polynomial coefficients of the reverse transform.

SipForwardTransform instances should be confined to a single thread.

class SipTransformBase
#include <SipTransform.h>

Base class for SIP transform objects.

This class simply provides some getters for its derived classes. It should not be used directly, and does not define a polymorphic interface.

Subclassed by lsst::meas::astrom::SipForwardTransform, lsst::meas::astrom::SipReverseTransform

namespace detail

Functions

int computePackedOffset(int order)

Compute the index of the first coefficient with the given order in a packed 2-d polynomial coefficient array.

This defines the ordering as

[(0,0), (0,1), (1,0), (0,2), (1,1), (2,0), ...]
(or the same with indices swapped).

int computePackedSize(int order)

Compute this size of a packed 2-d polynomial coefficient array.

void computePowers(Eigen::VectorXd &r, double x)

Fill an array with integer powers of x, so \($r[n] == r^n\).

When multiple powers are needed, this should be signficantly faster than repeated calls to std::pow().

Eigen::VectorXd computePowers(double x, int n)

Return an array with integer powers of x, so \($r[n] == r^n\).

When multiple powers are needed, this should be signficantly faster than repeated calls to std::pow().

class BinomialMatrix
#include <polynomialUtils.h>

A class that computes binomial coefficients up to a certain power.

The binomial coefficient is defined as:

\[ \left(\begin{array}{ c } n k \end{array}right\) = \frac{n!}{k!(n-k)!} \]
with both \(n\) and \(k\) nonnegative integers and \(k \le n\)

This class uses recurrence relations to avoid computing factorials directly, making it both more efficient and numerically stable.

namespace sip

Functions

template<class MatchT>
CreateWcsWithSip<MatchT> makeCreateWcsWithSip(std::vector<MatchT> const &matches, afw::geom::SkyWcs const &linearWcs, int const order, geom::Box2I const &bbox = geom::Box2I(), int const ngrid = 0)

Factory function for CreateWcsWithSip.

template<class MatchT>
class CreateWcsWithSip
#include <CreateWcsWithSip.h>

Measure the distortions in an image plane and express them a SIP polynomials.

Given a list of matching sources between a catalogue and an image, and a linear Wcs that describes the mapping from pixel space in the image and ra/dec space in the catalogue, calculate discrepancies between the two and compute SIP distortion polynomials to describe the discrepancy

SIP polynomials are defined in Shupe at al. (2005) ASPC 347 491.

Note that the SIP standard insists (although it is only mentioned obliquly between Eqns 3 and 4) that the lowest three terms in the distortion polynomials be zero (A00, A10, A01, B00, etc.). To achieve this, we need to adjust the values of CD and CRPIX from the input wcs. This may not be the behaviour you expect.

A Wcs may be created in a variety of ways (e.g. lsst::meas::astrom::net::GlobalAstrometrySolution ), and the list of matched sources (matches) can be generated with the matchRaDec function.

#Example usage
matches = matchRaDec(catSet, srcSet, 1.0*afwGeom.arcseconds, true)
wcs = getWcsFromSomewhere()

maxScatter=0.1
maxOrder= 10
sipObject = CreateWcsWithSip(matches, wcs, maxScatter, maxOrder)
wcs = sipObject.getNewWcs()

Note that the matches must be one-to-one; this is ensured by passing closest=true to matchRaDec.

template<class FittingFunc>
class LeastSqFitter1d
#include <LeastSqFitter1d.h>

Fit an lsst::afw::math::Function1 object to a set of data points in one dimension.

The class is templated over the kind of object to fit.

Input is a list of x ordinates for a set of points, the y coordinate, and the uncertainties, s. order is order of the polynomial to fit (e.g if the templated function is lsst::afw::math::PolynomialFunction1, then order=3 => fit a function of the form \(ax^2+bx+c\)

See

LeastSqFitter1d

Template Parameters
Parameters
  • x: Ordinate of points to fit

  • y: Co-ordinate of pionts to fit

  • s: 1 \(\sigma\) uncertainties in z

  • order: Polynomial order to fit

template<class FittingFunc>
class LeastSqFitter2d
#include <LeastSqFitter2d.h>

Fit an lsst::afw::math::Function1 object to a set of data points in two dimensions.

The class is templated over the kind of object to fit. Note that we fit the 1d object in each dimension, not the 2d one.

Input is a list of x and y ordinates for a set of points, the z coordinate, and the uncertainties, s. order is order of the polynomial to fit (e.g if the templated function is lsst::afw::math::PolynomialFunction1, then order=3 => fit a function of the form \(ax^2+bx+c\)

See

LeastSqFitter1d

Template Parameters
Parameters
  • x: Ordinate of points to fit

  • y: Ordinate of points to fit

  • z: Co-ordinate of pionts to fit

  • s: 1 \(\sigma\) uncertainties in z

  • order: Polynomial order to fit

class MatchSrcToCatalogue
#include <MatchSrcToCatalogue.h>

Match a SourceSet of objects with known ra/dec with a SourceSet of objects with known xy positions Take a catalogue of objects with known positions, a catalogue of objects with known xy, and a wcs to convert one xy <> ra/dec. This class then finds the set of objects with common ra/dec.

The simplest usage is to create an object of this class, then access the corresponence sets with getMatchedImgSet() and getMatchedCatSet(). Creating the object automatically calculates the sets of corresponences for you. If you are unhappy with these matches, you can change one or more of your input arguments and redo the match with findMatches()

Using this class has the side effect of updating the coord field of the input SourceCatalog (which may be desirable).

namespace base

Unnamed Group

typedef int ElementCount
typedef double Flux
typedef double FluxErrElement
typedef double Mag
typedef double MagErrElement
typedef float ErrElement
typedef double CentroidElement
typedef double ShapeElement
typedef geom::Point<CentroidElement, 2> Centroid
typedef Eigen::Matrix<ErrElement, 2, 2, Eigen::DontAlign> CentroidCov
typedef afw::geom::ellipses::Quadrupole Shape
typedef Eigen::Matrix<ErrElement, 3, 3, Eigen::DontAlign> ShapeCov
typedef Eigen::Matrix<ShapeElement, 3, 3, Eigen::DontAlign> ShapeTrMatrix

Enums

enum UncertaintyEnum

An enum used to specify how much uncertainty information measurement algorithms provide.

Currently, only ResultMappers (not Results) make use of these distinctions; Result structs always have data members that could hold the full-covariance, but may set some of these to NaN.

Values:

NO_UNCERTAINTY = 0

Algorithm provides no uncertainy information at all.

SIGMA_ONLY = 1

Only the diagonal elements of the covariance matrix are provided.

FULL_COVARIANCE = 2

The full covariance matrix is provided.

Functions

LSST_EXCEPTION_TYPE(FatalAlgorithmError, lsst::pex::exceptions::RuntimeError, lsst::meas::base::FatalAlgorithmError)

Exception to be thrown when a measurement algorithm experiences a fatal error.

This error type causes the meas_base framework to throw completely out of the measurement loop which is run for each exposure, sourceCatalog pair.

LSST_EXCEPTION_TYPE(PixelValueError, lsst::pex::exceptions::DomainError, lsst::meas::base::PixelValueError)

Exception to be thrown when a measurement algorithm encounters a NaN or infinite pixel.

When caught by the plugin framework, this exception will generate a log message.

ShapeTrMatrix makeShapeTransformMatrix(geom::LinearTransform const &xform)

Construct a matrix suitable for transforming second moments.

Given an LinearTransform which maps from positions (x, y) to (a, d), returns a 3-by-3 matrix which transforms (xx, yy, xy) to (aa, dd, ad).

That is, given an input transform described by the matrix

| A11 | A12 | | A21 | A22 |

we return the matrix

| A11*A11 | A12*A12 | 2*A11*A12 | | A21*A21 | A22*A22 | 2*A21*A22 | | A11*A21 | A12*A22 | A11*A22 + A12*A21 |

Return

A 3-by-3 transformation matrix for the second order moments

Parameters
  • [in] xform: LinearTransform describing the coordinate mapping

class ApertureFluxAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <ApertureFlux.h>

Base class for multiple-aperture photometry algorithms

ApertureFluxAlgorithm serves as an intermediate base class for all aperture fluxes, which it assumes have that capability of measuring multiple apertures (even if they are not always configured to do so).

Concrete implementations for single-aperture flux measurements are provided as static methods, as well as a consistent interface and control object for its derived classes. Currently, we only have one derived class, CircularApertureFluxAlgorithm, but in the future we anticipate adding more derived classes for e.g. elliptical apertures, or apertures that are circular in sky coordinates rather than pixel coordinates.

Subclassed by lsst::meas::base::CircularApertureFluxAlgorithm

class ApertureFluxControl
#include <ApertureFlux.h>

Configuration object for multiple-aperture flux algorithms

struct ApertureFluxResult : public lsst::meas::base::FluxResult
#include <ApertureFlux.h>

A Result struct for running an aperture flux algorithm with a single radius.

This simply extends FluxResult to add the appropriate error flags for aperture fluxes.

class ApertureFluxTransform : public lsst::meas::base::BaseTransform
#include <ApertureFlux.h>

Measurement transformation for aperture fluxes

Transforms instFluxes with associated errors to magnitudes. Correctly handles multiple apertures. Flags are propagated from input to output.

class BaseAlgorithm
#include <Algorithm.h>

Ultimate abstract base class for all C++ measurement algorithms

New algorithms should not inherit directly from this class.

Subclassed by lsst::meas::base::ForcedAlgorithm, lsst::meas::base::SingleFrameAlgorithm

class BaseTransform
#include <Transform.h>

Abstract base class for all C++ measurement transformations

Measurement plugins return results in raw, uncalibrated units (eg fluxes or positions in pixels). The transformation system provides a mechanism for post-processing those results into a calibrated form (magnitudes, celestial coordinates, etc).

A measurement transformation should derive from BaseTransform. It should implement a constructor which takes three arguments:

  • A Control object describing the configuration of the measurement plugin.

  • The name of the measurement plugin whose outputs are to be transformed (std::string);

  • An lsst::afw::table::SchemaMapper which links the input and output catalogs;

The constructor should use the SchemaMapper to map fields from the input to output schemas and add additional keys to the output as required. For example:


Derived classes should also implement operator() following the interface below. This will be called with a catalog containing the results of the measurement plugin and a catalog to be populated with transformed quantities, as well as WCS and calibration information. For example:


Note that it is safe to assume that both catalogs passed to operator() are contiguous in memory. It is good practice to ensure that they are equal in size: this may be conveniently achieved by calling BaseTransform::checkCatalogSize().

operator() may throw LengthError if the transformation is impossible to complete. In this case, the contents of outputCatalog is not guaranteed.

Subclassed by lsst::meas::base::ApertureFluxTransform, lsst::meas::base::CentroidTransform, lsst::meas::base::FluxTransform, lsst::meas::base::SdssShapeTransform

class BlendednessAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <Blendedness.h>

Compute metrics that measure how blended objects are.

Blendedness is initialized once for a given Schema, then run repeatedly by calls to measureChildPixels and measureParentPixels (in any order, possibly with multiple sources interleaved). Since it needs access to both the image with with noise and the noise replaced children it cannot use the standard plugin interface.

struct CentroidResult
#include <CentroidUtilities.h>

A reusable struct for centroid measurements.

Subclassed by lsst::meas::base::SdssShapeResult

class CentroidResultKey : public lsst::afw::table::FunctorKey<CentroidResult>
#include <CentroidUtilities.h>

A FunctorKey for CentroidResult.

This class makes it easy to copy centroids and their uncertainties to and from records, and provides a method to add the appropriate fields to a Schema.

class CentroidTransform : public lsst::meas::base::BaseTransform
#include <CentroidUtilities.h>

Base for centroid measurement transformations.

Provides a basic transform from centroid plus associated uncertainty to celestial position with uncertainty. The basic “flag” attribute for the measurement algorithm is propagated to the output.

Subclasses should define a constructor which take a Control argument corresponding to the measurement algorithm being transformed and ensure that any other necessary flags are propagated.

Subclassed by lsst::meas::base::NaiveCentroidTransform, lsst::meas::base::SdssCentroidTransform

struct FlagDefinition
#include <FlagHandler.h>

Simple class used to define and document flags The name and doc constitute the identity of the FlagDefinition The number is used for indexing, but is assigned arbitrarily.

class FlagDefinitionList
#include <FlagHandler.h>

vector-type utility class to build a collection of FlagDefinitions

class FlagHandler
#include <FlagHandler.h>

Utility class for handling flag fields that indicate the failure modes of an algorithm.

The typical pattern for using FlagHandler within an Algorithm is:

  • Add a FlagHandler object as a data member.

  • Create a FlagDefinitionList to specify the name and doc for each flag Add a “general” failure flag if one is needed (this indicates that some failure occurred). Add specific error flags for each type of error (these indicate a specific failure).

  • Initialize the FlagHandler data member within the Algorithm’s constructor, using the static addFields method to add the flags from the FlagDefinitionList to the schema.

See PsfFluxAlgorithm for a complete example.

struct FluxResult
#include <FluxUtilities.h>

A reusable result struct for instFlux measurements.

Subclassed by lsst::meas::base::ApertureFluxResult, lsst::meas::base::SdssShapeResult

class FluxResultKey : public lsst::afw::table::FunctorKey<FluxResult>
#include <FluxUtilities.h>

A FunctorKey for FluxResult.

This class makes it easy to copy instFluxes and their uncertainties to and from records, and provides a method to add the appropriate fields to a Schema.

class FluxTransform : public lsst::meas::base::BaseTransform
#include <FluxUtilities.h>

Base for instFlux measurement transformations

Provides a basic transform from instFlux plus associated uncertainty to magnitude with uncertainty. The basic “flag” attribute for the measurement algorithm is propagated to the output

Subclasses should define a constructor which take a Control argument corresponding to the measurement algorithm being transformed and ensure that any other necessary flags are propagated.

Subclassed by lsst::meas::base::GaussianFluxTransform, lsst::meas::base::LocalBackgroundTransform, lsst::meas::base::PeakLikelihoodFluxTransform, lsst::meas::base::PsfFluxTransform, lsst::meas::base::ScaledApertureFluxTransform

class ForcedAlgorithm : public virtual lsst::meas::base::BaseAlgorithm
#include <Algorithm.h>

Base class for algorithms that measure the properties of sources on one image, using previous measurements on another image to hold certain quantities fixed.

ForcedAlgorithm can be used when measuring both on single exposures and coadds, and is typically used to measure colors by holding centroids, apertures, or other model parameters fixed while allowing amplitudes to vary.

In addition to the virtual methods defined here, ForcedAlgorithm also puts requirements on constructor signatures; see the wrapForcedAlgorithm Python function for more information.

Most algorithms will not need to make use of the reference record or WCS, as transformed centroids and shapes should generally be available via the slots in measRecord, but these are made available for algorithms that need to transform more complex information. If that is the case, the algorithm may want to inherit from SimpleAlgorithm instead of inheriting from ForcedAlgorithm directly.

Subclassed by lsst::meas::base::SimpleAlgorithm

class GaussianFluxAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <GaussianFlux.h>

A measurement algorithm that estimates instFlux using an elliptical Gaussian weight.

This algorithm computes instFlux as the dot product of an elliptical Gaussian weight function with the image. The size and ellipticity of the weight function are determined using the SdssShape algorithm, or retreived from a named field.

class GaussianFluxControl
#include <GaussianFlux.h>

A C++ control class to handle GaussianFluxAlgorithm’s configuration.

class LocalBackgroundAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <LocalBackground.h>

A measurement algorithm that estimates the local background value per pixel.

class LocalBackgroundControl
#include <LocalBackground.h>

Configuration of LocalBackgroundAlgorithm.

struct MagResult
#include <FluxUtilities.h>

A reusable result struct for magnitudes.

class MagResultKey : public lsst::afw::table::FunctorKey<MagResult>
#include <FluxUtilities.h>

A FunctorKey for MagResult.

This class makes it easy to copy magnitudes and their uncertainties to and from records, and provides a method to add the appropriate fields to a Schema.

class MeasurementError : public RuntimeError
#include <exceptions.h>

Exception to be thrown when a measurement algorithm experiences a known failure mode.

In addition to the usual message, MeasurementError must be constructed with the bit of the algorithm-specific flag that indicates the known failure mode. This allows the measurement framework to set that flag upon failure. Typically, this flag bit is also used to look up the message from the algorithm classes FlagDefinition list; the common pattern is:

if (badThingHappened) {
    // BAD_THING is an enum value from the Algorithm's FlagBits enum; getFlagDefinitions()
    // is a static method algorithms are expected to define.
    throw LSST_EXCEPT(MeasurementError, getFlagDefinitions()[BAD_THING), BAD_THING);
 }

class NaiveCentroidAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <NaiveCentroid.h>

A class that calculates a centroid as a simple unweighted first moment of the 3x3 region around a pixel.

A fixed background (set via config) may optionally be subtracted. This algorithm does not currently report an error, but it probably should.

class NaiveCentroidControl
#include <NaiveCentroid.h>

A C++ control class to handle NaiveCentroidAlgorithm’s configuration.

class PeakLikelihoodFluxAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <PeakLikelihoodFlux.h>

A measurement algorithm that estimates the peak instrument flux, using a filtered image which has been convolved with its own PSF.

class PeakLikelihoodFluxControl
#include <PeakLikelihoodFlux.h>

C++ control object for peak likelihood instrument flux.

Peak likelihood flux requires an image that has been filtered by convolving with its own PSF (or an approximate model). It is equivalent to a PSF instrument flux (e.g. as computed by PsfFluxAlgorithm) computed on a non-preconvolved image.

The PSF must be provided in the exposure, as it is used to compute a weighting factor.

Flux and error are computed as follows:

  • instFlux = sum(unfiltered image * PSF) / sum(PSF^2) = value of peak of filtered source / sum(PSF^2)

  • err = sqrt(sum(unfiltered variance * PSF^2) / sum(PSF^2)^2) = sqrt(value of filtered variance at peak / sum(PSF^2)^2)

  • The pixels in the image are samples of a band-limited function, and by using a sinc interpolation (via a warping kernel) we can evaluate this function at any point. We use this technique to compute the peak of the function, which is assumed to be at the centroid of the filtered source.

class PixelFlagsAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <PixelFlags.h>

A measurement algorithm that gets mask bits from the exposure and sets flag bits to summarize which bits are set within a source’s footprint.

class PixelFlagsControl
#include <PixelFlags.h>

A C++ control class to handle PixelFlagsAlgorithm’s configuration.

class PsfFluxAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <PsfFlux.h>

A measurement algorithm that estimates instFlux using a linear least-squares fit with the Psf model.

The PsfFlux algorithm is extremely simple: we do a least-squares fit of the Psf model (evaluated at a given position) to the data. For point sources, this provides the optimal instFlux measurement in the limit where the Psf model is correct. We do not use per-pixel weights in the fit, as this results in bright stars being fit with a different effective profile than faint stairs.

class PsfFluxControl
#include <PsfFlux.h>

A C++ control class to handle PsfFluxAlgorithm’s configuration.

In C++, we define Control objects to handle configuration information. Using the LSST_CONTROL_FIELD macro and lsst.pex.config.wrap.makeConfigClass, we can turn these into more full-featured Config classes in Python. While the user will usually interact with the Config class, the plugin wrapper system will turn Config instances into Control instances when passing them to C++.

This should logically be an inner class, but Swig doesn’t know how to parse those.

class SafeCentroidExtractor
#include <InputUtilities.h>

Utility class for measurement algorithms that extracts a position from the Centroid slot and handles errors in a safe and consistent way.

class SafeShapeExtractor
#include <InputUtilities.h>

Utility class for measurement algorithms that extracts an ellipse from the Shape slot and handles errors in a safe and consistent way.

class ScaledApertureFluxAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <ScaledApertureFlux.h>

Measure the instFlux in an aperture scaled to the PSF.

This algorithm performs a sinc aperture instFlux measurement where they size of the aperture is determined by multiplying the FWHM of the PSF by the scaling factor specified in the algorithm configuration.

class SdssCentroidAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <SdssCentroid.h>

The Sdss Centroid Algorithm.

class SdssCentroidControl
#include <SdssCentroid.h>

A C++ control class to handle SdssCentroidAlgorithm’s configuration.

class SdssShapeAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <SdssShape.h>

Measure the image moments of source using adaptive Gaussian weights.

This algorithm measures the weighted second moments of an image using a Gaussian weight function, which is iteratively updated to match the current weights. If this iteration does not converge, it can fall back to using unweighted moments, which can be significantly noisier.

See Bernstein & Jarvis, 2002, for more information on this type of algorithm. Note that the code here makes no attempt to correct for the PSF; for PSF corrected ellipticities using weighted moments please use the shapeHSM package.

class SdssShapeControl
#include <SdssShape.h>

A C++ control class to handle SdssShapeAlgorithm’s configuration.

class SdssShapeResult : public lsst::meas::base::ShapeResult, public lsst::meas::base::CentroidResult, public lsst::meas::base::FluxResult
#include <SdssShape.h>

Result object SdssShapeAlgorithm.

Because we have use cases for running SdssShape outside of the measurement framework (in particular, we need to run it on PSF model images), we provide an interface that doesn’t need to use SourceRecord for its inputs and outputs. Instead, it returns an instance of this class.

Note: for what I guess are historical reasons, SdssShape computes covariance terms between the instFlux and the shape, but not between the instFlux and centroid or centroid and shape.

This should logically be an inner class, but Swig doesn’t know how to parse those.

class SdssShapeResultKey : public lsst::afw::table::FunctorKey<SdssShapeResult>
#include <SdssShape.h>

A FunctorKey that maps SdssShapeResult to afw::table Records.

This is used internally by SdssShapeAlgorithm to transfer results from SdssShapeResult to SourceRecord, but it can also be used in the other direction by codes that need to extra an SdssShapeResult from a record.

class SdssShapeTransform : public lsst::meas::base::BaseTransform
#include <SdssShape.h>

Transformation for SdssShape measurements.

SdssShape measures not just shape but also instFlux and centroid. This transform operates on the first directly, and delegates to the Flux and Centroid transforms for the other two.

struct ShapeResult
#include <ShapeUtilities.h>

A reusable struct for moments-based shape measurements.

Shape measurements and their errors should always be in pixels coordinates. This struct should generally be preferred over a custom struct with other ellipse parametrizations unless the measurement takes place in another parametrization and a transformation to this one would result in a loss of information or obfuscate the results of the measurement (i.e. use this one unless you have a good reason not to).

Subclassed by lsst::meas::base::SdssShapeResult

class ShapeResultKey : public lsst::afw::table::FunctorKey<ShapeResult>
#include <ShapeUtilities.h>

A FunctorKey for ShapeResult.

This class makes it easy to copy shapes and their uncertainties to and from records, and provides a method to add the appropriate fields to a Schema.

class SimpleAlgorithm : public lsst::meas::base::SingleFrameAlgorithm, public lsst::meas::base::ForcedAlgorithm
#include <Algorithm.h>

An abstract base classes for which the same implementation can be used for both SingleFrameAlgorithm and ForcedAlgorithm.

SimpleAlgorithm allows a ForcedAlgorithm to be defined using the measure() and measureN() signatures of SingleFrameAlgorithm. It should be used for any algorithm for which the forced version of the algorithm does not require anything to be transformed beyond the centroid and shape, and for which the the parameters being fit are the same for both single-frame and forced measurement. This should be the case for all flux algorithms that don’t involve fitting any additional model parameters. It can also be used for centroid and shape algorithms, where having a version that can re-measure values in forced mode may be useful for diagnostic purposes even if it is not useful for science.

Subclassed by lsst::ip::diffim::DipoleCentroidAlgorithm, lsst::ip::diffim::DipoleFluxAlgorithm, lsst::meas::base::ApertureFluxAlgorithm, lsst::meas::base::BlendednessAlgorithm, lsst::meas::base::GaussianFluxAlgorithm, lsst::meas::base::LocalBackgroundAlgorithm, lsst::meas::base::NaiveCentroidAlgorithm, lsst::meas::base::PeakLikelihoodFluxAlgorithm, lsst::meas::base::PixelFlagsAlgorithm, lsst::meas::base::PsfFluxAlgorithm, lsst::meas::base::ScaledApertureFluxAlgorithm, lsst::meas::base::SdssCentroidAlgorithm, lsst::meas::base::SdssShapeAlgorithm, lsst::meas::extensions::photometryKron::KronFluxAlgorithm, lsst::meas::extensions::simpleShape::SimpleShape, lsst::meas::modelfit::DoubleShapeletPsfApproxAlgorithm

template<typename PixelT>
class SincCoeffs
#include <SincCoeffs.h>

A singleton to calculate and cache the coefficients for sinc photometry

Caching is only performed for circular apertures (because elliptical apertures are assumed to be generated dynamically, and hence not expected to recur). Caching must be explicitly requested for a particular circular aperture (using the ‘cache’ method).

class SingleFrameAlgorithm : public virtual lsst::meas::base::BaseAlgorithm
#include <Algorithm.h>

Base class for algorithms that measure the properties of sources on single image.

SingleFrameAlgorithm defines the interface used in measuring both on single exposure images and on coadds.

In addition to the virtual methods defined here, SingleFrameAlgorithm also puts requirements on constructor signatures; see the wrapSingleFrameAlgorithm Python function for more information.

Subclassed by lsst::meas::base::SimpleAlgorithm

namespace python

Functions

template<class Algorithm, class PyAlg>
std::enable_if<!std::is_abstract<Algorithm>::value, void>::type declareAlgorithmConstructor(PyAlg &cls)

Wrap the standard algorithm constructor.

Template Parameters
  • Algorithm: The algorithm class.

  • PyAlg: The pybind11::class_ class corresponding to Algorithm.

Parameters
  • [inout] cls: The pybind11 wrapper for Algorithm.

template<class Algorithm, class PyAlg>
std::enable_if<std::is_abstract<Algorithm>::value, void>::type declareAlgorithmConstructor(PyAlg &cls)

Dummy function for not wrapping the constructor of an abstract base class.

Pybind11 cannot wrap such constructors, and there is no reason to call them from Python anyway.

Template Parameters
  • Algorithm: The algorithm class.

  • PyAlg: The pybind11::class_ class corresponding to Algorithm.

Parameters
  • [inout] cls: The pybind11 wrapper for Algorithm.

template<class Algorithm, class PyAlg>
void declareAlgorithm(PyAlg &clsAlgorithm)

Wrap the implicit API used by meas_base’s algorithms.

This function only initializes constructors, fields, and methods common to all Algorithms.

Template Parameters
  • Algorithm: The algorithm class.

  • PyAlg: The pybind11::class_ class corresponding to Algorithm.

Parameters
  • [inout] clsAlgorithm: The pybind11 wrapper for Algorithm.

template<class Algorithm, class Control, class PyAlg, class PyCtrl>
void declareAlgorithm(PyAlg &clsAlgorithm, PyCtrl &clsControl)

Wrap the implicit API used by meas_base’s algorithm-control pairs (no transform).

This function only initializes constructors, fields, and methods common to all Algorithms and Controls.

Template Parameters
  • Algorithm: The algorithm class.

  • Control: The control class. Must equal Algorithm::Control and Transform::Control.

  • PyAlg: The pybind11::class_ class corresponding to Algorithm.

  • PyCtrl: The pybind11::class_ class corresponding to Control.

Parameters
  • [inout] clsAlgorithm[inout] clsControl: The pybind11 wrappers for the respective C++ classes.

template<class Algorithm, class Control, class Transform, class PyAlg, class PyCtrl, class PyXform>
void declareAlgorithm(PyAlg &clsAlgorithm, PyCtrl &clsControl, PyXform &clsTransform)

Wrap the implicit API used by meas_base’s algorithm-control-transform triads.

This function only initializes constructors, fields, and methods common to all Algorithms, Controls, and Transforms.

Template Parameters
  • Algorithm: The algorithm class.

  • Control: The control class. Must equal Algorithm::Control and Transform::Control.

  • Transform: The transform class.

  • PyAlg: The pybind11::class_ class corresponding to Algorithm.

  • PyCtrl: The pybind11::class_ class corresponding to Control.

  • PyXform: The pybind11::class_ class corresponding to Transform.

Parameters
  • [inout] clsAlgorithm[inout] clsControl[inout] clsTransform: The pybind11 wrappers for the respective C++ classes.

namespace extensions
namespace photometryKron
class KronFluxAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <photometryKron.h>

A measurement algorithm that estimates flux using Kron photometry.

class KronFluxControl
#include <photometryKron.h>

C++ control object for Kron flux.

See

KronFluxConfig.

namespace psfex
class PsfexPsf : public lsst::afw::table::io::PersistableFacade<PsfexPsf>, public lsst::meas::algorithms::ImagePsf
#include <PsfexPsf.h>

Represent a PSF as a linear combination of PSFEX (== Karhunen-Loeve) basis functions.

namespace simpleShape
class SimpleShapeControl
#include <simpleShape.h>

A C++ control class to handle SdssShapeAlgorithm’s configuration.

class SimpleShapeResult
#include <simpleShape.h>

Struct to hold the results of SimpleShape when we don’t run it as a plugin.

namespace modelfit

Unnamed Group

typedef float Pixel

Typedefs to be used for pixel values

Unnamed Group

typedef double Scalar

Typedefs to be used for probability and parameter values

typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector
typedef afw::table::Key<Scalar> ScalarKey
typedef afw::table::Key<afw::table::Array<Scalar>> ArrayKey

Typedefs

typedef std::vector<PTR(Model)> ModelVector

Functions

void solveTrustRegion(ndarray::Array<Scalar, 1, 1> const &x, ndarray::Array<Scalar const, 2, 1> const &F, ndarray::Array<Scalar const, 1, 1> const &g, double r, double tolerance)

Solve a symmetric quadratic matrix equation with a ball constraint.

This computes a near-exact solution to the “trust region subproblem” necessary in trust-region-based nonlinear optimizers:

\[ \min_x{\quad g^T x + \frac{1}{2}x^T F x}\quad\quad\quad \text{s.t.} ||x|| \le r \]

The tolerance parameter sets how close to \(r\) we require the norm of the solution to be when it lies on the constraint, as a fraction of \(r\) itself.

This implementation is based on the algorithm described in Section 4.3 of “Nonlinear Optimization” by Nocedal and Wright.

class AdaptiveImportanceSampler : public lsst::meas::modelfit::Sampler
#include <AdaptiveImportanceSampler.h>

Sampler class that performs Monte Carlo sampling, while iteratively updating the analytic distribution from which points are drawn.

Between the iterations defined in the control object, the prior is applied to the samples, and the mixture distribution is updated using expectation-maximization to match the samples.

class CModelAlgorithm
#include <CModel.h>

Main public interface class for CModel algorithm.

See CModel Magnitudes for a full description of the algorithm.

This class provides the methods that actually execute the algorithm, and (depending on how it is constructed) holds the Key objects necessary to use SourceRecords for input and output.

struct CModelControl
#include <CModel.h>

The main control object for CModel, containing parameters for the final linear fit and aggregating the other control objects.

struct CModelResult
#include <CModel.h>

Master result object for CModel, containing results for the final linear fit and three nested CModelStageResult objects for the results of the previous stages.

struct CModelStageControl
#include <CModel.h>

Nested control object for CModel that configures one of the three (“initial”, “exp”, “dev”) nonlinear fitting stages.

struct CModelStageResult
#include <CModel.h>

Result object for a single nonlinear fitting stage of the CModel algorithm

class DoubleShapeletPsfApproxAlgorithm : public lsst::meas::base::SimpleAlgorithm
#include <DoubleShapeletPsfApprox.h>

An algorithm that fits a 2-component shapelet approximation to the PSF model.

This algorithm fits a similar model to the one that has been used on the HSC side for several data releases, but uses the improved optimizer in meas_modelfit instead of the one in (the now defunct) meas_extensions_multiShapelet and using moments to reduce the number of parameters in the fit. It is faster and more robust than GeneralShapeletPsfApprox, but much less flexible.

The model is not a fully general one, even for two shapelet components. We tie the ellipticities of the two components together, hold the center fixed, and keep their radii fixed at a value set in the configuration; this means we fit only one set of ellipse parameters, instead of two.

class DoubleShapeletPsfApproxControl
#include <DoubleShapeletPsfApprox.h>

Control object used to configure a 2-shapelet fit to a PSF model; see DoubleShapeletPsfApproxAlgorithm.

class EpochFootprint
#include <UnitTransformedLikelihood.h>

An image at one epoch of a galaxy, plus associated info

Includes one image of a galaxy and and associated footprint and multi-shapelet PSF model

class GeneralPsfFitter
#include <GeneralPsfFitter.h>

Class for fitting multishapelet models to PSF images.

This class fits up to four shapelet expansions simultaneously to a PSF image, with the relative radii and number of shapelet coefficients for each expansion separately configurable. These expansions are also named; this allows us to map different fits with some expansions disabled to each other, in order to first fit an approximate model and follow this up with a more complete model, using the approximate model as a starting point.

The configuration also defines a simple Bayesian prior for the fit, defined using simple independent Gaussians for the ellipse parameters of each component. The priors can be disabled by setting their width (xxPriorSigma in the control object) to infinity, and those parameters can be held fixed at their input values by setting the prior width to zero. The priors are always centered at the input value, meaning that it may be more appropriate to think of the priors as a form of regularization, rather than a rigorous prior. In fact, it’s impossible to use a prior here rigorously without a noise model for the PSF image, which is something the LSST Psf class doesn’t provide, and here is just provided as a constant noise sigma to be provided by the user (who generally just has to chose a small number arbitrarily). Decreasing the noise sigma will of course decrease the effect of the priors (and vice versa). In any case, having some sort of regularization is probably a good idea, as this is a very high-dimensional fit.

Subclassed by lsst::meas::modelfit::GeneralPsfFitterAlgorithm

class GeneralPsfFitterComponentControl
#include <GeneralPsfFitter.h>

Control object used to define one piece of multishapelet fit to a PSF model; see GeneralPsfFitterControl

class GeneralPsfFitterControl
#include <GeneralPsfFitter.h>

Control object used to configure a multishapelet fit to a PSF model; see GeneralPsfFitter.

The default configuration corresponds to fitting an elliptical double-Gaussian, in which each component can have different radii, positions, and ellipticities. While the fitter can support much more complex models, at present, fitting these is prohibitively slow, and is not recommended in production environments (use DoubleShapeletPsfApprox instead).

class ImportanceSamplerControl
#include <AdaptiveImportanceSampler.h>

Control object for one iteration of adaptive importance sampling.

See

AdaptiveImportanceSampler, AdaptiveImportanceSamplerTask

class Likelihood
#include <Likelihood.h>

Base class for optimizer/sampler likelihood functions that compute likelihood at a point.

Likelihood abstracts the problem of computing the likelihood over different kinds of data. It is responsible for creating a “model matrix” that maps amplitudes to data values, and maintaining a vector of scaled, weighted data values that corresponds to it. Its components can be represented best in the mathematical formula for a -log likelihood assuming Gaussian data and a model with both nonlinear parameters \(\theta\) and linear (“amplitude”) parameters \(\alpha\):

\[ L(\alpha,\theta) = \frac{1}{2}\left(y - A(\theta)\alpha\right)^T\, \Sigma^{-1}\,\left(y - A(\theta)\alpha\right) \]
where \(y\) is the data vector, \(\Sigma\) is the data covariance matrix (assumed to be diagonal), and \(A(\theta)\) is the “true” model matrix (parametrized on the nonlinear parameters).

When fitting or sampling from the likelihood, however, we don’t want to use these quantities directly, and they aren’t what the Likelihood class provides. Instead, we reparametrize with:

\[ w_i \equiv \Sigma_{i,i}^{-1/2} \]
\[ z_i = w_i y_i \]
\[ B_{i,j} = w_i A_{i,j} \]
resulting in the equivalent formula:
\[ L(\alpha,\theta) = \frac{1}{2}\left(z-B(\theta)\alpha\right)^T\,\left(z-B(\theta)\alpha\right) \]
The \(w_i\) are the weights, which are applied to both the data vector and the model matrix to account for the noise in the data. In some cases, we may choose to use a constant weight rather than per-pixel weights, but will will still use a vector to represent it.

Subclassed by lsst::meas::modelfit::MultiShapeletPsfLikelihood, lsst::meas::modelfit::UnitTransformedLikelihood

struct LocalUnitTransform
#include <UnitSystem.h>

A local mapping between two UnitSystems.

LocalUnitTransform is “local” because it linearizes the Wcs and evaluates the PhotoCalib transform at a particular predifined point, allowing it to represent the geometric transform as an AffineTransform and the photometric transform as a simple scaling.

class MixtureComponent
#include <Mixture.h>

A weighted Student’s T or Gaussian distribution used as a component in a Mixture.

class MixturePrior : public lsst::meas::modelfit::Prior
#include <MixturePrior.h>

A prior that’s flat in amplitude parameters, and uses a Mixture for nonlinear parameters.

class MixtureUpdateRestriction
#include <Mixture.h>

Helper class used to define restrictions to the form of the component parameters in Mixture::updateEM.

The base class implementation does not apply any restrictions.

class Model
#include <Model.h>

Abstract base class and concrete factories that define multi-shapelet galaxy models.

A Model provides a mapping from its parameters to ellipses and to a realization using shapelet objects. A Model does not “hold” its parameters; parameters are always stored in separate arrays.

Model parameters are split into three categories: nonlinear, amplitudes, and fixed. These are described more fully in modelfitParameters.

A few private concrete subclasses of Model have been provided that will meet most needs; instances can be constructed via the make() and makeGaussian()

Subclassed by lsst::meas::modelfit::MultiModel

class MultiModel : public lsst::meas::modelfit::Model
#include <MultiModel.h>

A concrete Model class that simply concatenates several other Models.

class MultiShapeletPsfLikelihood : public lsst::meas::modelfit::Likelihood
#include <GeneralPsfFitter.h>

Likelihood object used to fit multishapelet models to PSF model images; mostly for internal use by GeneralPsfFitter.

class Optimizer
#include <optimizer.h>

A numerical optimizer customized for least-squares problems with Bayesian priors.

The algorithm used by Optimizer combines the Gauss-Newton approach of approximating the second-derivative (Hessian) matrix as the inner product of the Jacobian of the residuals, while maintaining a matrix of corrections to this to account for large residuals, which is updated using a symmetric rank-1 (SR1) secant formula. We assume the prior has analytic first and second derivatives, but use numerical derivatives to compute the Jacobian of the residuals at every step. A trust region approach is used to ensure global convergence.

We consider the function \(f(x)\) we wish to optimize to have two terms, which correspond to negative log likelihood ( \(\chi^2/2=\|r(x)|^2\), where \(r(x)\) is the vector of residuals at \(x\)) and negative log prior \(q(x)=-\ln P(x)\):

\[ f(x) = \frac{1}{2}\|r(x)\|^2 + q(x) \]
At each iteration \(k\), we expand \(f(x)\) in a Taylor series in \(s=x_{k+1}-x_{k}\):
\[ f(x) \approx m(s) = f(x_k) + g_k^T s + \frac{1}{2}s^T H_k s \]
where
\[ g_k \equiv \left.\frac{\partial f}{\partial x}\right|_{x_k} = J_k^T r_k + \nabla q_k;\quad\quad J_k \equiv \left.\frac{\partial r}{\partial x}\right|_{x_k} \]
\[ H_k = J_k^T J_k + \nabla^2 q_k + B_k \]
Here, \(B_k\) is the SR1 approximation term to the second derivative term:
\[ B_k \approx \sum_i \frac{\partial^2 r^{(i)}_k}{\partial x^2}r^{(i)}_k \]
which we initialize to zero and then update with the following formula:
\[ B_{k+1} = B_{k} + \frac{v v^T}{v^T s};\quad\quad v\equiv J^T_{k+1} r_{k+1} - J^T_k r_k \]
Unlike the more common rank-2 BFGS update formula, SR1 updates are not guaranteed to produce a positive definite Hessian. This can result in more accurate approximations of the Hessian (and hence more accurate covariance matrices), but it rules out line-search methods and the simple dog-leg approach to the trust region problem. As a result, we should require fewer steps to converge, but spend more time computing each step; this is ideal when we expect the time spent in function evaluation to dominate the time per step anyway.

class OptimizerControl
#include <optimizer.h>

Configuration object for Optimizer.

Many of these configuration options pertain to how the trust region is updated. It’s easiest to understand these together rather than separately. At each iteration, a quadratic model of the objective function is formed. We can use this model to predict how we expect the objective function to behave over a step, and compare it to how the actual objective function behaves. To do this, we’ll use the ratio of the actual reduction in the objective function to the predicted reduction in the objective function, and call this \(\rho\). Then,

  • the step is accepted, and the parameters updated, when \(\rho >\) stepAcceptThreshold.

  • if \(\rho > \) trustRegionGrowReductionRatio and the length of the step is greater than trustRegionGrowStepFraction times the current trust region radius, the trust region radius will be multiplied by trustRegionGrowFactor.

  • if trustRegionShrinkMinReductionRatio \(< \rho < \) trustRegionShrinkMaxReductionRatio, the trust region radius will be multiplied by trustRegionShrinkFactor.

class OptimizerObjective
#include <optimizer.h>

Base class for objective functions for Optimizer.

class Prior
#include <Prior.h>

Base class for Bayesian priors.

Subclassed by lsst::meas::modelfit::MixturePrior, lsst::meas::modelfit::SemiEmpiricalPrior, lsst::meas::modelfit::SoftenedLinearPrior

class Sampler

Subclassed by lsst::meas::modelfit::AdaptiveImportanceSampler

class SemiEmpiricalPrior : public lsst::meas::modelfit::Prior
#include <SemiEmpiricalPrior.h>

A piecewise prior motivated by both real distributions and practical considerations.

class SoftenedLinearPrior : public lsst::meas::modelfit::Prior
#include <SoftenedLinearPrior.h>

A prior that’s linear in radius and flat in ellipticity, with a cubic roll-off at the edges.

class TruncatedGaussian
#include <TruncatedGaussian.h>

Represents a multidimensional Gaussian function truncated at zero.

This is typically used to represent the posterior probability of amplitude parameters, given a flat prior; we require that the amplitudes each be positive but otherwise do not modify the Gaussian likelihood.

Currently only 1 and 2 dimensions are supported, and all dimensions must be truncated. Computing integrals is the only operation for which > 2-d is not implemented, but the integrals must be computed upon construction, so we can’t support any other operations for > 2-d either.

Many operations on TruncatedGaussians are defined in -log space, as underflow/overflow problems will often occur in the non-log forms.

See modelfitTruncatedGaussianMath for implementation notes

class TruncatedGaussianEvaluator
#include <TruncatedGaussian.h>

Helper class for evaluating the -log of a TruncatedGaussian.

class TruncatedGaussianLogEvaluator
#include <TruncatedGaussian.h>

Helper class for evaluating the -log of a TruncatedGaussian.

class TruncatedGaussianSampler
#include <TruncatedGaussian.h>

Helper class for drawing samples from a TruncatedGaussian.

struct UnitSystem
#include <UnitSystem.h>

A simple struct that combines a Wcs and a PhotoCalib.

class UnitTransformedLikelihood : public lsst::meas::modelfit::Likelihood
#include <UnitTransformedLikelihood.h>

A concrete Likelihood class that does not require its parameters and data to be in the same UnitSystem.

This is the main concrete Likelihood class using when fitting sources, even in the case where the measurement UnitSystem is the same as that of the data; we always prefer to fit in a special UnitSystem (see modelfitUnits), using this class to transform the model realization when comparing to the data. This makes forced photometry and modelfit measurements just as easy as single-frame measurements (aside from data access); one can simply initialize a UnitTransformedLikelihood with multiple exposures instead of a single exposure to fit simultaneously to multiple exposures.

class UnitTransformedLikelihoodControl
#include <UnitTransformedLikelihood.h>

Control object used to initialize a UnitTransformedLikelihood.

Translated to Python as UnitTransformedLikelihoodConfig; the Swig-wrapped C++ Control object can be created from the config object via the makeControl() method (see lsst.pex.config.wrap).

namespace detail

Functions

Eigen::Vector4d solveRampPoly(double v0, double v1, double x0, double x1, double s0, double s1)

Solve for the coefficients of a cubic polynomial p(x) that goes from p(x0)=v0 to p(x1)=v1, with p’(x0)=s0 and p’(x1)=s1.

double phid(double z)

Compute univariate normal probabilities.

This function computes

\[ \frac{1}{2\pi}\int_z^{\infty}dx\;e^{-x^2/(2z^2)} \]

This is just a simple wrapper around boost::math::erfc, used to provide the particular form expected by bvnu.

double bvnu(double h, double k, double rho)

Compute bivariate normal probabilities.

This function computes

\[ \frac{1}{2\pi\sqrt{1-\rho^2}}\int_h^{\infty}dx\int_k^{\infty}dy \;e^{-(x^2 - 2\rho x y + y^2)/(2(1-\rho^2))} \]

It is a reimplementation of the “bvnu” MatLab routine by Alan Genz. The original implementation can be found at http://www.math.wsu.edu/faculty/genz/homepage. It is based on the algorithm described in:

Drezner & Wesolowsky (1989), “On the computation of the bivariate normal integral”, Journal of Statist. Comput. Simul. 35, pp. 101-107.

A copy of Genz’s FORTRAN routine of the same is included in the tests directory, as it has been used to generate the test reference data there. It should generally not need to be compiled by users.

Most of the time, this function should be called via the methods in the TruncatedGaussian class; it is exposed publically only for testing purposes.

template<int N>
class Vandermonde
#include <polynomials.h>

Class that computes rows of the Vandermonde matrix and related matrices; the dot product of these row vectors with the polynomial coefficient vectors evaluates the polynomial (or computes a derivative).

namespace pex
namespace exceptions

Typedefs

typedef std::vector<Tracepoint> Traceback

Functions

std::ostream &operator<<(std::ostream &stream, Exception const &e)

Push the text representation of an exception onto a stream.

Return

Reference to the output stream after adding the text.

Parameters
  • [in] stream: Reference to an output stream.

  • [in] e: Exception to output.

LSST_EXCEPTION_TYPE(LogicError, Exception, lsst::pex::exceptions::LogicError)

Reports errors in the logical structure of the program.

LogicError and its subclasses should be thrown to represent problems, such as violation of logical preconditions or class invariants, that are in principle preventable using defensive programming or other good practices. In many cases, it may not be appropriate to catch them.

This exception should be reserved for mathematical operations that are defined on a limited range of inputs. InvalidParameterError is more appropriate for non-mathematical operations.

See

RuntimeError

See

std::logic_error Reports arguments outside the domain of an operation.

See

std::domain_error

lsst::pex::exceptions::DomainError LSST_EXCEPTION_TYPE(InvalidParameterError, LogicError, lsst::pex::exceptions::InvalidParameterError)

Reports invalid arguments.

This exception reports errors that arise because an argument value has not been accepted.

For example, some collection classes might not be able to handle more than some number of elements, or bit fields might support a limited number of flags.

See

std::invalid_argument Reports attempts to exceed implementation-defined length limits for some classes.

See

std::length_error

lsst::pex::exceptions::DomainError lsst::pex::exceptions::LengthError lsst::pex::exceptions::LSST_EXCEPTION_TYPE(OutOfRangeError, LogicError, lsst::pex::exceptions::OutOfRangeError)

Reports attempts to access elements outside a valid range of indices.

RuntimeError and its subclasses represent problems that cannot be easily predicted or prevented. In other words, a RuntimeError is a possible outcome of calling a function or method even in well-written programs, and should be handled at the appropriate level.

See

NotFoundError

See

std::out_of_range

Note

pybind11 wrappers should manually translate this exception to py::index_error when appropriate. Some Python language constructs check for exceptions that are exactly IndexError rather than a sub- or superclass. Reports errors that are due to events beyond the control of the program.

In Python, this exception inherits from builtins.RuntimeError.

See

LogicError

See

std::runtime_error

lsst::pex::exceptions::DomainError lsst::pex::exceptions::LengthError lsst::pex::exceptions::RuntimeError lsst::pex::exceptions::LSST_EXCEPTION_TYPE(RangeError, RuntimeError, lsst::pex::exceptions::RangeError)

Reports when the result of an operation cannot be represented by the destination type.

Situations covered by this exception include lossy type conversions.

In Python, this exception inherits from

builtins.OverflowError.
See

OverflowError

See

UnderflowError

See

std::range_error Reports when the result of an arithmetic operation is too large for the destination type.

See

std::overflow_error

lsst::pex::exceptions::DomainError lsst::pex::exceptions::LengthError lsst::pex::exceptions::RuntimeError lsst::pex::exceptions::OverflowError lsst::pex::exceptions::LSST_EXCEPTION_TYPE(UnderflowError, RuntimeError, lsst::pex::exceptions::UnderflowError)

Reports when the result of an arithmetic operation is too small for the destination type.

In Python, this exception inherits from builtins.ArithmeticError.

This exception may represent lookup failures in classes that resemble C++ maps or Python dictionaries, but it may also be used when the relationship between an identifier and a resource is more abstract.

See

std::underflow_error Reports attempts to access elements using an invalid key.

In Python, this exception inherits from builtins.LookupError.

See

OutOfRangeError

Note

pybind11 wrappers should manually translate this exception to py::key_error when appropriate. Some Python language constructs check for exceptions that are exactly KeyError rather than a sub- or superclass.

lsst::pex::exceptions::DomainError lsst::pex::exceptions::LengthError lsst::pex::exceptions::RuntimeError lsst::pex::exceptions::OverflowError lsst::pex::exceptions::NotFoundError lsst::pex::exceptions::LSST_EXCEPTION_TYPE(IoError, RuntimeError, lsst::pex::exceptions::IoError)

Reports errors in external input/output operations.

In Python, this exception inherits from builtins.IOError.

In Python, this exception inherits from

builtins.TypeError.
See

std::ios_base::failure Reports errors from accepting an object of an unexpected or inappropriate type.

Variables

lsst::pex::exceptions::DomainError lsst::pex::exceptions::LengthError lsst::pex::exceptions::RuntimeError lsst::pex::exceptions::OverflowError lsst::pex::exceptions::NotFoundError lsst::pex::exceptions::LogicError
lsst::pex::exceptions::DomainError lsst::pex::exceptions::LengthError lsst::pex::exceptions::RuntimeError lsst::pex::exceptions::OverflowError lsst::pex::exceptions::Exception
lsst::pex::exceptions::DomainError lsst::pex::exceptions::LengthError lsst::pex::exceptions::RuntimeError lsst::pex::exceptions::RuntimeError
class Exception : public exception
#include <Exception.h>

Provides consistent interface for LSST exceptions.

All exceptions defined by the LSST Stack are derived from this class. Code should not throw or catch Exception directly, but should instead be written in terms of the appropriate subclasses (e.g., catch RuntimeError to handle all unknown errors).

In Python, this exception inherits from builtins.Exception.

struct Tracepoint
#include <Exception.h>

One point in the Traceback vector held by Exception.

namespace python

Functions

template<typename T, typename E = lsst::pex::exceptions::Exception>
pybind11::class_<T, E> declareException(pybind11::module &mod, const std::string &name, const std::string &base)

Helper function for pybind11, used to define new types of exceptions.

While this function creates the class wrapper, the user is still responsible for adding all constructor and member wrappers to the returned py::class_ object.

Template Parameters
  • T: The C++ exception to wrap.

  • E: The C++ base class of T.

Parameters
  • [in] mod: Module to insert the exception into.

  • [in] name: Name of the exception in the module.

  • [in] base: Python name of base class (from pex::exceptions).

namespace shapelet

Typedefs

typedef afw::geom::ellipses::Quadrupole EllipseCore
typedef ndarray::Array<double, 1> Array1d

Typedef for a commonly-used array type.

Note

Serves as a workaround for ambiguities in the C++ standard itself: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#325

Enums

enum BasisTypeEnum

An enum that sets whether to use real-valued polar shapelets or Cartesian shapelets.

The conversion between the two bases is theoretically exact, but of course subject to round-off error here.

Values:

HERMITE

Cartesian shapelets or Gauss-Hermite functions, as defined in Refregier, 2003. That is, \( \psi(x, y)_{n_x, n_y} = \frac{H_{n_x}(x) H_{n_y}(y) e^{-\frac{x^2 + y^2}{2}}} {\sigma 2^{n_x + n_y} \sqrt{\pi n_x! n_y!}} \) where \(H_n(x)\) is a Hermite polynomial.

The ordering of coefficients [n_x, n_y] is (row-major packed): [0,0], [0,1], [1,0], [0,2], [1,1], [2,0], [0,3], [1,2], [2,1], [3,0], [0,4], [1,3], [2,2], [3,1], [4,0] etc.

LAGUERRE

Polar shapelets or Gauss-Laguerre functions, as defined in Bernstein and Jarvis, 2002. That is, \( \psi(x, y, \sigma)_{p, q} = (-1)^q \sqrt{\frac{q!}{p!}} (x + i y)^{p-q} e^{-\frac{x^2 + y^2}{2}} L^{(p-q)}_q(x^2 + y^2) \) where \(L^{(m)}_n(r)\) is an associated Laguerre polynomial.

The ordering of coefficients [p, q] is (row-major packed): [0,0], Re([1,0]), Im([1,0]), Re([2,0]), Im([2,0]), [1,1], Re([3,0]), Im([3,0], Re([2,1]), Im([2,1]), Re([4,0]), Im([4,0], Re([3,1]), Im([3,1]), [2,2] etc.

Elements with p < q are redundant in representing real-valued functions, while those with p == q are inherently real.

Functions

int computeOffset(int order)

Return the offset of the given order in a coefficient vector.

int computeSize(int order)

Return the size of the coefficient vector for the given order.

int computeOrder(int size)

Infer the order of a shapelet expansion from the number of coefficients.

Exceptions
  • InvalidParameterError: if the number of coefficients does not correspond to any shapelet order.

double intSqrt(int n)

Compute the square root of an integer number.

double rationalSqrt(int n, int d)

Compute the square root of a rational number i.e. sqrt(n/d)

Variables

double const BASIS_NORMALIZATION

Normalization factor for 1-d orthonormal shapelets: pi^(-1/4)

class BasisEvaluator
#include <BasisEvaluator.h>

Evaluates a standard shapelet Basis.

class ConversionMatrix
#include <ConversionMatrix.h>

Conversions between shapelet basis types.

The basis conversion matrix is block-diagonal and only needs to be computed once, so we cache the blocks in a hidden singleton and provide operations that act on shapelet matrices while taking advantage of the sparseness of the conversion.

class GaussHermiteConvolution
#include <GaussHermiteConvolution.h>

A parametrized matrix that performs a convolution in shapelet space.

GaussHermiteConvolution is defined only for the HERMITE basis type.

class GaussHermiteEvaluator
#include <GaussHermiteEvaluator.h>

A class to evaluate HERMITE shapelet-related quantities.

class HermiteTransformMatrix
#include <HermiteTransformMatrix.h>

A class that computes a matrix that applies a linear transform to a 2-d Hermite polynomial expansion.

Let

\[ Z_{\boldsymbol{n}}\!(\boldsymbol{x}) \equiv \mathcal{H}_{n_0}\!(x_0)\;\mathcal{H}_{n_1}\!(x_1) \]
where
\[ \mathcal{H}_n(x)=(2^n \pi^{1/2} n!)^{-1/2}H_n(x) \]
is the \(i\)th “alternate” Hermite polynomial. This function computes the matrix \(\boldsymbol{Q}(\boldsymbol{U})\) given a linear transform \(\boldsymbol{U}\) such that
\[ Z_{\boldsymbol{m}}\!(\boldsymbol{U}\boldsymbol{x}) = \sum_{\boldsymbol{n}} Q_{\boldsymbol{m},\boldsymbol{n}}\!(\boldsymbol{U})\,Z_{\boldsymbol{n}}\!(\boldsymbol{x}) \]

template<typename T>
class MatrixBuilder
#include <MatrixBuilder.h>

Class that evaluates a (multi-)shapelet basis at predefined points.

The output “matrix” has pixels along the rows, and basis elements along columns; this is the design matrix involved in a linear least squares fit for the basis coefficients.

A MatrixBuilder can be constructed in two ways: via one of its own constructors, or via a MatrixBuilderFactory. Using the latter allows the workspace arrays used by the MatrixBuilder to be shared between instances. See MatrixBuilderFactory and MatrixBuilderWorkspace for more information.

template<typename T>
class MatrixBuilderFactory
#include <MatrixBuilder.h>

A factory class for MatrixBuilder, providing more control over workspace memory.

To allocate workspace manually for a MatrixBuilder, we use the following pattern:;

MatrixBuilderFactory<T> factory(...);
MatrixBuilderWorkspace<T> workspace(factory.computeWorkspace());
MatrixBuilder<T> builder = factory(workspace);
Because we aren’t doing anything special with the workspace, however, this is actually exactly equivalent to just constructing the MatrixBuilder directly, i.e.:
MatrixBuilder<T> builder(...);

A more interesting case is if we want to use the same workspace for a pair of MatrixBuilders:

MatrixBuilderFactory<T> factory1(...);
MatrixBuilderFactory<T> factory2(...);
MatrixBuilderWorkspace<T> workspace1(
   std::max(factory1.computeWorkspace(), factory2.computeWorkspace())
);
MatrixBuilderWorkspace<T> workspace2(workspace1);
MatrixBuilder<T> builder1 = factory1(workspace1);
MatrixBuilder<T> builder2 = factory2(workspace2);

template<typename T>
class MatrixBuilderWorkspace
#include <MatrixBuilder.h>

Reusable, shareable workspace for MatrixBuilder.

Multiple MatrixBuilders are often used together to evaluate a multi-shapelet model, and in this case it’s more efficient for the MatrixBuilders to use the same memory for temporary arrays rather than have them each allocate their own workspace. At other times, it may be useful to use one workspace for a sequence of throwaway MatrixBuilders, to avoid unnecessary memory allocations. This class manages the memory used for a MatrixBuilder’s workspace arrays, and provides methods for tracking it and sharing it between multple MatrixBuilders. See MatrixBuilderFactory for examples.

MatrixBuilderWorkspace holds a ndarray::Manager::Ptr that “owns” the block of memory. This is passed on to any MatrixBuilders constructed with it, ensuring that the block of memory remains alive with the MatrixBuilder even if the workspace object goes out of scope - so it is not necessary to keep the workspace object alive manually for the duration of its users.

In addition, MatrixBuilderWorkspace tracks both the current point in memory, and increments this as workspace matrices and vectors are created from it. It also checks that any created arrays do not exceed the bounds of the allocated memory. In order to share workspace memory between MatrixBuilders, the workspace object is simply copied - copied objects share the same memory, but maintain different “current” pointers, and hence create arrays from the same block of memory.

class MultiShapeletBasis
#include <MultiShapeletBasis.h>

A basis formed from a linear combination of shapelet bases that differ only in radius.

A MultiShapeletBasis can have many “components” (shapelet bases with different orders and radii), which are mapped via matrices into one or more “elements”. It’s common for a basis to have only one or two elements, representing a galaxy model that is a linear combination of one or two radial profiles. It’s also common for most components to be zeroth order (Gaussians), as higher- order shapelet terms don’t provide much of an advantage when approximating axisymmetric functions.

MultiShapeletBasis itself provides the interface to define these multi-Gaussian approximations and combine and refine them, and delegates the work of defining them to MultiShapeletFunction (via the makeFunction() method) and the MultiShapeletMatrixBuilder class. MultiShapeletFunction is a more user-friendly and versatile approach, intended for debugging and testing, while the MultiShapletMatrixBuilder approach is intended for performance-critical evaluation of PSF-convolved MultiShapeletBasis objects.

class MultiShapeletBasisComponent
#include <MultiShapeletBasis.h>

Simple struct that represents one shapelet expansion in a MultiShapeletBasis.

A MultiShapeletBasis is formed by the linear combination of several shapelet bases with different radii and common ellipticity; this represents a single shapelet basis within the MultiShapeletBasis.

Note

This really ought to be an inner class, and should generally be referred to via the MultiShapeletBasis::Component typedef, but Swig doesn’t handle inner classes.

class MultiShapeletFunction
#include <MultiShapeletFunction.h>

A multi-scale shapelet function.

class MultiShapeletFunctionEvaluator
#include <MultiShapeletFunction.h>

Evaluates a MultiShapeletFunction.

This is distinct from MultiShapeletFunction to allow the evaluator to construct temporaries and allocate workspace that will be reused when evaluating at multiple points.

A MultiShapeletFunctionEvaluator is invalidated whenever the MultiShapeletFunction it was constructed from is modified.

class MultiShapeletFunctionKey : public lsst::afw::table::FunctorKey<MultiShapeletFunction>
#include <FunctorKeys.h>

Class that maps MultiShapeletFunction objects to fields in afw::table objects.

A MultiShapeletFunctionKey holds a sequnece of ShapeletFunctionKey, with an numerical prefix in front of each component. A two-component MultiShapeletFunctionKey would thus be associated with the following keys:

  • ”<prefix>_0_xx”

  • ”<prefix>_0_yy”

  • ”<prefix>_0_xy”

  • ”<prefix>_0_x”

  • ”<prefix>_0_y”

  • ”<prefix>_1_xx”

  • ”<prefix>_1_yy”

  • ”<prefix>_1_xy”

  • ”<prefix>_1_x”

  • ”<prefix>_1_y”

As with all FunctorKeys, a MultiShapeletFunctorKey can be used to directly get or set objects on an afw::table::BaseRecord, just as with a true Key.

class PackedIndex
#include <GaussHermiteEvaluator.h>

An iterator-like object to help in traversing “packed” shapelet or Hermite polynomial matrix or vector dimensions.

A pair of indices (x,y) is mapped to the packed position i = (x+y)(x+y+1)/2 + x.

Typical usage is in a nested loop of the form:

for (PackedIndex i; i.getOrder() <= order; ++i) {
    // utilize i
}

class RadialProfile
#include <RadialProfile.h>

Registry and utility class for multi-Gaussian approximations to radial profiles.

RadialProfile provides C++ access to the saved multi-Gaussian approximations stored in the pickle files in the data subdirectory of the shapelet package, by maintaining a singleton registry of these that is populated at import time by tractor.py. It also provides access to the true (exact) profiles, (mostly useful for educational/diagnostic purposes) and information about the relationship between different radii for this profile (see getMomentsRadiusFactor()).

Each RadialProfile object represents a particular “true” profile, and can hold multiple multi-Gaussian (or multi-Shapelet) approximations with different degrees of fidelity, as controlled by the number of components in the approximation and the maximum radius at which the approximation was fit. For more information about these approximations, see tractor.py and references therein. All RadialProfiles are defined in units of the half-light radius of the true profile, even for profiles for which this is not the radius typically used.

Several predefined subclasses of RadialProfile are defined privately, and can be accessed by name through the static get() method:

  • ”gaussian”: a single Gaussian profile

  • ”exp”: Exponential profile (Sersic n=1)

  • ”ser2”: Sersic profile with n=2

  • ”ser3”: Sersic profile with n=3

  • ”dev”: de Vaucouleur profile (Sersic n=4)

  • ”ser5”: Sersic profile with n=5

  • ”lux”: SDSS truncated Exponential profile

  • ”luv”: SDSS truncated and softened de Vaucouleur profile

class ShapeletFunction
#include <ShapeletFunction.h>

A 2-d function defined by an expansion onto a Gauss-Laguerre or Gauss-Hermite basis.

The coefficients are in units of flux, not surface brightness; increasing the area of the basis ellipse while leaving the coefficients unchanged will decrease the surface brightness by the ratio of the areas of the new and old ellipses. This convention is necessary to ensure that convolution with a delta function is sane. Because the BasisEvaluator class does not deal with ellipses, it is necessary to divide its output by R^2 to get the same result as a ShapeletFunctionEvaluator whose ellipse has determinant radius of R.

The coefficient normalization is not identical to that of a Gaussian, however; a zeroth-order ShapeletFunction with its only coefficient value set to 1 has a flux of 2.0 * pi^(1/2). This value is defined as ShapeletFunction::FLUX_FACTOR. Of course, to get the flux of a more complex shapelet expansion you have to use ShapeletFunctionEvaluator::integrate().

Note that the units of the coefficients would have to be radius for basis functions with the same ellipse to be orthonormal, but this orthonormality isn’t very useful, because the basis functions aren’t even orthogonal in the more common case that the ellipses differ. However, basis functions defined on the unit circle are still orthonormal.

class ShapeletFunctionEvaluator
#include <ShapeletFunction.h>

Evaluates a ShapeletFunction.

This is distinct from ShapeletFunction to allow the evaluator to construct temporaries and allocate workspace that will be reused when evaluating at multiple points.

A ShapeletFunctionEvaluator is invalidated whenever the ShapeletFunction it was constructed from is modified.

class ShapeletFunctionKey : public lsst::afw::table::FunctorKey<ShapeletFunction>
#include <FunctorKeys.h>

Class that maps ShapeletFunction objects to fields in afw::table objects.

A ShapeletFunctionKey manages a set of fields with a common prefix and the following suffixes:

  • ”x”, “y”, “xx”, “yy”, “xy”: ellipse

  • ”0”, “1”, “2”, …: coefficients.

As with all FunctorKeys, a ShapeletFunctorKey can be used to directly get or set objects on an afw::table::BaseRecord, just as with a true Key.

namespace utils

Functions

std::string demangleType(std::string const _typeName)
std::size_t hashCombine(std::size_t seed)

Combine hashes

A specialization of hashCombine for a trivial argument list.

template<typename T, typename ...Rest>
std::size_t hashCombine(std::size_t seed, const T &value, Rest... rest)

Combine hashes

This is provided as a convenience for those who need to hash a composite. C++11 includes std::hash, but neglects to include a facility for combining hashes.

Shall not throw exceptions.

Return

A combined hash for all the arguments after seed.

Template Parameters
  • TRest: the types to hash. All types must have a valid (in particular, non-throwing) specialization of std::hash.

Parameters
  • seed: An arbitrary starting value.

  • valuerest: The objects to hash.

To use it:

// Arbitrary seed; can change to get different hashes of same argument list
std::size_t seed = 0;
result = hashCombine(seed, obj1, obj2, obj3);

template<typename InputIterator>
std::size_t hashIterable(std::size_t seed, InputIterator begin, InputIterator end)

Combine hashes in an iterable.

This is provided as a convenience for those who need to hash a container.

Shall not throw exceptions.

Return

A combined hash for all the elements in [begin, end).

Template Parameters
  • InputIterator: an iterator to the objects to be hashed. The pointed-to type must have a valid (in particular, non-throwing) specialization of std::hash.

Parameters
  • seed: An arbitrary starting value.

  • beginend: The range to hash.

To use it:

// Arbitrary seed; can change to get different hashes of same argument list
std::size_t seed = 0;
result = hashIterable(seed, container.begin(), container.end());

double nanojanskyToABMagnitude(double flux)

Convert a flux in nanojansky to AB magnitude.

double ABMagnitudeToNanojansky(double magnitude)

Convert an AB magnitude to a flux in nanojansky.

std::string getPackageDir(std::string const &packageName)

return the root directory of a setup package

Parameters
  • [in] packageName: name of package (e.g. “utils”)

Exceptions
  • lsst::pex::exceptions::NotFoundError: if desired version can’t be found

template<typename T>
constexpr void assertValidHash()

Compile-time test of whether a specialization of std::hash conforms to the general spec.

The function itself is a no-op.

Template Parameters
  • T: The properties of std::hash<T> will be tested.

template<typename T>
void assertHashesEqual(T obj1, T obj2)

Test that equal objects have equal hashes.

If objects of type T can be equal despite having different internal representations, you should include pairs of such objects.

Template Parameters
  • T: A hashable type.

Parameters
  • obj1obj2: Two equal objects.

Variables

const double referenceFlux = 1e23 * pow(10, ) * 1e9

The Oke & Gunn (1983) AB magnitude reference flux, in nJy (often approximated as 3631.0).

class Backtrace
#include <Backtrace.h>

Singleton, enables automatic backtraces on the following signals:

  • SIGABRT

  • SIGSEGV

  • SIGILL

  • SIGFPE

Note

Uses low level malloc and fprintf since higher level constructs may not be available when a signal is received.

template<typename Key, typename Value, typename KeyHash, typename KeyPred>
class Cache
#include <Cache.h>

Cache of most recently used values

This object stores the most recent maxElements values, where maxElements is set in the constructor. Objects (of type Value) are stored by a key (of type Key; hence the need to provide a KeyHash and KeyPred), and the class presents a dict-like interface. Objects may be added to (add) and retrieved from (operator[]) the cache. For ease of use, an interface (operator()) is also provided that will check the cache for an existing key, and if the key is not present, generate it with a function provided by the user.

Note

Value and Key must be copyable.

Note

This header (Cache.h) should generally only be included in source files, not other header files, because you probably don’t want all of the boost::multi_index includes in your header. We suggest you se the CacheFwd.h file in your header instead, and hold the Cache as a std::unique_ptr.

Note

Python bindings (for pybind11) are available in lsst/utils/python/Cache.h.

namespace python

Functions

template<typename Key, typename Value, typename KeyHash = boost::hash<Key>, typename KeyPred = std::equal_to<Key>>
void declareCache(py::module &mod, std::string const &name)
template<typename T, typename PyClass>
void addSharedPtrEquality(PyClass &cls)

Add __eq__ and __ne__ methods based on two std::shared_ptr<T> pointing to the same address

Example:

Template Parameters
  • T: The type to which the std::shared_ptr points.

  • PyClass: The pybind11 class_ type; this can be automatically deduced.

lsst::afw::table records are considered equal if two std::shared_ptr<record> point to the same record. This is wrapped as follows for lsst::afw::table::BaseRecord, where cls is an instance of pybind11::class_<BaseRecord, std::shared_ptr<BaseRecord>>):

utils::addSharedPtrEquality<BaseRecord>(cls);

Note that all record subclasses inherit this behavior without needing to call this function.

template<class PyClass>
void addOutputOp(PyClass &cls, std::string const &method)

Add __str__ or __repr__ method implemented by operator<<.

For flexibility, this method can be used to define one or both of __str__ and __repr__. It can also be used to define any Python method that takes no arguments and returns a string, regardless of name.

Template Parameters
  • PyClass: The pybind11 class_ type. The wrapped class must support << as a stream output operator.

Parameters
  • cls: The PyClass object to which to add a wrapper.

  • method: The name of the method to implement. Should be "__str__" or "__repr__".

template<class PyClass>
void addHash(PyClass &cls)

Add __hash__ method implemented by std::hash.

Template Parameters
  • PyClass: The pybind11 class_ type. The wrapped class must have an enabled specialization of std::hash.

Parameters
  • cls: The PyClass object to which to add a wrapper.

std::size_t cppIndex(std::ptrdiff_t size, std::ptrdiff_t i)

Compute a C++ index from a Python index (negative values count from the end) and range-check.

Return

index in the range [0, size - 1]

Note

the size argument has type std::ptrdiff_t instead of std::size_t in order to to match the allowed range for the i argument.

Parameters
  • [in] size: Number of elements in the collection.

  • [in] i: Index into the collection; negative values count from the end

Exceptions
  • Python: IndexError if i not in range [-size, size - 1]

std::pair<std::size_t, std::size_t> cppIndex(std::ptrdiff_t size_i, std::ptrdiff_t size_j, std::ptrdiff_t i, std::ptrdiff_t j)

Compute a pair of C++ indices from a pair of Python indices (negative values count from the end) and range-check.

Return

a std::pair of indices, each in the range [0, size - 1]

Parameters
  • [in] size_i: Number of elements along the first axis.

  • [in] size_j: Number of elements along the second axis.

  • [in] i: Index along first axis; negative values count from the end

  • [in] j: Index along second axis; negative values count from the end

Exceptions
  • Python: IndexError if either input index not in range [-size, size - 1]

template<typename T>
class PySharedPtr
#include <PySharedPtr.h>

A shared pointer that tracks both a C++ object and its associated PyObject.

Each group of PySharedPtr for a given object collectively counts as one reference to that object for the purpose of Python garbage collection.

A PySharedPtr is implicitly convertible to and from a std::shared_ptr to minimize API impact. Any shared_ptr created this way will (I think) keep the Python reference alive, as described above.

class TemplateInvoker
#include <TemplateInvoker.h>

A helper class for wrapping C++ template functions as Python functions with dtype arguments.

TemplateInvoker takes a templated callable object, a pybind11::dtype object, and a sequence of supported C++ types via its nested Tag struct. The callable is invoked with a scalar argument of the type matching the dtype object. If none of the supported C++ types match, a different error callback is invoked instead.

As an example, we’ll wrap this function:

template <typename T>
T doSomething(std::string const & argument);

TemplateInvoker provides a default error callback, which we’ll use here (otherwise you’d need to pass one when constructing the TemplateInvoker).

For the main callback, we’ll define this helper struct:

struct DoSomethingHelper {

    template <typename T>
    T operator()(T) const {
        return doSomething<T>(argument);
    }

    std::string argument;
};

The pybind11 wrapper for doSomething is then another lambda that uses TemplateInvoker::apply to call the helper:

mod.def(
    "doSomething",
    [](std::string const & argument, py::dtype const & dtype) {
        return TemplateInvoker().apply(
            DoSomethingHelper{argument},
            dtype,
            TemplateInvoker::Tag<int, float, double>()
        );
    },
    "argument"_a
);

The type returned by the helper callable’s operator() can be anything pybind11 knows how to convert to Python.

While defining a full struct with a templated operator() makes it more obvious what TemplateInvoker is doing, it’s much more concise to use a universal lambda with the decltype operator. This wrapper is equivalent to the one above, but it doesn’t need DoSomethingHelper:

mod.def(
    "doSomething",
    [](std::string const & argument, py::dtype const & dtype) {
        return TemplateInvoker().apply(
            [&argument](auto t) { return doSomething<decltype(t)>(argument); },
            dtype,
            TemplateInvoker::Tag<int, float, double>()
        );
    },
    "argument"_a
);
Note that the value of t here doesn’t matter; what’s important is that its C++ type corresponds to the type passed in the dtype argument. So instead of using that value, we use the decltype operator to extract that type and use it as a template parameter.

class WrapperCollection
#include <python.h>

A helper class for subdividing pybind11 module across multiple translation units (i.e. source files).

Merging wrappers for different classes into a single compiled module can dramatically decrease the total size of the binary, but putting the source for multiple wrappers into a single file slows down incremental rebuilds and makes editing unwieldy. The right approach is to define wrappers in different source files and link them into a single module at build time. In simple cases, that’s quite straightforward: pybind11 declarations are just regular C++ statements, and you can factor them out into different functions in different source files.

That approach doesn’t work so well when the classes being wrapped are interdependent, because bindings are only guaranteed to work when all types used in a wrapped method signature have been declared to pybind11 before the method using them is itself declared. Naively, then, each source file would thus have to have multiple wrapper-declaring functions, so all type-wrapping functions could be executed before any method-wrapping functions. Of course, each type-wrapping function would also have to pass its type object to at least one method-wrapping function (to wrap the types own methods), and the result is a tangled mess of wrapper-declaring functions that obfuscate the code with a lot of boilerplate.

WrapperCollection provides a way out of that by allowing type wrappers and their associated methods to be declared at a single point, but the method wrappers wrapped in a lambda to defer their execution. A single WrapperCollection instance is typically constructed at the beginning of a PYBIND11_MODULE block, then passed by reference to wrapper-declaring functions defined in other source files. As type and method wrappers are added to the WrapperCollection by those functions, the types are registered immediately, and the method-wrapping lambdas are collected. After all wrapper-declaring functions have been called, finish() is called at the end of the PYBIND11_MODULE block to execute the collecting method-wrapping lambdas.

Typical usage:

// _mypackage.cc

void wrapClassA(WrapperCollection & wrappers);
void wrapClassB(WrapperCollection & wrappers);

PYBIND11_MODULE(_mypackage, module) {
    WrapperCollection wrappers(module, "mypackage");
    wrapClassA(wrappers);
    wrapClassB(wrappers);
    wrappers.finish();
}
// _ClassA.cc

void wrapClassA(WrapperCollection & wrappers) {
    wrappers.wrapType(
        py::class_<ClassA>(wrappers.module, "ClassA"),
        [](auto & mod, auto & cls) {
            cls.def("methodOnClassA", &methodOnClassA);
        }
    );
}
// _ClassB.cc

void wrapClassB(WrapperCollection & wrappers) {
    wrappers.wrapType(
        py::class_<ClassB>(wrappers.module, "ClassB"),
        [](auto & mod, auto & cls) {
            cls.def("methodOnClassB", &methodOnClassB);
            mod.def("freeFunction", &freeFunction);
        }
    );
}

Note that we recommend the use of universal lambdas (i.e. auto & parameters) to reduce verbosity.