8 #include "lsst/pex/exceptions.h"
26 if (name ==
"HCOMPRESS")
throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
27 "HCOMPRESS is unsupported");
29 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
"Unrecognised compression algorithm: " + name);
41 std::ostringstream os;
42 os <<
"Unrecognized compression algorithm: " << algorithm;
43 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, os.str());
55 case HCOMPRESS_1:
throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
56 "Unsupported compression algorithm: HCOMPRESS_1");
58 std::ostringstream os;
59 os <<
"Unrecognized cfitsio compression: " << cfitsio;
60 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, os.str());
73 std::ostringstream os;
74 os <<
"Unrecognized compression algorithm: " << algorithm;
75 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, os.str());
84 ) : algorithm(algorithm_), tiles(ndarray::allocate(MAX_COMPRESS_DIM)), quantizeLevel(quantizeLevel_) {
87 for (
int ii = 2; ii < MAX_COMPRESS_DIM; ++ii)
tiles[ii] = 1;
98 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
"Unrecognized scaling algorithm: " + name);
111 std::ostringstream os;
112 os <<
"Unrecognized scaling algorithm: " << algorithm;
113 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, os.str());
121 std::vector<std::string>
const& maskPlanes_,
123 float quantizeLevel_,
128 ) : algorithm(algorithm_), bitpix(bitpix_), fuzz(fuzz_),
129 seed(std::abs(seed_ - 1) % (N_RANDOM - 1) + 1),
130 maskPlanes(maskPlanes_),
131 quantizeLevel(quantizeLevel_), quantizePad(quantizePad_),
132 bscale(bscale_), bzero(bzero_) {}
138 template <
typename T,
int N>
139 std::pair<T, T> calculateMedianStdev(
140 ndarray::Array<T const, N, N>
const&
image,
141 ndarray::Array<bool, N, N>
const&
mask
144 auto const& flatMask = ndarray::flatten<1>(
mask);
145 for (
auto mm = flatMask.begin(); mm != flatMask.end(); ++mm) {
148 ndarray::Array<T, 1, 1> array = ndarray::allocate(num);
149 auto const& flatImage = ndarray::flatten<1>(
image);
150 auto mm = ndarray::flatten<1>(
mask).begin();
151 auto aa = array.begin();
152 for (
auto ii = flatImage.begin(); ii != flatImage.end(); ++ii, ++mm) {
159 auto const q1 = num/4;
160 auto const q2 = num/2;
161 auto const q3 = q1 + q2;
162 std::nth_element(array.begin(), array.begin() + q1, array.end());
163 std::nth_element(array.begin() + q1 + 1, array.begin() + q2, array.end());
164 std::nth_element(array.begin() + q2 + 1, array.begin() + q3, array.end());
166 T
const median = num % 2 ? array[num/2] : 0.5*(array[num/2] + array[num/2 - 1]);
169 T
const lq = array[q1];
170 T
const uq = array[q3];
171 return std::make_pair(median, 0.741*(uq - lq));
175 template <
typename T,
int N>
176 std::pair<T, T> calculateMinMax(
177 ndarray::Array<T const, N, N>
const& image,
178 ndarray::Array<bool, N, N>
const& mask
181 auto mm = ndarray::flatten<1>(
mask).begin();
182 auto const& flatImage = ndarray::flatten<1>(
image);
183 for (
auto ii = flatImage.begin(); ii != flatImage.end(); ++ii, ++mm) {
185 if (!std::isfinite(*ii))
continue;
187 if (*ii < min) min = *ii;
189 return std::make_pair(min,
max);
193 template <
typename T>
194 double rangeForBitpix(
int bitpix,
bool cfitsioPadding) {
196 bitpix = detail::Bitpix<T>::value;
198 double range = std::pow(2.0, bitpix) - 1;
199 if (cfitsioPadding) {
207 template <
typename T,
int N>
208 ImageScale ImageScalingOptions::determineFromRange(
209 ndarray::Array<T const, N, N>
const& image,
210 ndarray::Array<bool, N, N>
const& mask,
214 auto minMax = calculateMinMax(image, mask);
215 T
const min = minMax.first;
216 T
const max = minMax.second;
217 if (min == max)
return ImageScale(bitpix, 1.0, min);
218 double range = rangeForBitpix<T>(
bitpix, cfitsioPadding);
220 double const bscale =
static_cast<T
>((max -
min)/range);
221 double bzero =
static_cast<T
>(isUnsigned ? min : min + 0.5*range*
bscale);
222 if (cfitsioPadding) {
226 return ImageScale(bitpix, bscale, bzero);
229 template <
typename T,
int N>
230 ImageScale ImageScalingOptions::determineFromStdev(
231 ndarray::Array<T const, N, N>
const& image,
232 ndarray::Array<bool, N, N>
const& mask,
236 auto stats = calculateMedianStdev(image, mask);
237 auto const median = stats.first, stdev = stats.second;
241 auto minMax = calculateMinMax(image, mask);
242 T
const min = minMax.first;
243 T
const max = minMax.second;
244 double range = rangeForBitpix<T>(
bitpix, cfitsioPadding);
245 double const numUnique = (max -
min)/bscale;
249 if (numUnique < range) {
257 diskVal = (bitpix == 8) ? 0 : - (1L << (bitpix - 1));
263 diskVal = (bitpix == 8) ? 255 : (1L << (bitpix - 1)) - 1;
275 double bzero =
static_cast<T
>(imageVal - bscale*diskVal);
276 return ImageScale(bitpix, bscale, bzero);
280 template <
typename T,
class Enable=
void>
282 static double constexpr
value = 0.0;
290 static double constexpr
value = 0.0;
294 template <
typename T>
295 struct Bzero<T, typename std::enable_if<std::numeric_limits<T>::is_integer &&
296 !std::numeric_limits<T>::is_signed>::type> {
301 template <
typename T,
int N>
303 ndarray::Array<T const, N, N>
const& image,
304 ndarray::Array<bool, N, N>
const& mask
308 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
309 "Image scaling not supported for integral types");
311 bool const isUnsigned = bitpix == 8 || (bitpix == 0 && detail::Bitpix<T>::value == 8);
312 bool const cfitsioPadding = !std::numeric_limits<T>::is_integer && bitpix == 32;
314 case NONE:
return ImageScale(detail::Bitpix<T>::value, 1.0, Bzero<T>::value);
315 case RANGE:
return determineFromRange(image, mask, isUnsigned, cfitsioPadding);
316 case MANUAL:
return ImageScale(bitpix, bscale, bzero);
320 return determineFromStdev(image, mask, isUnsigned, cfitsioPadding);
332 class CfitsioRandom {
335 CfitsioRandom(
int seed) :
_seed(seed) {
336 assert(seed != 0 && seed < N_RANDOM);
342 void resetForTile(
int iTile) {
367 template <
typename T>
368 ndarray::Array<T, 1, 1> forImage(
369 typename ndarray::Array<T const, 2, 2>::Index
const& shape,
370 ndarray::Array<long, 1>
const& tiles
372 std::size_t
const xSize = shape[1], ySize = shape[0];
373 ndarray::Array<T, 1, 1> out = ndarray::allocate(xSize*ySize);
374 std::size_t
const xTileSize = tiles[0] <= 0 ? xSize : tiles[0];
375 std::size_t
const yTileSize = tiles[1] < 0 ? ySize : (tiles[1] == 0 ? 1 : tiles[1]);
376 int const xNumTiles =
std::ceil(xSize/static_cast<float>(xTileSize));
377 int const yNumTiles =
std::ceil(ySize/static_cast<float>(yTileSize));
378 for (
int iTile = 0, yTile = 0; yTile < yNumTiles; ++yTile) {
379 int const yStart = yTile*yTileSize;
380 int const yStop =
std::min(yStart + yTileSize, ySize);
381 for (
int xTile = 0; xTile < xNumTiles; ++xTile, ++iTile) {
382 int const xStart = xTile*xTileSize;
383 int const xStop =
std::min(xStart + xTileSize, xSize);
385 for (
int y = yStart; y < yStop; ++y) {
386 auto iter = out.begin() + y*xSize + xStart;
387 for (
int x = xStart;
x < xStop; ++
x, ++iter) {
388 *iter =
static_cast<T
>(getNext());
410 template <
typename T>
412 ndarray::Array<T const, 2, 2>
const& image,
413 bool forceNonfiniteRemoval,
415 ndarray::Array<long, 1>
const& tiles,
418 if (!std::numeric_limits<T>::is_integer && bitpix < 0) {
420 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
421 "Floating-point images may not be converted to different floating-point types");
423 if (bscale != 1.0 || bzero != 0.0) {
424 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
425 "Scaling may not be applied to floating-point images");
429 if (bitpix < 0 || (bitpix == 0 && !std::numeric_limits<T>::is_integer) ||
430 (bscale == 1.0 && bzero == 0.0 && !fuzz)) {
431 if (!forceNonfiniteRemoval) {
435 if (!std::numeric_limits<T>::is_integer) {
436 ndarray::Array<T, 1, 1> out = ndarray::allocate(image.getNumElements());
437 auto outIter = out.begin();
438 auto const& flatImage = ndarray::flatten<1>(
image);
439 for (
auto inIter = flatImage.begin(); inIter != flatImage.end(); ++inIter, ++outIter) {
448 double min = bitpix == 8 ? 0 : -std::pow(2.0, bitpix - 1);
449 double max = bitpix == 8 ? 255 : (std::pow(2.0, bitpix - 1) - 1.0);
451 if (!std::numeric_limits<T>::is_integer && bitpix == 32) {
457 std::size_t
const num = image.getNumElements();
458 bool const applyFuzz = fuzz && !std::numeric_limits<T>::is_integer && bitpix > 0;
459 ndarray::Array<double, 1, 1> out;
461 if (tiles.isEmpty()) {
462 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
463 "Tile sizes must be provided if fuzzing is desired");
465 out = CfitsioRandom(seed).forImage<
double>(image.getShape(), tiles);
467 out = ndarray::allocate(num);
469 auto outIter = out.begin();
470 auto const& flatImage = ndarray::flatten<1>(
image);
471 for (
auto inIter = flatImage.begin(); inIter != flatImage.end(); ++inIter, ++outIter) {
472 double value = (*inIter -
bzero)*scale;
473 if (!std::isfinite(value)) {
484 *outIter = (value < min ? blank : (value > max ?
blank :
std::floor(value)));
490 template <
typename T>
492 ndarray::Array<T, 2, 2> memory = ndarray::allocate(image.getShape());
493 memory.deep() = bscale*image +
bzero;
499 #define INSTANTIATE(TYPE) \
500 template ImageScale ImageScalingOptions::determine<TYPE, 2>( \
501 ndarray::Array<TYPE const, 2, 2> const& image, ndarray::Array<bool, 2, 2> const& mask) const; \
502 template std::shared_ptr<detail::PixelArrayBase> ImageScale::toFits<TYPE>( \
503 ndarray::Array<TYPE const, 2, 2> const&, bool, bool, ndarray::Array<long, 1> const&, int) const; \
504 template ndarray::Array<TYPE, 2, 2> ImageScale::fromFits<TYPE>( \
505 ndarray::Array<TYPE, 2, 2> const&) const;
int const N_RESERVED_VALUES
ImageScalingOptions()
Default Ctor.
int bitpix
Bits per pixel (0, 8,16,32,64,-32,-64)
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.
ndarray::Array< T, 2, 2 > fromFits(ndarray::Array< T, 2, 2 > const &image) const
Convert to an array.
Scale to preserve dynamic range.
int compressionAlgorithmToCfitsio(ImageCompressionOptions::CompressionAlgorithm algorithm)
Convert ImageCompressionOptions::CompressionAlgorithm to cfitsio.
long blank
Value for integer images indicating non-finite values.
Extent< int, N > ceil(Extent< double, N > const &input)
Return the component-wise ceil (round towards more positive).
#define INSTANTIATE(TYPE)
CompressionAlgorithm
Compression algorithms.
FITS BITPIX header value by C++ type.
Extent< int, N > floor(Extent< double, N > const &input)
Return the component-wise floor (round towards more negative).
Tiles tiles
Tile size; a dimension with 0 means infinite (e.g., to specify one row: 0,1)
ImageCompressionOptions(CompressionAlgorithm algorithm_, Tiles tiles_, float quantizeLevel_=0.0)
Custom compression.
float quantizeLevel
Divisor of the standard deviation for STDEV_* scaling.
double bzero
Zero-point to apply when reading from FITS.
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromString(std::string const &name)
Interpret compression algorithm expressed in string.
std::shared_ptr< detail::PixelArrayBase > toFits(ndarray::Array< T const, 2, 2 > const &image, bool forceNonfiniteRemoval, bool fuzz=true, ndarray::Array< long, 1 > const &tiles=ndarray::Array< long, 1, 1 >(), int seed=1) const
Convert to an array of pixel values to write to FITS.
table::Key< std::string > name
double bscale
Scale to apply when reading from FITS.
std::string scalingAlgorithmToString(ImageScalingOptions::ScalingAlgorithm algorithm)
Provide string version of compression algorithm.
Scaling zero-point, set according to pixel type.
std::string compressionAlgorithmToString(ImageCompressionOptions::CompressionAlgorithm algorithm)
Provide string version of compression algorithm.
static double constexpr value
Standard GZIP compression.
Scale based on the standard deviation, dynamic range negative.
double bzero
Manually specified BSCALE and BZERO (for MANUAL scaling)
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromCfitsio(int cfitsio)
Convert compression algorithm from cfitsio to ImageCompressionOptions::CompressionAlgorithm.
ScalingAlgorithm algorithm
Scaling algorithm to use.
Scale based on the standard deviation, dynamic range positive+negative.
float quantizePad
Number of stdev to allow on the low/high side (for STDEV_POSITIVE/NEGATIVE)
Scale based on the standard deviation. dynamic range positive.
ImageScalingOptions::ScalingAlgorithm scalingAlgorithmFromString(std::string const &name)
Interpret scaling algorithm expressed in string.
GZIP compression with shuffle (most-significant byte first)