Coverage for tests/test_linearize.py: 98%
299 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 20:25 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 20:25 +0000
1# This file is part of ip_isr.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22import unittest
24import logging
25import numpy as np
27import lsst.utils.tests
28import lsst.utils
29import lsst.afw.image as afwImage
30import lsst.afw.math as afwMath
31import lsst.afw.cameraGeom as cameraGeom
32from lsst.afw.geom.testUtils import BoxGrid
33from lsst.afw.image.testUtils import makeRampImage
34from lsst.ip.isr import applyLookupTable, Linearizer
35from lsst.ip.isr.linearize import SplineLUT, LinearizeSpline, LinearizeDoubleSpline
36from scipy.interpolate import Akima1DInterpolator
39def referenceImage(image, detector, linearityType, inputData, table=None):
40 """Generate a reference linearization.
42 Parameters
43 ----------
44 image: `lsst.afw.image.Image`
45 Image to linearize.
46 detector: `lsst.afw.cameraGeom.Detector`
47 Detector this image is from.
48 linearityType: `str`
49 Type of linearity to apply.
50 inputData: `numpy.array`
51 An array of values for the linearity correction.
52 table: `numpy.array`, optional
53 An optional lookup table to use.
55 Returns
56 -------
57 outImage: `lsst.afw.image.Image`
58 The output linearized image.
59 numOutOfRange: `int`
60 The number of values that could not be linearized.
62 Raises
63 ------
64 RuntimeError :
65 Raised if an invalid linearityType is supplied.
66 """
67 numOutOfRange = 0
68 for ampIdx, amp in enumerate(detector.getAmplifiers()):
69 ampIdx = (ampIdx // 3, ampIdx % 3)
70 bbox = amp.getBBox()
71 imageView = image.Factory(image, bbox)
73 if linearityType == 'Squared':
74 sqCoeff = inputData[ampIdx]
75 array = imageView.getArray()
77 array[:] = array + sqCoeff*array**2
78 elif linearityType == 'LookupTable':
79 rowInd, colIndOffset = inputData[ampIdx]
80 rowInd = int(rowInd)
81 tableRow = table[rowInd, :]
82 numOutOfRange += applyLookupTable(imageView, tableRow, colIndOffset)
83 elif linearityType == 'Polynomial':
84 coeffs = inputData[ampIdx]
85 array = imageView.getArray()
86 summation = np.zeros_like(array)
87 for index, coeff in enumerate(coeffs):
88 summation += coeff*np.power(array, (index + 2))
89 array += summation
90 elif linearityType == 'Spline':
91 centers, values = np.split(inputData, 2) # This uses the full data
92 # Note that we are using the slow afw AKIMA_SPLINE interpolator
93 # to offset the data, but using the equivalent but faster scipy
94 # Akima1DInterpolator to correct the data.
95 interp = afwMath.makeInterpolate(centers.tolist(), values.tolist(),
96 afwMath.stringToInterpStyle('AKIMA_SPLINE'))
97 array = imageView.getArray()
98 delta = interp.interpolate(array.flatten())
99 array -= np.array(delta).reshape(array.shape)
100 elif linearityType == 'DoubleSpline': 100 ↛ 116line 100 didn't jump to line 116 because the condition on line 100 was always true
101 nNodes1 = int(inputData[0])
102 nNodes2 = int(inputData[1])
104 centers1, values1 = np.split(inputData[2: 2 + 2*nNodes1], 2)
105 centers2, values2 = np.split(inputData[2 + 2*nNodes1: 2 + 2*nNodes1 + 2*nNodes2], 2)
106 interp1 = afwMath.makeInterpolate(centers1.tolist(), values1.tolist(),
107 afwMath.stringToInterpStyle('AKIMA_SPLINE'))
108 interp2 = afwMath.makeInterpolate(centers2.tolist(), values2.tolist(),
109 afwMath.stringToInterpStyle('AKIMA_SPLINE'))
110 array = imageView.getArray()
111 delta1 = interp1.interpolate(array.ravel())
112 array -= np.asarray(delta1).reshape(array.shape)
113 delta2 = interp2.interpolate(array.ravel())
114 array -= np.asarray(delta2).reshape(array.shape)
115 else:
116 raise RuntimeError(f"Unknown linearity: {linearityType}")
117 return image, numOutOfRange
120class LinearizeTestCase(lsst.utils.tests.TestCase):
121 """Unit tests for linearizers.
122 """
124 def setUp(self):
125 # This uses the same arbitrary values used in previous tests.
126 self.bbox = lsst.geom.Box2I(lsst.geom.Point2I(-31, 22), lsst.geom.Extent2I(100, 85))
127 self.ampArrangement = (2, 3)
128 self.numAmps = self.ampArrangement[0]*self.ampArrangement[1]
130 # Squared Parameters
131 self.sqCoeffs = np.array([[0, 5e-6, 2.5e-5], [1e-5, 1.1e-6, 2.1e-6]], dtype=float)
133 # Lookup Table Parameters
134 self.colIndOffsets = np.array([[0, -50, 2.5], [37, 1, -3]], dtype=float)
135 self.rowInds = np.array([[0, 1, 4], [3, 5, 2]])
136 # This creates a 2x3 array (matching the amplifiers) that contains a
137 # 2x1 array containing [colIndOffset_i, rowInd_i].
138 self.lookupIndices = np.transpose(np.stack((self.rowInds, self.colIndOffsets), axis=0),
139 axes=[1, 2, 0])
141 rng = np.random.Generator(np.random.MT19937(1))
142 self.table = rng.normal(scale=55, size=(self.numAmps, 2500))
143 self.assertLess(np.max(self.rowInds), self.numAmps, "error in test conditions; invalid row index")
145 # Polynomial Parameters: small perturbation on Squared
146 self.polyCoeffs = np.array([[[0, 1e-7], [5e-6, 1e-7], [2.5e-5, 1e-7]],
147 [[1e-5, 1e-7], [1.1e-6, 1e-7], [2.1e-6, 1e-7]]], dtype=float)
149 # Spline coefficients: should match a 1e-6 Squared solution
150 self.splineCoeffs = np.array([0.0, 1000, 2000, 3000, 4000, 5000,
151 0.0, 1.0, 4.0, 9.0, 16.0, 25.0])
153 # Double spline coefficients.
154 self.doubleSplineCoeffs = np.asarray(
155 [
156 5, # Number of nodes in first spline.
157 6, # Number of nodes in second spline.
158 0.0, 2000., 3000., 4000., 5000., # Nodes for first spline.
159 0.0, 0.01, 0.02, 0.03, 0.04, # Values for first spline.
160 0.0, 1000, 2000, 3000, 4000, 5000, # Nodes for second spline.
161 0.0, 1.0, 4.0, 9.0, 16.0, 25.0, # Values for second spline.
162 0.0, 0.0, # Extra filler.
163 ],
164 )
166 self.log = logging.getLogger("lsst.ip.isr.testLinearizer")
168 def tearDown(self):
169 # destroy LSST objects so memory test passes.
170 self.bbox = None
171 self.detector = None
173 def compareResults(self, linearizedImage, linearizedOutOfRange, linearizedCount, linearizedAmps,
174 referenceImage, referenceOutOfRange, referenceCount, referenceAmps):
175 """Run assert tests on results.
177 Parameters
178 ----------
179 linearizedImage : `lsst.afw.image.Image`
180 Corrected image.
181 linearizedOutOfRange : `int`
182 Number of measured out-of-range pixels.
183 linearizedCount : `int`
184 Number of amplifiers that should be linearized.
185 linearizedAmps : `int`
186 Total number of amplifiers checked.
187 referenceImage : `lsst.afw.image.Image`
188 Truth image to compare against.
189 referenceOutOfRange : `int`
190 Number of expected out-of-range-pixels.
191 referenceCount : `int`
192 Number of amplifiers that are expected to be linearized.
193 referenceAmps : `int`
194 Expected number of amplifiers checked.
195 """
196 self.assertImagesAlmostEqual(linearizedImage, referenceImage)
197 self.assertEqual(linearizedOutOfRange, referenceOutOfRange)
198 self.assertEqual(linearizedCount, referenceCount)
199 self.assertEqual(linearizedAmps, referenceAmps)
201 def testBasics(self):
202 """Test basic linearization functionality.
203 """
204 for imageClass in (afwImage.ImageF, afwImage.ImageD):
205 inImage = makeRampImage(bbox=self.bbox, start=-5, stop=2500, imageClass=imageClass)
207 for linearityType in ('Squared', 'LookupTable', 'Polynomial', 'Spline', 'DoubleSpline'):
208 detector = self.makeDetector(linearityType)
209 table = None
210 inputData = {'Squared': self.sqCoeffs,
211 'LookupTable': self.lookupIndices,
212 'Polynomial': self.polyCoeffs,
213 'Spline': self.splineCoeffs,
214 'DoubleSpline': self.doubleSplineCoeffs}[linearityType]
215 if linearityType == 'LookupTable':
216 table = np.array(self.table, dtype=inImage.getArray().dtype)
217 linearizer = Linearizer(detector=detector, table=table)
219 measImage = inImage.Factory(inImage, True)
220 result = linearizer.applyLinearity(measImage, detector=detector, log=self.log)
221 refImage, refNumOutOfRange = referenceImage(inImage.Factory(inImage, True),
222 detector, linearityType, inputData, table)
224 # This is necessary for the same tests to be used on
225 # all types. The first amplifier has 0.0 for the
226 # coefficient, which should be tested (it has a log
227 # message), but we are not linearizing an amplifier
228 # with no correction, so it fails the test that
229 # numLinearized == numAmps.
230 zeroLinearity = 1 if linearityType == 'Squared' else 0
232 self.compareResults(measImage, result.numOutOfRange, result.numLinearized, result.numAmps,
233 refImage, refNumOutOfRange, self.numAmps - zeroLinearity, self.numAmps)
235 # Test a stand alone linearizer. This ignores validate checks.
236 measImage = inImage.Factory(inImage, True)
237 storedLinearizer = self.makeLinearizer(linearityType)
238 storedResult = storedLinearizer.applyLinearity(measImage, log=self.log)
240 self.compareResults(measImage, storedResult.numOutOfRange, storedResult.numLinearized,
241 storedResult.numAmps,
242 refImage, refNumOutOfRange, self.numAmps - zeroLinearity, self.numAmps)
244 # "Save to yaml" and test again
245 storedDict = storedLinearizer.toDict()
246 storedLinearizer = Linearizer().fromDict(storedDict)
248 measImage = inImage.Factory(inImage, True)
249 storedResult = storedLinearizer.applyLinearity(measImage, log=self.log)
251 self.compareResults(measImage, storedResult.numOutOfRange, storedResult.numLinearized,
252 storedResult.numAmps,
253 refImage, refNumOutOfRange, self.numAmps - zeroLinearity, self.numAmps)
255 # "Save to fits" and test again
256 storedTable = storedLinearizer.toTable()
257 storedLinearizer = Linearizer().fromTable(storedTable)
259 measImage = inImage.Factory(inImage, True)
260 storedResult = storedLinearizer.applyLinearity(measImage, log=self.log)
262 self.compareResults(measImage, storedResult.numOutOfRange, storedResult.numLinearized,
263 storedResult.numAmps,
264 refImage, refNumOutOfRange, self.numAmps - zeroLinearity, self.numAmps)
266 # Use a gain and test again
267 measImage = inImage.Factory(inImage, True)
268 storedLinearizer = self.makeLinearizer(linearityType)
269 gains = {key: 1.0 for key in storedLinearizer.linearityType.keys()}
270 storedResult = storedLinearizer.applyLinearity(measImage, log=self.log, gains=gains)
272 self.compareResults(measImage, storedResult.numOutOfRange, storedResult.numLinearized,
273 storedResult.numAmps,
274 refImage, refNumOutOfRange, self.numAmps - zeroLinearity, self.numAmps)
276 def makeDetector(self, linearityType, bbox=None):
277 """Generate a fake detector for the test.
279 Parameters
280 ----------
281 linearityType : `str`
282 Which linearity to assign to the detector's cameraGeom.
283 bbox : `lsst.geom.Box2I`, optional
284 Bounding box to use for the detector.
286 Returns
287 -------
288 detBuilder : `lsst.afw.cameraGeom.Detector`
289 The fake detector.
290 """
291 bbox = bbox if bbox is not None else self.bbox
292 numAmps = self.ampArrangement
294 detName = "det_a"
295 detId = 1
296 detSerial = "123"
297 orientation = cameraGeom.Orientation()
298 pixelSize = lsst.geom.Extent2D(1, 1)
300 camBuilder = cameraGeom.Camera.Builder("fakeCam")
301 detBuilder = camBuilder.add(detName, detId)
302 detBuilder.setSerial(detSerial)
303 detBuilder.setBBox(bbox)
304 detBuilder.setOrientation(orientation)
305 detBuilder.setPixelSize(pixelSize)
307 boxArr = BoxGrid(box=bbox, numColRow=numAmps)
308 for i in range(numAmps[0]):
309 for j in range(numAmps[1]):
310 ampInfo = cameraGeom.Amplifier.Builder()
311 ampInfo.setName("amp %d_%d" % (i + 1, j + 1))
312 ampInfo.setBBox(boxArr[i, j])
313 ampInfo.setLinearityType(linearityType)
314 if linearityType == 'Squared':
315 ampInfo.setLinearityCoeffs([self.sqCoeffs[i, j]])
316 elif linearityType == 'LookupTable':
317 # setLinearityCoeffs is picky about getting a mixed
318 # int/float list.
319 ampInfo.setLinearityCoeffs(np.array([self.rowInds[i, j], self.colIndOffsets[i, j],
320 0, 0], dtype=float))
321 elif linearityType == 'Polynomial':
322 ampInfo.setLinearityCoeffs(self.polyCoeffs[i, j])
323 elif linearityType == 'Spline':
324 ampInfo.setLinearityCoeffs(self.splineCoeffs)
325 elif linearityType == 'DoubleSpline': 325 ↛ 327line 325 didn't jump to line 327 because the condition on line 325 was always true
326 ampInfo.setLinearityCoeffs(self.doubleSplineCoeffs)
327 detBuilder.append(ampInfo)
329 return detBuilder
331 def makeLinearizer(self, linearityType, bbox=None):
332 """Construct a linearizer with the test coefficients.
334 Parameters
335 ----------
336 linearityType : `str`
337 Type of linearity to use. The coefficients are set by the
338 setUp method.
339 bbox : `lsst.geom.Box2I`
340 Bounding box for the full detector. Used to assign
341 amp-based bounding boxes.
343 Returns
344 -------
345 linearizer : `lsst.ip.isr.Linearizer`
346 A fully constructed, persistable linearizer.
347 """
348 bbox = bbox if bbox is not None else self.bbox
349 numAmps = self.ampArrangement
350 boxArr = BoxGrid(box=bbox, numColRow=numAmps)
351 linearizer = Linearizer()
352 linearizer.hasLinearity = True
354 for i in range(numAmps[0]):
355 for j in range(numAmps[1]):
356 ampName = f"amp {i+1}_{j+1}"
357 ampBox = boxArr[i, j]
358 linearizer.ampNames.append(ampName)
360 if linearityType == 'Squared':
361 linearizer.linearityCoeffs[ampName] = np.array([self.sqCoeffs[i, j]])
362 elif linearityType == 'LookupTable':
363 linearizer.linearityCoeffs[ampName] = np.array(self.lookupIndices[i, j])
364 linearizer.tableData = self.table
365 elif linearityType == 'Polynomial':
366 linearizer.linearityCoeffs[ampName] = np.array(self.polyCoeffs[i, j])
367 elif linearityType == 'Spline':
368 linearizer.linearityCoeffs[ampName] = np.array(self.splineCoeffs)
369 elif linearityType == 'DoubleSpline': 369 ↛ 372line 369 didn't jump to line 372 because the condition on line 369 was always true
370 linearizer.linearityCoeffs[ampName] = np.asarray(self.doubleSplineCoeffs)
372 linearizer.inputGain[ampName] = 1.0
373 linearizer.inputTurnoff[ampName] = 100_000.0
374 linearizer.linearityType[ampName] = linearityType
375 linearizer.linearityBBox[ampName] = ampBox
376 linearizer.inputAbscissa[ampName] = np.array([])
377 linearizer.inputOrdinate[ampName] = np.array([])
378 linearizer.inputMask[ampName] = np.array([], dtype=np.bool_)
379 linearizer.inputGroupingIndex[ampName] = np.array([], dtype=np.int64)
380 linearizer.inputNormalization[ampName] = np.array([])
381 linearizer.fitParams[ampName] = np.array([])
382 linearizer.fitParamsErr[ampName] = np.array([])
383 linearizer.fitChiSq[ampName] = np.nan
384 linearizer.fitResiduals[ampName] = np.array([])
385 linearizer.fitResidualsSigmaMad[ampName] = np.nan
386 linearizer.fitResidualsUnmasked[ampName] = np.array([])
387 linearizer.fitResidualsModel[ampName] = np.array([])
388 linearizer.linearFit[ampName] = np.array([])
389 linearizer.linearityTurnoff[ampName] = np.nan
390 linearizer.linearityMaxSignal[ampName] = np.nan
392 return linearizer
395class LinearizeSplineLUTTestCase(lsst.utils.tests.TestCase):
396 """Test spline LUT approximation."""
398 def setUp(self):
399 self.coeffs = np.array(
400 [
401 3.10000000e+01, 4.20000000e+01, 0.00000000e+00, 1.00000000e+02,
402 9.16666667e+02, 1.73333333e+03, 2.55000000e+03, 3.36666667e+03,
403 4.18333333e+03, 5.00000000e+03, 1.00824468e+04, 1.51648935e+04,
404 2.02473403e+04, 2.53297870e+04, 3.04122338e+04, 3.54946805e+04,
405 4.05771273e+04, 4.56595740e+04, 5.07420208e+04, 5.58244675e+04,
406 6.09069143e+04, 6.59893610e+04, 7.10718078e+04, 7.61542545e+04,
407 8.12367013e+04, 8.63191480e+04, 9.14015948e+04, 9.64840415e+04,
408 1.01566488e+05, 1.06648935e+05, 1.11731382e+05, 1.16813829e+05,
409 1.21896275e+05, 0.00000000e+00, 2.57127737e-01, 9.18656313e-01,
410 1.44500841e+00, 2.10392802e+00, 2.52352228e+00, 3.02482109e+00,
411 3.39951782e+00, 5.73139402e+00, 7.80053896e+00, 9.49879550e+00,
412 1.05805421e+01, 1.18831413e+01, 1.28236340e+01, 1.38840371e+01,
413 1.51085197e+01, 1.76883772e+01, 2.05294873e+01, 2.05866913e+01,
414 1.74193547e+01, 9.99885598e+00, 3.54508405e+00, -2.51815128e+00,
415 -7.95380422e+00, -1.27917663e+01, -1.77831451e+01, -2.24518191e+01,
416 -2.70152662e+01, -3.15776911e+01, -3.50369171e+01, -3.86511063e+01,
417 0.00000000e+00, 3.01314367e+03, 6.02628734e+03, 9.03943102e+03,
418 1.20525747e+04, 1.50657184e+04, 1.80788620e+04, 2.10920057e+04,
419 2.41051494e+04, 2.71182930e+04, 3.01314367e+04, 3.31445804e+04,
420 3.61577241e+04, 3.91708677e+04, 4.21840114e+04, 4.51971551e+04,
421 4.82102988e+04, 5.12234424e+04, 5.42365861e+04, 5.72497298e+04,
422 6.02628734e+04, 6.32760171e+04, 6.62891608e+04, 6.93023045e+04,
423 7.23154481e+04, 7.53285918e+04, 7.83417355e+04, 8.13548791e+04,
424 8.43680228e+04, 8.73811665e+04, 9.03943102e+04, 9.34074538e+04,
425 9.64205975e+04, 9.94337412e+04, 1.02446885e+05, 1.05460029e+05,
426 1.08473172e+05, 1.11486316e+05, 1.14499460e+05, 1.17512603e+05,
427 1.20525747e+05, 1.23538891e+05, 0.00000000e+00, 5.56955070e+00,
428 9.10051783e+00, 1.15758850e+01, 1.29073863e+01, 1.09894808e+01,
429 6.77995949e+00, 2.49618378e+00, 6.22587525e+00, 9.58451741e+00,
430 1.80369319e+01, 2.77149612e+01, 3.20840316e+01, 3.30687975e+01,
431 3.46292108e+01, 3.90328292e+01, 3.98838232e+01, 3.58625699e+01,
432 3.21882871e+01, 2.30733220e+01, 9.62716370e+00, -8.01735826e+00,
433 -3.31899466e+01, -5.64462894e+01, -7.75822153e+01, -1.00876039e+02,
434 -1.14279103e+02, -1.20797135e+02, -1.00824177e+02, -7.05961405e+01,
435 -4.08397896e+01, -2.45405003e+01, -3.13275501e+01, -2.53090688e+01,
436 -2.77171609e+01, -1.64968546e+01, 3.09687948e+02, -1.67409893e+02,
437 2.47173203e+02, -1.89592184e+01, 1.66227471e+01, 9.69744458e+01,
438 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
439 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
440 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
441 0.00000000e+00, 0.00000000e+00,
442 ],
443 )
445 def test_splineLUT_single(self):
446 nNodes1 = int(self.coeffs[0])
447 coeff1 = self.coeffs[2: 2 + 2*nNodes1]
448 centers1, values1 = np.split(coeff1, 2)
450 lut = SplineLUT(centers1, values1)
452 arr = np.linspace(1, centers1[-1], 20000, dtype=np.float32)
454 # Old direct method
455 interp = Akima1DInterpolator(centers1, values1, method="akima")
456 lin_arr1 = arr.copy()
457 lin_arr1 -= interp(np.clip(lin_arr1, centers1[0], centers1[-1] - 0.1))
459 # New LUT method
460 lin_arr2 = arr.copy()
461 lut(lin_arr2)
463 delta = lin_arr2 - lin_arr1
464 frac_diff = (lin_arr2 - lin_arr1) / lin_arr1
466 # The largest fractional deviations are at very low flux level.
467 self.assertLess(np.max(np.abs(frac_diff)), 2e-4)
468 # The largest deviations are at high flux.
469 self.assertLess(np.max(np.abs(delta)), 1e-2)
471 def test_splineLUT_double(self):
472 nNodes1 = int(self.coeffs[0])
473 nNodes2 = int(self.coeffs[1])
474 coeff1 = self.coeffs[2: 2 + 2*nNodes1]
475 centers1, values1 = np.split(coeff1, 2)
476 coeff2 = self.coeffs[2 + 2*nNodes1: 2 + 2*nNodes1 + 2*nNodes2]
477 centers2, values2 = np.split(coeff2, 2)
479 lut = SplineLUT(centers1, values1, centers2=centers2, values2=values2)
481 arr = np.linspace(1, centers1[-1], 20000, dtype=np.float32)
483 # Old direct method
484 interp1 = Akima1DInterpolator(centers1, values1, method="akima")
485 interp2 = Akima1DInterpolator(centers2, values2, method="akima")
486 lin_arr1 = arr.copy()
487 lin_arr1 -= interp1(np.clip(lin_arr1, centers1[0], centers1[-1] - 0.1))
488 lin_arr1 -= interp2(np.clip(lin_arr1, centers2[0], centers2[-1] - 0.1))
490 # New LUT method
491 lin_arr2 = arr.copy()
492 lut(lin_arr2)
494 delta = lin_arr2 - lin_arr1
495 frac_diff = (lin_arr2 - lin_arr1) / lin_arr1
497 # The largest fractional deviations are at very low flux level.
498 self.assertLess(np.max(np.abs(frac_diff)), 4e-4)
499 # The largest deviations are at high flux.
500 self.assertLess(np.max(np.abs(delta)), 3e-2)
502 def test_linearizeSpline(self):
503 """Test application via LinearizeSpline, with gain, multiple times."""
504 linearizer = LinearizeSpline()
506 bbox = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Extent2I(500, 500))
507 image = makeRampImage(bbox=bbox, start=50, stop=50000, imageClass=afwImage.ImageF)
508 coeffs = self.coeffs[2: 2 + 2*int(self.coeffs[0])]
509 centers, values = np.split(coeffs, 2)
511 image1 = image.clone()
513 # This caches the LUT and applies it.
514 gain = 1.5
515 linearizer(image1, coeffs=coeffs, gain=gain)
517 # Check that the values are good.
518 interp = Akima1DInterpolator(centers * gain, values * gain, method="akima")
519 arr1 = image.array.copy()
520 arr1 -= interp(np.clip(arr1, centers[0] * gain, centers[-1] * gain - 0.1))
522 frac_diff = (arr1.ravel() - image1.array.ravel()) / arr1.ravel()
523 self.assertLess(np.max(np.abs(frac_diff)), 4e-4)
525 # Re-apply with same gain.
526 image2 = image.clone()
527 linearizer(image2, coeffs=coeffs, gain=1.5)
529 # Check this is the same values.
530 np.testing.assert_array_almost_equal(image2.array, image1.array)
532 # Re-apply with new gain.
533 gain = 5.0
534 image3 = image.clone()
535 linearizer(image3, coeffs=coeffs, gain=gain)
537 # Check that the values are good (again)
538 interp = Akima1DInterpolator(centers * gain, values * gain, method="akima")
539 arr3 = image.array.copy()
540 arr3 -= interp(np.clip(arr3, centers[0] * gain, centers[-1] * gain - 0.1))
542 frac_diff = (arr3.ravel() - image3.array.ravel()) / arr3.ravel()
543 self.assertLess(np.max(np.abs(frac_diff)), 4e-4)
545 def test_linearizeDoubleSpline(self):
546 """Test application via LinearizeSpline, with gain, multiple times."""
548 bbox = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Extent2I(500, 500))
549 image = makeRampImage(bbox=bbox, start=50, stop=50000, imageClass=afwImage.ImageF)
550 coeffs1 = self.coeffs[2: 2 + 2*int(self.coeffs[0])]
551 coeffs2 = self.coeffs[2 + 2*int(self.coeffs[0]): 2 + 2*int(self.coeffs[0]) + 2*int(self.coeffs[1])]
552 centers1, values1 = np.split(coeffs1, 2)
553 centers2, values2 = np.split(coeffs2, 2)
555 for mode in ["first", "second", "both"]:
556 linearizer = LinearizeDoubleSpline()
558 if mode == "first":
559 # Ignore the second spline.
560 coeffs = np.concatenate(
561 (
562 np.array([self.coeffs[0], 0], dtype=np.float64),
563 coeffs1,
564 ),
565 )
566 elif mode == "second":
567 # Ignore the first spline (and contract).
568 coeffs = np.concatenate(
569 (
570 np.array([0, self.coeffs[1]], dtype=np.float64),
571 coeffs2,
572 ),
573 )
574 else:
575 coeffs = self.coeffs.copy()
577 image1 = image.clone()
579 # This caches the LUT and applies it.
580 gain = 1.5
581 linearizer(image1, coeffs=coeffs, gain=gain)
583 # Check that the values are good.
584 arr1 = image.array.copy()
585 if mode in ["first", "both"]:
586 interp1 = Akima1DInterpolator(centers1 * gain, values1 * gain, method="akima")
587 arr1 -= interp1(np.clip(arr1, centers1[0] * gain, centers1[-1] * gain - 0.1))
588 if mode in ["second", "both"]:
589 interp2 = Akima1DInterpolator(centers2 * gain, values2 * gain, method="akima")
590 arr1 -= interp2(np.clip(arr1, centers1[0] * gain, centers1[-1] * gain - 0.1))
592 frac_diff = (arr1.ravel() - image1.array.ravel()) / arr1.ravel()
593 self.assertLess(np.max(np.abs(frac_diff)), 4e-4)
595 # Re-apply with same gain.
596 image2 = image.clone()
597 linearizer(image2, coeffs=coeffs, gain=1.5)
599 # Check this is the same values.
600 np.testing.assert_array_almost_equal(image2.array, image1.array)
602 # Re-apply with new gain.
603 gain = 5.0
604 image3 = image.clone()
605 linearizer(image3, coeffs=coeffs, gain=gain)
607 # Check that the values are good (again)
608 arr3 = image.array.copy()
609 if mode in ["first", "both"]:
610 interp1 = Akima1DInterpolator(centers1 * gain, values1 * gain, method="akima")
611 arr3 -= interp1(np.clip(arr3, centers1[0] * gain, centers1[-1] * gain - 0.1))
612 if mode in ["second", "both"]:
613 interp2 = Akima1DInterpolator(centers2 * gain, values2 * gain, method="akima")
614 arr3 -= interp2(np.clip(arr3, centers1[0] * gain, centers1[-1] * gain - 0.1))
616 frac_diff = (arr3.ravel() - image3.array.ravel()) / arr3.ravel()
617 self.assertLess(np.max(np.abs(frac_diff)), 4e-4)
620class MemoryTester(lsst.utils.tests.MemoryTestCase):
621 pass
624def setup_module(module):
625 lsst.utils.tests.init()
628if __name__ == "__main__": 628 ↛ 629line 628 didn't jump to line 629 because the condition on line 628 was never true
629 lsst.utils.tests.init()
630 unittest.main()