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_),
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) {
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;
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) {
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);
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 #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
309 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
310 "Image scaling not supported for integral types");
313 bool const cfitsioPadding = !std::numeric_limits<T>::is_integer &&
bitpix == 32;
316 case RANGE:
return determineFromRange(image, mask, isUnsigned, cfitsioPadding);
321 return determineFromStdev(image, mask, isUnsigned, cfitsioPadding);
334 class CfitsioRandom {
337 CfitsioRandom(
int seed) : _seed(seed) {
338 assert(seed != 0 && seed < N_RANDOM);
344 void resetForTile(
int iTile) {
345 _start = (iTile + _seed - 1) % N_RANDOM;
359 if (_index == N_RANDOM) {
361 if (_start == N_RANDOM) {
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
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);
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());
412 template <
typename T>
414 ndarray::Array<T const, 2, 2>
const& image,
415 bool forceNonfiniteRemoval,
417 ndarray::Array<long, 1>
const& tiles,
420 if (!std::numeric_limits<T>::is_integer &&
bitpix < 0) {
422 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
423 "Floating-point images may not be converted to different floating-point types");
426 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
427 "Scaling may not be applied to floating-point images");
431 if (
bitpix < 0 || (
bitpix == 0 && !std::numeric_limits<T>::is_integer) ||
433 if (!forceNonfiniteRemoval) {
437 if (!std::numeric_limits<T>::is_integer) {
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) {
453 if (!std::numeric_limits<T>::is_integer &&
bitpix == 32) {
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;
463 if (tiles.isEmpty()) {
464 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
465 "Tile sizes must be provided if fuzzing is desired");
467 out = CfitsioRandom(seed).forImage<
double>(image.getShape(), tiles);
469 out = ndarray::allocate(num);
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)) {
486 *outIter = (value < min ? blank : (value > max ? blank :
std::floor(value)));
492 template <
typename T>
494 ndarray::Array<T, 2, 2> memory = ndarray::allocate(image.getShape());
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; 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.
table::Key< std::string > name
Scale to preserve dynamic range.
int compressionAlgorithmToCfitsio(ImageCompressionOptions::CompressionAlgorithm algorithm)
Convert ImageCompressionOptions::CompressionAlgorithm to cfitsio.
def scale(algorithm, min, max=None, frame=None)
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.
int seed
Seed for random number generator when fuzzing.
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.
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.
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.
Standard GZIP compression.
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 BSCALE and BZERO (for MANUAL scaling)
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.
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?
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.