lsst.afw  16.0-10-gd1b3a1c94
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  if (name == "NONE") return ImageCompressionOptions::NONE;
22  if (name == "GZIP") return ImageCompressionOptions::GZIP;
23  if (name == "GZIP_SHUFFLE") return ImageCompressionOptions::GZIP_SHUFFLE;
24  if (name == "RICE") return ImageCompressionOptions::RICE;
25  if (name == "HCOMPRESS")
26  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "HCOMPRESS is unsupported");
27  if (name == "PLIO") return ImageCompressionOptions::PLIO;
28  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "Unrecognised compression algorithm: " + name);
29 }
30 
32  switch (algorithm) {
34  return "NONE";
36  return "GZIP";
38  return "GZIP_SHUFFLE";
40  return "RICE";
42  return "PLIO";
43  default:
45  os << "Unrecognized compression algorithm: " << algorithm;
47  }
48 }
49 
51  switch (cfitsio) {
52  case 0:
54  case RICE_1:
56  case GZIP_1:
58  case GZIP_2:
60  case PLIO_1:
62  case HCOMPRESS_1:
64  "Unsupported compression algorithm: HCOMPRESS_1");
65  default:
67  os << "Unrecognized cfitsio compression: " << cfitsio;
69  }
70 }
71 
73  switch (algorithm) {
75  return 0;
77  return GZIP_1;
79  return GZIP_2;
81  return RICE_1;
83  return PLIO_1;
84  default:
86  os << "Unrecognized compression algorithm: " << algorithm;
88  }
89 }
90 
92  int rows, float quantizeLevel_)
93  : algorithm(algorithm_), tiles(ndarray::allocate(MAX_COMPRESS_DIM)), quantizeLevel(quantizeLevel_) {
94  tiles[0] = 0;
95  tiles[1] = rows;
96  for (int ii = 2; ii < MAX_COMPRESS_DIM; ++ii) tiles[ii] = 1;
97 }
98 
100  if (name == "NONE") return ImageScalingOptions::NONE;
101  if (name == "RANGE") return ImageScalingOptions::RANGE;
102  if (name == "STDEV_POSITIVE") return ImageScalingOptions::STDEV_POSITIVE;
103  if (name == "STDEV_NEGATIVE") return ImageScalingOptions::STDEV_NEGATIVE;
104  if (name == "STDEV_BOTH") return ImageScalingOptions::STDEV_BOTH;
105  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, "Unrecognized scaling algorithm: " + name);
106 }
107 
109  switch (algorithm) {
111  return "NONE";
113  return "RANGE";
115  return "STDEV_POSITIVE";
117  return "STDEV_NEGATIVE";
119  return "STDEV_BOTH";
120  default:
122  os << "Unrecognized scaling algorithm: " << algorithm;
124  }
125 }
126 
128  std::vector<std::string> const& maskPlanes_, int seed_,
129  float quantizeLevel_, float quantizePad_, bool fuzz_, double bscale_,
130  double bzero_)
131  : algorithm(algorithm_),
132  bitpix(bitpix_),
133  fuzz(fuzz_),
134  seed(std::abs(seed_ - 1) % (N_RANDOM - 1) +
135  1), // zero is bad (cfitsio uses non-deterministic method)
136  maskPlanes(maskPlanes_),
137  quantizeLevel(quantizeLevel_),
138  quantizePad(quantizePad_),
139  bscale(bscale_),
140  bzero(bzero_) {}
141 
142 namespace {
143 
145 template <typename T, int N>
146 std::pair<T, T> calculateMedianStdev(ndarray::Array<T const, N, N> const& image,
147  ndarray::Array<bool, N, N> const& mask) {
148  std::size_t num = 0;
149  auto const& flatMask = ndarray::flatten<1>(mask);
150  for (auto mm = flatMask.begin(); mm != flatMask.end(); ++mm) {
151  if (!*mm) ++num;
152  }
153  ndarray::Array<T, 1, 1> array = ndarray::allocate(num);
154  auto const& flatImage = ndarray::flatten<1>(image);
155  auto mm = ndarray::flatten<1>(mask).begin();
156  auto aa = array.begin();
157  for (auto ii = flatImage.begin(); ii != flatImage.end(); ++ii, ++mm) {
158  if (*mm) continue;
159  *aa = *ii;
160  ++aa;
161  }
162 
163  // Quartiles; from https://stackoverflow.com/a/11965377/834250
164  auto const q1 = num / 4;
165  auto const q2 = num / 2;
166  auto const q3 = q1 + q2;
167  std::nth_element(array.begin(), array.begin() + q1, array.end());
168  std::nth_element(array.begin() + q1 + 1, array.begin() + q2, array.end());
169  std::nth_element(array.begin() + q2 + 1, array.begin() + q3, array.end());
170 
171  T const median = num % 2 ? array[num / 2] : 0.5 * (array[num / 2] + array[num / 2 - 1]);
172  // No, we're not doing any interpolation for the lower and upper quartiles.
173  // We're estimating the noise, so it doesn't need to be super precise.
174  T const lq = array[q1];
175  T const uq = array[q3];
176  return std::make_pair(median, 0.741 * (uq - lq));
177 }
178 
180 template <typename T, int N>
181 std::pair<T, T> calculateMinMax(ndarray::Array<T const, N, N> const& image,
182  ndarray::Array<bool, N, N> const& mask) {
184  auto mm = ndarray::flatten<1>(mask).begin();
185  auto const& flatImage = ndarray::flatten<1>(image);
186  for (auto ii = flatImage.begin(); ii != flatImage.end(); ++ii, ++mm) {
187  if (*mm) continue;
188  if (!std::isfinite(*ii)) continue;
189  if (*ii > max) max = *ii;
190  if (*ii < min) min = *ii;
191  }
192  return std::make_pair(min, max);
193 }
194 
195 // Return range of values for target BITPIX
196 template <typename T>
197 double rangeForBitpix(int bitpix, bool cfitsioPadding) {
198  if (bitpix == 0) {
199  bitpix = detail::Bitpix<T>::value;
200  }
201  double range = std::pow(2.0, bitpix) - 1; // Range of values for target BITPIX
202  if (cfitsioPadding) {
203  range -= N_RESERVED_VALUES;
204  }
205  return range;
206 }
207 
208 } // anonymous namespace
209 
210 template <typename T, int N>
211 ImageScale ImageScalingOptions::determineFromRange(ndarray::Array<T const, N, N> const& image,
212  ndarray::Array<bool, N, N> const& mask, bool isUnsigned,
213  bool cfitsioPadding) 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(ndarray::Array<T const, N, N> const& image,
231  ndarray::Array<bool, N, N> const& mask, bool isUnsigned,
232  bool cfitsioPadding) const {
233  auto stats = calculateMedianStdev(image, mask);
234  auto const median = stats.first, stdev = stats.second;
235  double const bscale = static_cast<T>(stdev / quantizeLevel);
236 
238  auto minMax = calculateMinMax(image, mask);
239  T const min = minMax.first;
240  T const max = minMax.second;
241  double range = rangeForBitpix<T>(bitpix, cfitsioPadding); // Range of values for target BITPIX
242  double const numUnique = (max - min) / bscale; // Number of unique values
243 
244  double imageVal; // Value on image
245  long diskVal; // Corresponding quantized value
246  if (numUnique < range) {
247  imageVal = median;
248  diskVal = cfitsioPadding ? 0.5 * N_RESERVED_VALUES : 0;
249  } else {
250  switch (algorithm) {
252  // Put (median - N sigma) at the lowest possible value: predominantly positive images
253  imageVal = median - quantizePad * stdev;
254  diskVal = (bitpix == 8) ? 0 : -(1L << (bitpix - 1)); // Lowest value: -2^(bitpix-1)
255  if (cfitsioPadding) diskVal -= N_RESERVED_VALUES;
256  break;
258  // Put (median + N sigma) at the highest possible value: predominantly negative images
259  imageVal = median + quantizePad * stdev;
260  diskVal = (bitpix == 8) ? 255 : (1L << (bitpix - 1)) - 1; // Lowest value: 2^(bitpix-1)-1
261  break;
263  // Put median right in the middle: images with an equal abundance of positive and negative
264  // values
265  imageVal = median;
266  diskVal = cfitsioPadding ? 0.5 * N_RESERVED_VALUES : 0;
267  break;
268  default:
269  std::abort(); // Programming error: should never get here
270  }
271  }
272 
273  double bzero = static_cast<T>(imageVal - bscale * diskVal);
274  return ImageScale(bitpix, bscale, bzero);
275 }
276 
278 template <typename T, class Enable = void>
279 struct Bzero {
280  static double constexpr value = 0.0;
281 };
282 
283 // uint64 version
284 // 'double' doesn't have sufficient bits to represent the appropriate BZERO,
285 // so let cfitsio handle it.
286 template <>
287 struct Bzero<std::uint64_t> {
288  static double constexpr value = 0.0;
289 };
290 
291 // Unsigned integer version
292 template <typename T>
293 struct Bzero<T, typename std::enable_if<std::numeric_limits<T>::is_integer &&
294  !std::numeric_limits<T>::is_signed>::type> {
295  static double constexpr value = std::numeric_limits<T>::max() >> 1;
296 };
297 
298 #ifndef DOXYGEN // suppress a bogus Doxygen complaint about an documented symbol
299 template <typename T, int N>
300 ImageScale ImageScalingOptions::determine(ndarray::Array<T const, N, N> const& image,
301  ndarray::Array<bool, N, N> const& mask) const {
303  algorithm != NONE) {
305  "Image scaling not supported for integral types");
306  }
307  bool const isUnsigned = bitpix == 8 || (bitpix == 0 && detail::Bitpix<T>::value == 8);
308  bool const cfitsioPadding = !std::numeric_limits<T>::is_integer && bitpix == 32;
309  switch (algorithm) {
310  case NONE:
312  case RANGE:
313  return determineFromRange(image, mask, isUnsigned, cfitsioPadding);
314  case MANUAL:
315  return ImageScale(bitpix, bscale, bzero);
319  return determineFromStdev(image, mask, isUnsigned, cfitsioPadding);
320  default:
321  std::abort(); // should never get here
322  }
323 }
324 #endif
325 
326 namespace {
327 
332 class CfitsioRandom {
333 public:
335  CfitsioRandom(int seed) : _seed(seed) {
336  assert(seed != 0 && seed < N_RANDOM);
337  fits_init_randoms();
338  resetForTile(0);
339  }
340 
342  void resetForTile(int iTile) {
343  _start = (iTile + _seed - 1) % N_RANDOM;
344  reseed();
345  }
346 
348  float getNext() {
349  float const value = fits_rand_value[_index];
350  increment();
351  return value;
352  }
353 
355  void increment() {
356  ++_index;
357  if (_index == N_RANDOM) {
358  ++_start;
359  if (_start == N_RANDOM) {
360  _start = 0;
361  }
362  reseed();
363  }
364  }
365 
367  template <typename T>
368  ndarray::Array<T, 1, 1> forImage(typename ndarray::Array<T const, 2, 2>::Index const& shape,
369  ndarray::Array<long, 1> const& tiles) {
370  std::size_t const xSize = shape[1], ySize = shape[0];
371  ndarray::Array<T, 1, 1> out = ndarray::allocate(xSize * ySize);
372  std::size_t const xTileSize = tiles[0] <= 0 ? xSize : tiles[0];
373  std::size_t const yTileSize = tiles[1] < 0 ? ySize : (tiles[1] == 0 ? 1 : tiles[1]);
374  int const xNumTiles = std::ceil(xSize / static_cast<float>(xTileSize));
375  int const yNumTiles = std::ceil(ySize / static_cast<float>(yTileSize));
376  for (int iTile = 0, yTile = 0; yTile < yNumTiles; ++yTile) {
377  int const yStart = yTile * yTileSize;
378  int const yStop = std::min(yStart + yTileSize, ySize);
379  for (int xTile = 0; xTile < xNumTiles; ++xTile, ++iTile) {
380  int const xStart = xTile * xTileSize;
381  int const xStop = std::min(xStart + xTileSize, xSize);
382  resetForTile(iTile);
383  for (int y = yStart; y < yStop; ++y) {
384  auto iter = out.begin() + y * xSize + xStart;
385  for (int x = xStart; x < xStop; ++x, ++iter) {
386  *iter = static_cast<T>(getNext());
387  }
388  }
389  }
390  }
391  return out;
392  }
393 
394 private:
396  void reseed() { _index = static_cast<int>(fits_rand_value[_start] * 500); }
397 
398  int _seed; // Initial seed
399  int _start; // Starting index for tile; "iseed" in cfitsio
400  int _index; // Index of next value; "nextrand" in cfitsio
401 };
402 
403 } // anonymous namespace
404 
405 template <typename T>
406 std::shared_ptr<detail::PixelArrayBase> ImageScale::toFits(ndarray::Array<T const, 2, 2> const& image,
407  bool forceNonfiniteRemoval, bool fuzz,
408  ndarray::Array<long, 1> const& tiles,
409  int seed) const {
413  "Floating-point images may not be converted to different floating-point types");
414  }
415  if (bscale != 1.0 || bzero != 0.0) {
417  "Scaling may not be applied to floating-point images");
418  }
419  }
420 
421  if (bitpix < 0 || (bitpix == 0 && !std::numeric_limits<T>::is_integer) ||
422  (bscale == 1.0 && bzero == 0.0 && !fuzz)) {
423  if (!forceNonfiniteRemoval) {
424  // Type conversion only
425  return detail::makePixelArray(bitpix, ndarray::Array<T const, 1, 1>(ndarray::flatten<1>(image)));
426  }
428  ndarray::Array<T, 1, 1> out = ndarray::allocate(image.getNumElements());
429  auto outIter = out.begin();
430  auto const& flatImage = ndarray::flatten<1>(image);
431  for (auto inIter = flatImage.begin(); inIter != flatImage.end(); ++inIter, ++outIter) {
432  *outIter = std::isfinite(*inIter) ? *inIter : std::numeric_limits<T>::max();
433  }
434  return detail::makePixelArray(bitpix, out);
435  }
436  // Fall through for explicit scaling
437  }
438 
439  // Note: BITPIX=8 treated differently, since it uses unsigned values; the rest use signed */
440  double min = bitpix == 8 ? 0 : -std::pow(2.0, bitpix - 1);
441  double max = bitpix == 8 ? 255 : (std::pow(2.0, bitpix - 1) - 1.0);
442 
444  // cfitsio saves space for N_RESERVED_VALUES=10 values at the low end
445  min += N_RESERVED_VALUES;
446  }
447 
448  double const scale = 1.0 / bscale;
449  std::size_t const num = image.getNumElements();
450  bool const applyFuzz = fuzz && !std::numeric_limits<T>::is_integer && bitpix > 0;
451  ndarray::Array<double, 1, 1> out;
452  if (applyFuzz) {
453  if (tiles.isEmpty()) {
455  "Tile sizes must be provided if fuzzing is desired");
456  }
457  out = CfitsioRandom(seed).forImage<double>(image.getShape(), tiles);
458  } else {
459  out = ndarray::allocate(num);
460  }
461  auto outIter = out.begin();
462  auto const& flatImage = ndarray::flatten<1>(image);
463  for (auto inIter = flatImage.begin(); inIter != flatImage.end(); ++inIter, ++outIter) {
464  double value = (*inIter - bzero) * scale;
465  if (!std::isfinite(value)) {
466  // This choice of "max" for non-finite and overflow pixels is mainly cosmetic --- it has to be
467  // something, and "min" would produce holes in the cores of bright stars.
468  *outIter = blank;
469  continue;
470  }
471  if (applyFuzz) {
472  // Add random factor [0.0,1.0): adds a variance of 1/12,
473  // but preserves the expectation value given the floor()
474  value += *outIter;
475  }
476  *outIter = (value < min ? blank : (value > max ? blank : std::floor(value)));
477  }
478  return detail::makePixelArray(bitpix, out);
479 }
480 
481 template <typename T>
482 ndarray::Array<T, 2, 2> ImageScale::fromFits(ndarray::Array<T, 2, 2> const& image) const {
483  ndarray::Array<T, 2, 2> memory = ndarray::allocate(image.getShape());
484  memory.deep() = bscale * image + bzero;
485  return memory;
486 }
487 
488 // Explicit instantiation
489 #define INSTANTIATE(TYPE) \
490  template ImageScale ImageScalingOptions::determine<TYPE, 2>( \
491  ndarray::Array<TYPE const, 2, 2> const& image, ndarray::Array<bool, 2, 2> const& mask) const; \
492  template std::shared_ptr<detail::PixelArrayBase> ImageScale::toFits<TYPE>( \
493  ndarray::Array<TYPE const, 2, 2> const&, bool, bool, ndarray::Array<long, 1> const&, int) const; \
494  template ndarray::Array<TYPE, 2, 2> ImageScale::fromFits<TYPE>(ndarray::Array<TYPE, 2, 2> const&) const;
495 
503 INSTANTIATE(boost::float32_t);
504 INSTANTIATE(boost::float64_t);
505 
506 } // namespace fits
507 } // namespace afw
508 } // namespace lsst
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:113
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:98
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:737
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.