Skip to content
demitriPublic

About

Adding WCS functionality via the Starlink AST library natively to PostgreSQL.

Resources

Stars

0 stars

Watchers

2 watching

Forks

Latest commit

 

History

76 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

pgAST

The Starlink AST library as a PostgreSQL plug-in.

Author: Demitri Muna

pgAST is a PostgreSQL plug-in that implements some functionality from the Starlink AST, a library for handling world coordinate systems (WCS) in astronomy. This plug-in provides an interface between WCS and region-related functionality and data available in databases containing astronomical data. Rather than pull data down to a client to perform astronomy-related calculations, these can be performed at the server to reduce the need of transferring data and provide more application-specific filters in queries.

Only a few functions are currently defined; more will be added over time. This project provides a straightforward means of extending the functionality of the powerful and well-tested AST library into a database.

Building and Installing the Extension

Building pgAST requires the Starlink AST Library to be installed. Note the path where this is installed to use for the make command (i.e. replace /usr/local/ast below with your location).

From the src directory:

make clean; make AST=/usr/local/ast
sudo make install

Then from psql:

DROP EXTENSION pgast;
CREATE EXTENSION pgast;

pgAST requires AST 9.5.0 or later; the build stops with an error against an older version.

Running the Tests

From the repository root:

AST=/usr/local/ast scripts/run_tests.sh

The script builds the extension, installs it into a temporary staging directory, starts a throwaway PostgreSQL cluster that loads it from there, and runs the pg_regress tests in src/test/. Nothing is installed into PostgreSQL itself, so no root access is needed. It requires PostgreSQL 18 or later; set PG_CONFIG=/path/to/pg_config to choose which installation to use. Against an installed extension, make installcheck (from src) runs the same tests.

Documentation & API

Data Types

Note that many of these functions accept and return native PostgreSQL geometric types (i.e. not PostGIS), such as Circles, Polygons, and Points. A reference of geometric functions supported by the database for use with these objects can be found here.

All geometries are on the celestial sphere and in the ICRS coordinate frame unless otherwise noted. Points of a polygon are connected by great circle segments.

Vertex order matters. Following AST (and the IVOA STC convention), the inside of a polygon is the region to the left of its edges as the vertices are traversed in order, seen from inside the celestial sphere, where east is to the left when north is up. Polygons returned by pgast_bounding_polygon follow this. A polygon whose vertices run the other way describes the rest of the sky: for example ((149.99,1.99),(150.01,1.99),(150.01,2.01),(149.99,2.01)) does not contain (150, 2), while the same box listed as ((150.01,1.99),(149.99,1.99),(149.99,2.01),(150.01,2.01)) does.

PostgreSQL's own geometric operators (&&, @>, box(polygon), ...) work on these polygons but are planar in (RA, Dec), not spherical: they are wrong for polygons that cross RA = 0 or contain a pole. Use the pgAST functions for tests on the sky.

Known limitation: pgast_point_in_polygon can report the near-exact antipode of a small polygon (the point on the opposite side of the sky) as inside it. This comes from the AST library's point-in-polygon test; points even a fraction of a degree away are classified correctly.

API

The functions defined by this extension are:

pgast_bounding_circle(polygon poly)
pgast_bounding_circle(text fits_header_as_string)
pgast_bounding_polygon(text fits_header_as_string)
pgast_point_in_polygon(float8 ra, float8 dec, polygon poly)
pgast_point_in_polygon(float8 ra, float8 dec, text fits_header_string)
pgast_icrs_polygon_overlaps_hdu(polygon icrs_polygon, text fits_header_as_string)
pgast_cutout(text fits_header_as_string, float8 ra, float8 dec, float8 side_length_arcsec)

Errors

pgAST raises errors with standard PostgreSQL SQLSTATE codes, so they can be caught by name (e.g. EXCEPTION WHEN invalid_parameter_value in PL/pgSQL):

SQLSTATE Name When
22023 invalid_parameter_value The input cannot be used: an unreadable or unsuitable FITS header or WCS, a position or box beyond where the WCS is defined, a polygon AST cannot build, a region with no bounding circle.
XX000 internal_error The AST library failed on input that should have worked.

When the error comes from the AST library, the error's DETAIL carries AST's own message (for example, astRead(FitsChan): FITS keyword 'CTYPE1' refers to an unknown projection type '-QQQ'.). An error aborts the whole statement, including a query over many rows.

pgast_bounding_circle

Returns a bounding circle of a 2D image or a polygon.

This function has two signatures; it accepts a text value of a FITS header or a PostgreSQL Polygon object. The circle is the AST library's approximation: it encloses the region but is not always the smallest such circle, and for wide polygons it can depend on which vertex is listed first. An error is raised for a region on the far side of its boundary, for which AST gives no enclosing circle: a footprint larger than half the sky, or a polygon whose vertex order describes the rest of the sky.

pgast_bounding_circle(polygon)
pgast_bounding_circle(fits_header_as_string)

The return value is a native PostgreSQL Circle record.

The FITS header must be provided as a single string, i.e. each 80 character record concatenated. Only the header records that define the WCS and pixel dimensions of the image are necessary, but it's usually easier to pass in the full header. The header as a string can be stored in the database in another column or concatenated using another function. The circle center point is defined as (ra,dec) and the radius is in degrees.

Values of the circle can be read as:

-- radius in degrees
SELECT RADIUS(pgast_bounding_circle(fits_header_as_string)) FROM ...
-- return the center of the circle (Point object) as ra,dec
SELECT POINT(pgast_bounding_circle(fits_header_as_string)) FROM ...

pgast_bounding_polygon

Return a polygon that describes the perimeter of a 2D FITS image.

The return value is a native PostgreSQL Polygon record.

pgast_bounding_polygon(text fits_header_as_string)

pgast_point_in_polygon

Test whether an (ra,dec) point is within a given polygon.

Returns true or false. The function comes in two forms. The first takes the ra,dec point along with a PostgreSQL polygon:

pgast_point_in_polygon(float8 ra, float8 dec, polygon poly)

The second takes the full FITS header as a single string and extracts a polygon (if it can) from that:

pgast_point_in_polygon(float8 ra, float8 dec, text fits_header_string)

pgast_icrs_polygon_overlaps_hdu

Test whether two polygons on the sky overlap.

This function takes a PostgreSQL polygon, assumed to be in the ICRS coordinate system in degrees, and compares it to a polygon derived from the FITS header of a 2D image HDU. The FITS header provided is not required to also be in the ICRS coordinate system — the underlying AST code will perform any necessary transformation.

NULL is returned if the FITS header is not of a 2D image with axis lengths at least 2. An error is raised if a WCS with a sky frame cannot be read from the header, if the WCS does not map the image's centre pixel to the sky, if neither vertex order of the image boundary gives a polygon that contains the centre pixel (a WCS that is not well behaved over the image), or if AST cannot compare the two regions. Footprints larger than half the sky are supported.

pgast_icrs_polygon_overlaps_hdu(polygon icrs_polygon, text fits_header_as_string)

pgast_cutout

Return the polygon of a square cutout of a 2D image.
pgast_cutout(text fits_header_as_string, float8 ra, float8 dec, float8 side_length_arcsec)

Returns a four-vertex polygon around (ra, dec), in ICRS degrees, aligned with the image's pixel grid. The position is moved to the centre of the pixel that contains it, and the box is grown to whole pixels, so it is at least side_length_arcsec on each side. NULL is returned, with a WARNING, if the position is outside the image and has no pixel coordinates. An error is raised if the box extends beyond the region where the WCS is defined (for example past the limb of a SIN projection).

pgast_distance

Calculate distance between two points on a sphere.

This function takes two points x0,y0 and x1,y1 and calculates the angular distance between them along a great circle. Both input and output values are in degrees. This function has three signatures:

pgast_distance(x0_deg double precision, y0_deg double precision,
               x1_deg double precision, y1_deg double precision);
pgast_distance(x0_deg double precision, y0_deg double precision, p point);
pgast_distance(p1 point, p2 point);

Developer Notes

This section is intended for those who are interested in working with the source code.

Debugging

Log messages can be placed in the C code. Each message should specify a log level, one of:

DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1,
LOG, NOTICE, WARNING, ERROR

These are in descending order of verbosity. Use the ereport function to send a log message, specifying the log level (first parameter):

ereport(NOTICE, (errmsg("Log message here.")));

This above is an abbreviated version of the more verbose method, which specifies an error code:

ereport(NOTICE,
	    (
	     errcode(ERRCODE_ARRAY_ELEMENT_ERROR),
		 (errmsg("Header:\n"))
		)
		);

And for an even longer version:

ereport(ERROR,
            (
             errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
             errmsg("negative values are not allowed"),
             errdetail("value %d is negative", arg),
             errhint("make it positive")
            )
        );

See this blog post for more detail.

The settings in postgresql.conf determines which level of log messages are sent to the client and/or the server log. The details can be found here.

For example, to view DEBUG1 messages and higher (less verbose) in the client (e.g. psql), place this line in postgresql.conf and restart the server:

set client_min_messages = debug1

or to see messages in just the client session:

SET client_min_messages TO 'DEBUG1';

Useful Reference

  • PostgreSQL Server Programming, Second Edition (2015), Chapter 9. Writing Advanced Functions in C

About

Adding WCS functionality via the Starlink AST library natively to PostgreSQL.

Resources

Stars

0 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages