lsst.afw  15.0-18-g5f205baaa
fitsCompression.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 
3 #include "fitsio.h"
4 extern "C" {
5 #include "fitsio2.h"
6 }
7 
8 #include "lsst/pex/exceptions.h"
9 #include "lsst/afw/math/Random.h"
10 
12 
13 extern float* fits_rand_value; // Random numbers, defined in cfitsio
14 int const N_RESERVED_VALUES = 10; // Number of reserved values for float --> bitpix=32 conversions (cfitsio)
15 
16 namespace lsst {
17 namespace afw {
18 namespace fits {
19 
21 {
22  if (name == "NONE") return ImageCompressionOptions::NONE;
23  if (name == "GZIP") return ImageCompressionOptions::GZIP;
24  if (name == "GZIP_SHUFFLE") return ImageCompressionOptions::GZIP_SHUFFLE;
25  if (name == "RICE") return ImageCompressionOptions::RICE;
26  if (name == "HCOMPRESS") throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
27  "HCOMPRESS is unsupported");
28  if (name == "PLIO") return ImageCompressionOptions::PLIO;
29  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "Unrecognised compression algorithm: " + name);
30 }
31 
33 {
34  switch (algorithm) {
35  case ImageCompressionOptions::NONE: return "NONE";
36  case ImageCompressionOptions::GZIP: return "GZIP";
37  case ImageCompressionOptions::GZIP_SHUFFLE: return "GZIP_SHUFFLE";
38  case ImageCompressionOptions::RICE: return "RICE";
39  case ImageCompressionOptions::PLIO: return "PLIO";
40  default:
42  os << "Unrecognized compression algorithm: " << algorithm;
44  }
45 }
46 
48 {
49  switch (cfitsio) {
50  case 0: return ImageCompressionOptions::NONE;
51  case RICE_1: return ImageCompressionOptions::RICE;
52  case GZIP_1: return ImageCompressionOptions::GZIP;
53  case GZIP_2: return ImageCompressionOptions::GZIP_SHUFFLE;
54  case PLIO_1: return ImageCompressionOptions::PLIO;
56  "Unsupported compression algorithm: HCOMPRESS_1");
57  default:
59  os << "Unrecognized cfitsio compression: " << cfitsio;
61  }
62 }
63 
65 {
66  switch (algorithm) {
67  case ImageCompressionOptions::NONE: return 0;
68  case ImageCompressionOptions::GZIP: return GZIP_1;
69  case ImageCompressionOptions::GZIP_SHUFFLE: return GZIP_2;
70  case ImageCompressionOptions::RICE: return RICE_1;
71  case ImageCompressionOptions::PLIO: return PLIO_1;
72  default:
74  os << "Unrecognized compression algorithm: " << algorithm;
76  }
77 }
78 
79 
82  int rows,
83  float quantizeLevel_
84 ) : algorithm(algorithm_), tiles(ndarray::allocate(MAX_COMPRESS_DIM)), quantizeLevel(quantizeLevel_) {
85  tiles[0] = 0;
86  tiles[1] = rows;
87  for (int ii = 2; ii < MAX_COMPRESS_DIM; ++ii) tiles[ii] = 1;
88 }
89 
90 
92 {
93  if (name == "NONE") return ImageScalingOptions::NONE;
94  if (name == "RANGE") return ImageScalingOptions::RANGE;
95  if (name == "STDEV_POSITIVE") return ImageScalingOptions::STDEV_POSITIVE;
96  if (name == "STDEV_NEGATIVE") return ImageScalingOptions::STDEV_NEGATIVE;
97  if (name == "STDEV_BOTH") return ImageScalingOptions::STDEV_BOTH;
98  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "Unrecognized scaling algorithm: " + name);
99 }
100 
101 
103 {
104  switch (algorithm) {
105  case ImageScalingOptions::NONE: return "NONE";
106  case ImageScalingOptions::RANGE: return "RANGE";
107  case ImageScalingOptions::STDEV_POSITIVE: return "STDEV_POSITIVE";
108  case ImageScalingOptions::STDEV_NEGATIVE: return "STDEV_NEGATIVE";
109  case ImageScalingOptions::STDEV_BOTH: return "STDEV_BOTH";
110  default:
112  os << "Unrecognized scaling algorithm: " << algorithm;
114  }
115 }
116 
117 
119  ScalingAlgorithm algorithm_,
120  int bitpix_,
121  std::vector<std::string> const& maskPlanes_,
122  int seed_,
123  float quantizeLevel_,
124  float quantizePad_,
125  bool fuzz_,
126  double bscale_,
127  double bzero_
128 ) : algorithm(algorithm_), bitpix(bitpix_), fuzz(fuzz_),
129  seed(std::abs(seed_ - 1) % (N_RANDOM - 1) + 1), // zero is bad (cfitsio uses non-deterministic method)
130  maskPlanes(maskPlanes_),
131  quantizeLevel(quantizeLevel_), quantizePad(quantizePad_),
132  bscale(bscale_), bzero(bzero_) {}
133 
134 
135 namespace {
136 
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
142 ) {
143  std::size_t num = 0;
144  auto const& flatMask = ndarray::flatten<1>(mask);
145  for (auto mm = flatMask.begin(); mm != flatMask.end(); ++mm) {
146  if (!*mm) ++num;
147  }
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) {
153  if (*mm) continue;
154  *aa = *ii;
155  ++aa;
156  }
157 
158  // Quartiles; from https://stackoverflow.com/a/11965377/834250
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());
165 
166  T const median = num % 2 ? array[num/2] : 0.5*(array[num/2] + array[num/2 - 1]);
167  // No, we're not doing any interpolation for the lower and upper quartiles.
168  // We're estimating the noise, so it doesn't need to be super precise.
169  T const lq = array[q1];
170  T const uq = array[q3];
171  return std::make_pair(median, 0.741*(uq - lq));
172 }
173 
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
179 ) {
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) {
184  if (*mm) continue;
185  if (!std::isfinite(*ii)) continue;
186  if (*ii > max) max = *ii;
187  if (*ii < min) min = *ii;
188  }
189  return std::make_pair(min, max);
190 }
191 
192 // Return range of values for target BITPIX
193 template <typename T>
194 double rangeForBitpix(int bitpix, bool cfitsioPadding) {
195  if (bitpix == 0) {
196  bitpix = detail::Bitpix<T>::value;
197  }
198  double range = std::pow(2.0, bitpix) - 1; // Range of values for target BITPIX
199  if (cfitsioPadding) {
200  range -= N_RESERVED_VALUES;
201  }
202  return range;
203 }
204 
205 } // anonymous namespace
206 
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,
211  bool isUnsigned,
212  bool cfitsioPadding
213 ) const {
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);
219  range -= 2; // To allow for rounding and fuzz at either end
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) {
223  bzero -= bscale*N_RESERVED_VALUES;
224  }
225  bzero -= bscale; // Allow for rounding and fuzz on the low end
226  return ImageScale(bitpix, bscale, bzero);
227 }
228 
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,
233  bool isUnsigned,
234  bool cfitsioPadding
235 ) const {
236  auto stats = calculateMedianStdev(image, mask);
237  auto const median = stats.first, stdev = stats.second;
238  double const bscale = static_cast<T>(stdev/quantizeLevel);
239 
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); // Range of values for target BITPIX
245  double const numUnique = (max - min)/bscale; // Number of unique values
246 
247  double imageVal; // Value on image
248  long diskVal; // Corresponding quantized value
249  if (numUnique < range) {
250  imageVal = median;
251  diskVal = cfitsioPadding ? 0.5*N_RESERVED_VALUES : 0;
252  } else {
253  switch (algorithm) {
255  // Put (median - N sigma) at the lowest possible value: predominantly positive images
256  imageVal = median - quantizePad * stdev;
257  diskVal = (bitpix == 8) ? 0 : - (1L << (bitpix - 1)); // Lowest value: -2^(bitpix-1)
258  if (cfitsioPadding) diskVal -= N_RESERVED_VALUES;
259  break;
261  // Put (median + N sigma) at the highest possible value: predominantly negative images
262  imageVal = median + quantizePad * stdev;
263  diskVal = (bitpix == 8) ? 255 : (1L << (bitpix - 1)) - 1; // Lowest value: 2^(bitpix-1)-1
264  break;
266  // Put median right in the middle: images with an equal abundance of positive and negative values
267  imageVal = median;
268  diskVal = cfitsioPadding ? 0.5*N_RESERVED_VALUES : 0;
269  break;
270  default:
271  std::abort(); // Programming error: should never get here
272  }
273  }
274 
275  double bzero = static_cast<T>(imageVal - bscale*diskVal);
276  return ImageScale(bitpix, bscale, bzero);
277 }
278 
280 template <typename T, class Enable=void>
281 struct Bzero {
282  static double constexpr value = 0.0;
283 };
284 
285 // uint64 version
286 // 'double' doesn't have sufficient bits to represent the appropriate BZERO,
287 // so let cfitsio handle it.
288 template <>
289 struct Bzero<std::uint64_t> {
290  static double constexpr value = 0.0;
291 };
292 
293 // Unsigned integer version
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> {
297  static double constexpr value = std::numeric_limits<T>::max() >> 1;
298 };
299 
300 
301 #ifndef DOXYGEN // suppress a bogus Doxygen complaint about an documented symbol
302 template <typename T, int N>
304  ndarray::Array<T const, N, N> const& image,
305  ndarray::Array<bool, N, N> const& mask
306 ) const {
308  algorithm != NONE) {
310  "Image scaling not supported for integral types");
311  }
312  bool const isUnsigned = bitpix == 8 || (bitpix == 0 && detail::Bitpix<T>::value == 8);
313  bool const cfitsioPadding = !std::numeric_limits<T>::is_integer && bitpix == 32;
314  switch (algorithm) {
316  case RANGE: return determineFromRange(image, mask, isUnsigned, cfitsioPadding);
317  case MANUAL: return ImageScale(bitpix, bscale, bzero);
321  return determineFromStdev(image, mask, isUnsigned, cfitsioPadding);
322  default:
323  std::abort(); // should never get here
324  }
325 }
326 #endif
327 
328 namespace {
329 
334 class CfitsioRandom {
335  public:
337  CfitsioRandom(int seed) : _seed(seed) {
338  assert(seed != 0 && seed < N_RANDOM);
339  fits_init_randoms();
340  resetForTile(0);
341  }
342 
344  void resetForTile(int iTile) {
345  _start = (iTile + _seed - 1) % N_RANDOM;
346  reseed();
347  }
348 
350  float getNext() {
351  float const value = fits_rand_value[_index];
352  increment();
353  return value;
354  }
355 
357  void increment() {
358  ++_index;
359  if (_index == N_RANDOM) {
360  ++_start;
361  if (_start == N_RANDOM) {
362  _start = 0;
363  }
364  reseed();
365  }
366  }
367 
369  template <typename T>
370  ndarray::Array<T, 1, 1> forImage(
371  typename ndarray::Array<T const, 2, 2>::Index const& shape,
372  ndarray::Array<long, 1> const& tiles
373  ) {
374  std::size_t const xSize = shape[1], ySize = shape[0];
375  ndarray::Array<T, 1, 1> out = ndarray::allocate(xSize*ySize);
376  std::size_t const xTileSize = tiles[0] <= 0 ? xSize : tiles[0];
377  std::size_t const yTileSize = tiles[1] < 0 ? ySize : (tiles[1] == 0 ? 1 : tiles[1]);
378  int const xNumTiles = std::ceil(xSize/static_cast<float>(xTileSize));
379  int const yNumTiles = std::ceil(ySize/static_cast<float>(yTileSize));
380  for (int iTile = 0, yTile = 0; yTile < yNumTiles; ++yTile) {
381  int const yStart = yTile*yTileSize;
382  int const yStop = std::min(yStart + yTileSize, ySize);
383  for (int xTile = 0; xTile < xNumTiles; ++xTile, ++iTile) {
384  int const xStart = xTile*xTileSize;
385  int const xStop = std::min(xStart + xTileSize, xSize);
386  resetForTile(iTile);
387  for (int y = yStart; y < yStop; ++y) {
388  auto iter = out.begin() + y*xSize + xStart;
389  for (int x = xStart; x < xStop; ++x, ++iter) {
390  *iter = static_cast<T>(getNext());
391  }
392  }
393  }
394  }
395  return out;
396  }
397 
398  private:
400  void reseed() {
401  _index = static_cast<int>(fits_rand_value[_start]*500);
402  }
403 
404  int _seed; // Initial seed
405  int _start; // Starting index for tile; "iseed" in cfitsio
406  int _index; // Index of next value; "nextrand" in cfitsio
407 };
408 
409 } // anonymous namespace
410 
411 
412 template <typename T>
414  ndarray::Array<T const, 2, 2> const& image,
415  bool forceNonfiniteRemoval,
416  bool fuzz,
417  ndarray::Array<long, 1> const& tiles,
418  int seed
419 ) const {
423  "Floating-point images may not be converted to different floating-point types");
424  }
425  if (bscale != 1.0 || bzero != 0.0) {
427  "Scaling may not be applied to floating-point images");
428  }
429  }
430 
431  if (bitpix < 0 || (bitpix == 0 && !std::numeric_limits<T>::is_integer) ||
432  (bscale == 1.0 && bzero == 0.0 && !fuzz)) {
433  if (!forceNonfiniteRemoval) {
434  // Type conversion only
435  return detail::makePixelArray(bitpix, ndarray::Array<T const, 1, 1>(ndarray::flatten<1>(image)));
436  }
438  ndarray::Array<T, 1, 1> out = ndarray::allocate(image.getNumElements());
439  auto outIter = out.begin();
440  auto const& flatImage = ndarray::flatten<1>(image);
441  for (auto inIter = flatImage.begin(); inIter != flatImage.end(); ++inIter, ++outIter) {
442  *outIter = std::isfinite(*inIter) ? *inIter : std::numeric_limits<T>::max();
443  }
444  return detail::makePixelArray(bitpix, out);
445  }
446  // Fall through for explicit scaling
447  }
448 
449  // Note: BITPIX=8 treated differently, since it uses unsigned values; the rest use signed */
450  double min = bitpix == 8 ? 0 : -std::pow(2.0, bitpix - 1);
451  double max = bitpix == 8 ? 255 : (std::pow(2.0, bitpix - 1) - 1.0);
452 
454  // cfitsio saves space for N_RESERVED_VALUES=10 values at the low end
455  min += N_RESERVED_VALUES;
456  }
457 
458  double const scale = 1.0/bscale;
459  std::size_t const num = image.getNumElements();
460  bool const applyFuzz = fuzz && !std::numeric_limits<T>::is_integer && bitpix > 0;
461  ndarray::Array<double, 1, 1> out;
462  if (applyFuzz) {
463  if (tiles.isEmpty()) {
465  "Tile sizes must be provided if fuzzing is desired");
466  }
467  out = CfitsioRandom(seed).forImage<double>(image.getShape(), tiles);
468  } else {
469  out = ndarray::allocate(num);
470  }
471  auto outIter = out.begin();
472  auto const& flatImage = ndarray::flatten<1>(image);
473  for (auto inIter = flatImage.begin(); inIter != flatImage.end(); ++inIter, ++outIter) {
474  double value = (*inIter - bzero)*scale;
475  if (!std::isfinite(value)) {
476  // This choice of "max" for non-finite and overflow pixels is mainly cosmetic --- it has to be
477  // something, and "min" would produce holes in the cores of bright stars.
478  *outIter = blank;
479  continue;
480  }
481  if (applyFuzz) {
482  // Add random factor [0.0,1.0): adds a variance of 1/12,
483  // but preserves the expectation value given the floor()
484  value += *outIter;
485  }
486  *outIter = (value < min ? blank : (value > max ? blank : std::floor(value)));
487  }
488  return detail::makePixelArray(bitpix, out);
489 }
490 
491 
492 template <typename T>
493 ndarray::Array<T, 2, 2> ImageScale::fromFits(ndarray::Array<T, 2, 2> const& image) const {
494  ndarray::Array<T, 2, 2> memory = ndarray::allocate(image.getShape());
495  memory.deep() = bscale*image + bzero;
496  return memory;
497 }
498 
499 
500 // Explicit instantiation
501 #define INSTANTIATE(TYPE) \
502  template ImageScale ImageScalingOptions::determine<TYPE, 2>( \
503  ndarray::Array<TYPE const, 2, 2> const& image, ndarray::Array<bool, 2, 2> const& mask) const; \
504  template std::shared_ptr<detail::PixelArrayBase> ImageScale::toFits<TYPE>( \
505  ndarray::Array<TYPE const, 2, 2> const&, bool, bool, ndarray::Array<long, 1> const&, int) const; \
506  template ndarray::Array<TYPE, 2, 2> ImageScale::fromFits<TYPE>( \
507  ndarray::Array<TYPE, 2, 2> const&) const;
508 
516 INSTANTIATE(boost::float32_t);
517 INSTANTIATE(boost::float64_t);
518 
519 }}} // namespace lsst::afw::fits
int const N_RESERVED_VALUES
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.
afw::table::Key< afw::table::Array< ImagePixelT > > image
afw::table::Key< afw::table::Array< MaskPixelT > > mask
T ceil(T... args)
Scale to preserve dynamic range.
int compressionAlgorithmToCfitsio(ImageCompressionOptions::CompressionAlgorithm algorithm)
Convert ImageCompressionOptions::CompressionAlgorithm to cfitsio.
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:115
int min
Definition: Coord.cc:82
STL namespace.
#define INSTANTIATE(TYPE)
T floor(T... args)
CompressionAlgorithm
Compression algorithms.
FITS BITPIX header value by C++ type.
int seed
Seed for random number generator when fuzzing.
Fits * fits
Definition: FitsWriter.cc:90
STL class.
T min(T... args)
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.
A base class for image defects.
float quantizeLevel
Divisor of the standard deviation for STDEV_* scaling.
ndarray::Array< T, 2, 2 > fromFits(ndarray::Array< T, 2, 2 > const &image) const
Convert to an array.
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromString(std::string const &name)
Interpret compression algorithm expressed in string.
int max
Definition: BoundedField.cc:99
double bscale
Manually specified BSCALE (for MANUAL scaling)
T str(T... args)
T make_pair(T... args)
T isfinite(T... args)
double x
std::string scalingAlgorithmToString(ImageScalingOptions::ScalingAlgorithm algorithm)
Provide string version of compression algorithm.
T max(T... args)
Scaling zero-point, set according to pixel type.
std::string compressionAlgorithmToString(ImageCompressionOptions::CompressionAlgorithm algorithm)
Provide string version of compression algorithm.
#define LSST_EXCEPT(type,...)
T pow(T... args)
float quantizeLevel
quantization level: 0.0 = none requires use of GZIP or GZIP_SHUFFLE
Scale based on the standard deviation, dynamic range negative.
double bzero
Manually specified BZERO (for MANUAL scaling)
float * fits_rand_value
CompressionAlgorithm algorithm
Compresion algorithm to use.
ImageCompressionOptions::CompressionAlgorithm compressionAlgorithmFromCfitsio(int cfitsio)
Convert compression algorithm from cfitsio to ImageCompressionOptions::CompressionAlgorithm.
ImageScale determine(image::ImageBase< T > const &image, std::shared_ptr< image::Mask< image::MaskPixel > const > mask=nullptr) const
Determine the scaling for a particular image.
T abort(T... args)
T nth_element(T... args)
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)
bool fuzz
Fuzz the values when quantising floating-point values?
std::ostream * os
Definition: Schema.cc:736
int y
Definition: SpanSet.cc:44
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)
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.
Scale to apply to image.