Coverage for python/lsst/drp/tasks/build_camera.py: 97%

352 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-19 10:01 +0000

1# This file is part of drp_tasks. 

2# 

3# LSST Data Management System 

4# This product includes software developed by the 

5# LSST Project (http://www.lsst.org/). 

6# See COPYRIGHT file at the top of the source tree. 

7# 

8# This program is free software: you can redistribute it and/or modify 

9# it under the terms of the GNU General Public License as published by 

10# the Free Software Foundation, either version 3 of the License, or 

11# (at your option) any later version. 

12# 

13# This program is distributed in the hope that it will be useful, 

14# but WITHOUT ANY WARRANTY; without even the implied warranty of 

15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

16# GNU General Public License for more details. 

17# 

18# You should have received a copy of the LSST License Statement and 

19# the GNU General Public License along with this program. If not, 

20# see <https://www.lsstcorp.org/LegalNotices/>. 

21# 

22import re 

23from collections import defaultdict 

24 

25import astshim as ast 

26import numpy as np 

27import scipy.optimize 

28 

29import lsst.pex.config 

30from lsst.afw.cameraGeom import FIELD_ANGLE, FOCAL_PLANE, PIXELS, Camera 

31from lsst.afw.geom import TransformPoint2ToPoint2 

32from lsst.geom import degrees 

33from lsst.pipe.base import Struct, Task 

34 

35__all__ = [ 

36 "BuildCameraFromAstrometryConfig", 

37 "BuildCameraFromAstrometryTask", 

38] 

39 

40# Set up global variable to use in minimization callback. 

41nFunctionEval = 0 

42 

43 

44def _z_function(params, x, y, order=4): 

45 """Convenience function for calculating the value of a 2-d polynomial with 

46 coefficients given by an array of parameters. 

47 

48 Parameters 

49 ---------- 

50 params : `np.ndarray` 

51 Coefficientss for polynomial with terms ordered 

52 [1, x, y, x^2, xy, y^2, ...]. 

53 x, y : `np.ndarray` 

54 x and y values at which to evaluate the 2-d polynomial. 

55 order : `int`, optional 

56 Order of the given polynomial. 

57 

58 Returns 

59 ------- 

60 z : `np.ndarray` 

61 Value of polynomial evaluated at (x, y). 

62 """ 

63 coeffs = np.zeros((order + 1, order + 1)) 

64 c = 0 

65 for i in range(order + 1): 

66 for j in range(i + 1): 

67 coeffs[j, i - j] = params[c] 

68 c += 1 

69 z = np.polynomial.polynomial.polyval2d(x, y, coeffs.T) 

70 return z 

71 

72 

73def _z_function_dx(params, x, y, order=4): 

74 """Convenience function for calculating the derivative with respect to x of 

75 a 2-d polynomial with coefficients given by an array of parameters. 

76 

77 Parameters 

78 ---------- 

79 params : `np.ndarray` 

80 Coefficientss for polynomial with terms ordered 

81 [1, x, y, x^2, xy, y^2, ...]. 

82 x, y : `np.ndarray` 

83 x and y values at which to evaluate the 2-d polynomial. 

84 order : `int`, optional 

85 Order of the given polynomial. 

86 

87 Returns 

88 ------- 

89 z : `np.ndarray` 

90 Derivative of polynomial evaluated at (x, y). 

91 """ 

92 coeffs = np.zeros((order + 1, order + 1)) 

93 c = 0 

94 for i in range(order + 1): 

95 for j in range(i + 1): 

96 coeffs[j, i - j] = params[c] 

97 c += 1 

98 derivCoeffs = np.zeros(coeffs.shape) 

99 derivCoeffs[:, :-1] = coeffs[:, 1:] 

100 derivCoeffs[:, :-1] *= np.arange(1, order + 1) 

101 

102 z = np.polynomial.polynomial.polyval2d(x, y, derivCoeffs.T) 

103 return z 

104 

105 

106def _z_function_dy(params, x, y, order=4): 

107 """Convenience function for calculating the derivative with respect to y of 

108 a 2-d polynomial with coefficients given by an array of parameters. 

109 

110 Parameters 

111 ---------- 

112 params : `np.ndarray` 

113 Coefficientss for polynomial with terms ordered 

114 [1, x, y, x^2, xy, y^2, ...]. 

115 x, y : `np.ndarray` 

116 x and y values at which to evaluate the 2-d polynomial. 

117 order : `int`, optional 

118 Order of the given polynomial. 

119 

120 Returns 

121 ------- 

122 z : `np.ndarray` 

123 Derivative of polynomial evaluated at (x, y). 

124 """ 

125 coeffs = np.zeros((order + 1, order + 1)) 

126 c = 0 

127 for i in range(order + 1): 

128 for j in range(i + 1): 

129 coeffs[j, i - j] = params[c] 

130 c += 1 

131 derivCoeffs = np.zeros(coeffs.shape) 

132 derivCoeffs[:-1] = coeffs[1:] 

133 derivCoeffs[:-1] *= np.arange(1, order + 1).reshape(-1, 1) 

134 

135 z = np.polynomial.polynomial.polyval2d(x, y, derivCoeffs.T) 

136 return z 

137 

138 

139class BuildCameraFromAstrometryConfig(lsst.pex.config.Config): 

140 """Configuration for BuildCameraTask.""" 

141 

142 tangentPlaneDegree = lsst.pex.config.Field( 

143 dtype=int, 

144 doc=( 

145 "Order of polynomial mapping between the focal plane and the tangent plane. Only used if " 

146 "modelSplitting='physical'." 

147 ), 

148 default=9, 

149 ) 

150 focalPlaneDegree = lsst.pex.config.Field( 

151 dtype=int, 

152 doc=( 

153 "Order of polynomial mapping between the pixels and the focal plane. Only used if " 

154 "modelSplitting='physical'." 

155 ), 

156 default=3, 

157 ) 

158 modelSplitting = lsst.pex.config.ChoiceField( 

159 dtype=str, 

160 doc="How to split the camera model into pixel to focal plane and focal plane to tangent plane parts.", 

161 default="basic", 

162 allowed={ 

163 "basic": "Put all the mapping except scaling into the pixel to focal plane part", 

164 "physical": ( 

165 "Fit a more physical mapping where as much as possible of the model variability goes" 

166 "into the focal plane to tangent plane part of the model, to imitate the effects of " 

167 "the telescope optics" 

168 ), 

169 }, 

170 ) 

171 plateScale = lsst.pex.config.Field( 

172 dtype=float, 

173 doc=("Scaling between camera coordinates in mm and angle on the sky in" " arcsec."), 

174 default=20.005867576692737, 

175 ) 

176 astInversionTolerance = lsst.pex.config.Field( 

177 dtype=float, 

178 doc="Tolerance for AST map inversion.", 

179 default=0.005, 

180 ) 

181 astInversionMaxIter = lsst.pex.config.Field( 

182 dtype=int, doc="Maximum iterations fro AST map inversion.", default=10 

183 ) 

184 modelSplittingTolerance = lsst.pex.config.Field( 

185 dtype=float, 

186 doc="Average error in model splitting minimization acceptable for convergence.", 

187 default=1e-8, 

188 ) 

189 includeMissingDetectors = lsst.pex.config.Field( 

190 dtype=bool, 

191 doc=( 

192 "Use mappings from input obs_* camera to fill in any detectors that are not included in the " 

193 "provided astrometry mappings." 

194 ), 

195 default=True, 

196 ) 

197 

198 

199class BuildCameraFromAstrometryTask(Task): 

200 """Build an `lsst.afw.cameraGeom.Camera` object out of the `gbdes` 

201 polynomials mapping from pixels to the tangent plane. 

202 

203 Parameters 

204 ---------- 

205 

206 """ 

207 

208 ConfigClass = BuildCameraFromAstrometryConfig 

209 _DefaultName = "buildCameraFromAstrometry" 

210 

211 def __init__(self, **kwargs): 

212 super().__init__(**kwargs) 

213 

214 # The gbdes model normalizes the pixel positions to the range -1 - +1. 

215 self.X = np.linspace(-1, 1, 10) 

216 self.Y = np.linspace(-1, 1, 10) 

217 x, y = np.meshgrid(self.X, self.Y) 

218 self.x = x.ravel() 

219 self.y = y.ravel() 

220 

221 def run(self, mapParams, mapTemplate, detectorList, inputCamera): 

222 """Convert the model parameters into a Camera object. 

223 

224 Parameters 

225 ---------- 

226 mapParams : `dict` [`float`] 

227 Parameters that describe the per-detector and per-visit parts of 

228 the astrometric model. 

229 mapTemplate : `dict` 

230 Dictionary describing the format of the astrometric model, 

231 following the convention in `gbdes`. 

232 detectorList : `list` [`int`] 

233 List of detector ids. 

234 camera : `lsst.afw.cameraGeom.Camera` 

235 Camera object from which to take pupil function, name, and other 

236 properties. 

237 rotationAngle : `float` 

238 Value in radians of the average rotation angle of the input visits. 

239 

240 Returns 

241 ------- 

242 camera : `lsst.afw.cameraGeom.Camera` 

243 Camera object with transformations set by the input mapParams. 

244 """ 

245 

246 # Align the model with the obs_* model camera. 

247 recenteredParams = self._recenter_model(mapParams, mapTemplate, detectorList, inputCamera) 

248 

249 if self.config.modelSplitting == "basic": 

250 # Put all of the camera distortion into the pixels->focal plane 

251 # part of the distortion model, with the focal plane->tangent plane 

252 # part only used for scaling between the focal plane and sky. 

253 pixToFocalPlane, focalPlaneToTangentPlane = self._basic_model( 

254 recenteredParams.newDeviceArray, detectorList 

255 ) 

256 

257 else: 

258 # Fit two polynomials, such that the first describes the pixel-> 

259 # focal plane part of the model, and the second describes the focal 

260 # plane->tangent plane part of the model, with the goal of 

261 # generating a more physically-motivated distortion model. 

262 pixToFocalPlane, focalPlaneToTangentPlane = self._split_model( 

263 recenteredParams.newTPx, recenteredParams.newTPy, detectorList 

264 ) 

265 

266 xScale = int(mapTemplate["BAND/DEVICE/poly"]["XMax"]) - int(mapTemplate["BAND/DEVICE/poly"]["XMin"]) 

267 yScale = int(mapTemplate["BAND/DEVICE/poly"]["YMax"]) - int(mapTemplate["BAND/DEVICE/poly"]["YMin"]) 

268 

269 # Turn the mappings into a Camera object. 

270 camera = self._translate_to_afw( 

271 pixToFocalPlane, 

272 focalPlaneToTangentPlane, 

273 detectorList, 

274 inputCamera, 

275 xScale, 

276 yScale, 

277 ) 

278 

279 return camera 

280 

281 def _recenter_model(self, mapParams, mapTemplate, detectorList, camera, transform="affine"): 

282 """Normalize and recenter the camera mappings, such that they 

283 correspond to the average visit. 

284 

285 In order to break degeneracies, `gbdes` sets one visit to have the 

286 identity for the per-visit part of its model. This visit is thus 

287 imprinted in the per-detector part of the model. This function 

288 normalizes and recenters the model such that the parameters correspond 

289 instead to the average per-visit behavior. This step assumes that the 

290 per-visit part of the model is a first-order polynomial, in which case 

291 this conversion can be done without loss of information. If `normalize` 

292 is false, the model is just recentered so that the average offset is 

293 zero. 

294 

295 Parameters 

296 ---------- 

297 mapParams : `dict` [`float`] 

298 Parameters that describe the per-detector and per-visit parts of 

299 the astrometric model. 

300 mapTemplate : `dict` 

301 Dictionary describing the format of the astrometric model, 

302 following the convention in `gbdes`. 

303 detectorList : `list` [`int`] 

304 List of detector ids. 

305 camera: `lsst.afw.cameraGeom.Camera` 

306 Existing camera model ontoo which the new model will be normalized. 

307 transform: `str` 

308 Method for recentering the camera. 

309 - ``"affine"``: The camera parameters are shifted by a linear 

310 function to minimize the difference between this camera model 

311 and a preexisting model. 

312 - ``"rigid"`: The camera parameters are shifted by a 

313 translation and rotation to minimize the difference between 

314 this camera model and a preexisting model. TODO: DM-56786 This 

315 needs to be combined with a model for other causes of shifts, 

316 like refraction or camera flexure, in order to be 

317 scientifically useful. 

318 

319 Returns 

320 ------- 

321 result : `lsst.pipe.base.Struct` 

322 A struct object with the following attributes: 

323 ``newDeviceArray`` : `np.ndarray` 

324 Array of NxM, where N is the number of detectors, and M is the 

325 number of coefficients for each per-detector mapping. 

326 ``newTPx``, ``newTPy`` : `np.ndarray` 

327 Projection of `self.x` and `self.y` onto the tangent plane for 

328 each detector, given the normalized mapping. 

329 ``inputCoords`` : `np.ndarray` 

330 Projection of `self.x` and `self.y` onto the tangent plane for 

331 each detector using the input camera. 

332 ``targetCoords`` : `np.ndarray` 

333 Projection of `self.x` and `self.y` onto the tangent plane for 

334 each detector using the target preexisting camera. 

335 """ 

336 # Get the per-device part of the model. 

337 deviceParams = [] 

338 for element in mapTemplate["BAND/DEVICE"]["Elements"]: 

339 for detector in detectorList: 

340 detectorTemplate = element.replace("DEVICE", str(detector)) 

341 detectorTemplate = detectorTemplate.replace("BAND", ".+") 

342 for k, params in mapParams.items(): 

343 if re.fullmatch(detectorTemplate, k): 

344 deviceParams.append(params) 

345 deviceArray = np.vstack(deviceParams) 

346 

347 inputTPx = [] 

348 inputTPy = [] 

349 targetTPx = [] 

350 targetTPy = [] 

351 xMax = max([det.getBBox().endX for det in camera]) - 1 

352 yMax = max([det.getBBox().endY for det in camera]) - 1 

353 

354 for d, deviceMap in enumerate(deviceArray): 

355 detector = detectorList[d] 

356 obsDet = camera[detector] 

357 detBBox = obsDet.getBBox() 

358 

359 nCoeffsDev = len(deviceMap) // 2 

360 deviceDegree = int(-1.5 + 0.5 * (1 + 8 * nCoeffsDev) ** 0.5) 

361 

362 x = ((detBBox.endX - 1) / xMax) * (self.x + 1) - 1 

363 y = ((detBBox.endY - 1) / yMax) * (self.y + 1) - 1 

364 

365 intX = _z_function(deviceMap[:nCoeffsDev], x, y, order=deviceDegree) 

366 intY = _z_function(deviceMap[nCoeffsDev:], x, y, order=deviceDegree) 

367 inputTPx.append(intX) 

368 inputTPy.append(intY) 

369 

370 # Get the tangent plane mapping for the same points from the target 

371 # camera model. 

372 dX = np.linspace(detBBox.beginX, detBBox.endX - 1, len(self.X)) 

373 dY = np.linspace(detBBox.beginY, detBBox.endY - 1, len(self.Y)) 

374 detX, detY = np.meshgrid(dX, dY) 

375 detX = detX.ravel() 

376 detY = detY.ravel() 

377 mapping = obsDet.getTransform(PIXELS, FIELD_ANGLE).getMapping() 

378 faX, faY = mapping.applyForward(np.array([detX, detY])) 

379 targetTPx.append(np.degrees(faX)) 

380 targetTPy.append(np.degrees(faY)) 

381 

382 inputCoords = np.array([np.concatenate(inputTPx), np.concatenate(inputTPy)]) 

383 targetCoords = np.array([np.concatenate(targetTPx), np.concatenate(targetTPy)]) 

384 

385 if transform == "rigid": 

386 # Find the best rigid transformation matching the new model to the 

387 # input camera model using the method described in 

388 # https://igl.ethz.ch/projects/ARAP/svd_rot.pdf. 

389 inputAve = inputCoords.mean(axis=1) 

390 targetAve = targetCoords.mean(axis=1) 

391 

392 xVec = inputCoords - inputAve.reshape(-1, 1) 

393 yVec = targetCoords - targetAve.reshape(-1, 1) 

394 

395 # Now do SVD: 

396 SMatrix = xVec.dot(yVec.T) 

397 U, S, VTrans = np.linalg.svd(SMatrix) 

398 

399 rotationMatrix = (VTrans.T).dot(U.T) 

400 translation = targetAve.reshape(-1, 1) - rotationMatrix.dot(inputAve.reshape(-1, 1)) 

401 

402 # Convert the tangent plane coordinates already calculated. 

403 matchedTPCoords = rotationMatrix.dot(inputCoords) + translation 

404 

405 # Convert the device map coefficients. 

406 nCoeffsDev = deviceArray.shape[1] // 2 

407 newDeviceArray = np.zeros(deviceArray.shape) 

408 newDeviceArray[:, :nCoeffsDev] = ( 

409 deviceArray[:, :nCoeffsDev] * rotationMatrix[0, 0] 

410 + deviceArray[:, nCoeffsDev:] * rotationMatrix[0, 1] 

411 ) 

412 newDeviceArray[:, 0] += translation[0] 

413 newDeviceArray[:, nCoeffsDev:] = ( 

414 deviceArray[:, :nCoeffsDev] * rotationMatrix[1, 0] 

415 + deviceArray[:, nCoeffsDev:] * rotationMatrix[1, 1] 

416 ) 

417 newDeviceArray[:, nCoeffsDev] += translation[1] 

418 

419 elif transform == "affine": 419 ↛ 445line 419 didn't jump to line 445 because the condition on line 419 was always true

420 # Find the transformation parameters by minimizing 

421 # (target coords - transforms X input coords)**2. 

422 x = np.vstack([np.ones_like(inputCoords[0]), inputCoords]) 

423 A = x.dot(x.T) 

424 AInv = np.linalg.inv(A) 

425 bx = (x * targetCoords[0]).sum(axis=1) 

426 by = (x * targetCoords[1]).sum(axis=1) 

427 transformX = AInv.dot(bx) 

428 transformY = AInv.dot(by) 

429 

430 matchedTPCoords = np.array([transformX, transformY]).dot(x) 

431 

432 # Convert the device map coefficients. 

433 nCoeffsDev = deviceArray.shape[1] // 2 

434 newDeviceArray = np.zeros(deviceArray.shape) 

435 newDeviceArray[:, :nCoeffsDev] = ( 

436 deviceArray[:, :nCoeffsDev] * transformX[1] + deviceArray[:, nCoeffsDev:] * transformX[2] 

437 ) 

438 newDeviceArray[:, 0] += transformX[0] 

439 newDeviceArray[:, nCoeffsDev:] = ( 

440 deviceArray[:, :nCoeffsDev] * transformY[1] + deviceArray[:, nCoeffsDev:] * transformY[2] 

441 ) 

442 newDeviceArray[:, nCoeffsDev] += transformY[0] 

443 

444 else: 

445 raise RuntimeError("Transform '%s' is not supported", transform) 

446 

447 newTPx, newTPy = matchedTPCoords 

448 

449 return Struct( 

450 newDeviceArray=newDeviceArray, 

451 newTPx=newTPx, 

452 newTPy=newTPy, 

453 inputCoords=inputCoords, 

454 targetCoords=targetCoords, 

455 ) 

456 

457 def _basic_model(self, modelParameters, detectorList): 

458 """This will just convert the pix->fp parameters into the right format, 

459 and return an identity mapping for the fp->tp part. 

460 

461 Parameters 

462 ---------- 

463 modelParameters : `np.ndarray` 

464 Array of NxM, where N is the number of detectors, and M is the 

465 number of coefficients for each per-detector mapping. 

466 detectorList : `list` [`int`] 

467 List of detector ids. 

468 

469 Returns 

470 ------- 

471 pixelsToFocalPlane : `dict` [`int`, [`string`, `float`]] 

472 Dictionary giving the per-detector pixel to focal plane mapping, 

473 with keys for each detector giving the x and y transformation 

474 polynomials. 

475 focalPlaneToTangentPlane : `dict` [`string`, `float`] 

476 Dictionary giving the focal plane to tangent plane mapping. 

477 """ 

478 

479 nCoeffsFp = modelParameters.shape[1] // 2 

480 pixelsToFocalPlane = defaultdict(dict) 

481 for d, det in enumerate(detectorList): 

482 pixelsToFocalPlane[det]["x"] = modelParameters[d][:nCoeffsFp] 

483 pixelsToFocalPlane[det]["y"] = modelParameters[d][nCoeffsFp:] 

484 

485 focalPlaneToTangentPlane = {"x": [0, 1, 0], "y": [0, 0, 1]} 

486 

487 return pixelsToFocalPlane, focalPlaneToTangentPlane 

488 

489 def _split_model(self, targetX, targetY, detectorList, pixToFpGuess=None, fpToTpGuess=None): 

490 """Fit a two-step model, with one polynomial per detector fitting the 

491 pixels to focal plane part, followed by a polynomial fitting the focal 

492 plane to tangent plane part. 

493 

494 The linear parameters of the focal plane to tangent plane model are 

495 fixed to be an identity map to remove degeneracies. 

496 

497 Parameters 

498 ---------- 

499 targetX, targetY : `np.ndarray` 

500 Target x and y values in the tangent plane. 

501 detectorList : `list` [`int`] 

502 List of detector ids. 

503 pixToFpGuess : `dict` [`int`, [`string`, `float`]] 

504 Initial guess for the pixels to focal plane mapping to use in the 

505 model fit, in the form of a dictionary giving the per-detector 

506 pixel to focal plane mapping, with keys for each detector giving 

507 the x and y transformation polynomials. 

508 focalPlaneToTangentPlane : `dict` [`string`, `float`] 

509 Initial guess for the focal plane to tangent plane mapping to use 

510 in the model fit, in the form of a dictionary giving the focal 

511 plane to tangent plane mapping. 

512 

513 Returns 

514 ------- 

515 pixelsToFocalPlane : `dict` [`int`, [`string`, `float`]] 

516 Dictionary giving the per-detector pixel to focal plane mapping, 

517 with keys for each detector giving the x and y transformation 

518 polynomials. 

519 focalPlaneToTangentPlane : `dict` [`string`, `float`] 

520 Dictionary giving the focal plane to tangent plane mapping. 

521 """ 

522 

523 tpDegree = self.config.tangentPlaneDegree 

524 fpDegree = self.config.focalPlaneDegree 

525 

526 nCoeffsFP = int((fpDegree + 2) * (fpDegree + 1) / 2) 

527 nCoeffsFPTot = len(detectorList) * nCoeffsFP * 2 

528 

529 nCoeffsTP = int((tpDegree + 2) * (tpDegree + 1) / 2) 

530 # The constant and linear terms will be fixed to remove degeneracy with 

531 # the pix->fp part of the model 

532 nCoeffsFixed = 3 

533 nCoeffsFree = nCoeffsTP - nCoeffsFixed 

534 fixedParams = np.zeros(nCoeffsTP * 2) 

535 fixedParams[1] = 1 

536 fixedParams[nCoeffsTP + 2] = 1 

537 

538 nX = len(self.x) 

539 # We need an array of the form [1, x, y, x^2, xy, y^2, ...] to use when 

540 # calculating derivatives. 

541 xyArray = np.zeros((nCoeffsFP, nX)) 

542 c = 0 

543 for ii in range(fpDegree + 1): 

544 for jj in range(ii + 1): 

545 coeffs = np.zeros((fpDegree + 1, fpDegree + 1)) 

546 coeffs[jj, ii - jj] = 1 

547 xyArray[c] = np.polynomial.polynomial.polyval2d(self.x, self.y, coeffs.T) 

548 c += 1 

549 

550 def two_part_function(params): 

551 # The function giving the split model. 

552 fpXAll = [] 

553 fpYAll = [] 

554 for i in range(len(detectorList)): 

555 fpX = _z_function( 

556 params[2 * nCoeffsFP * i : (2 * i + 1) * nCoeffsFP], self.x, self.y, order=fpDegree 

557 ) 

558 fpY = _z_function( 

559 params[(2 * i + 1) * nCoeffsFP : 2 * nCoeffsFP * (1 + i)], self.x, self.y, order=fpDegree 

560 ) 

561 fpXAll.append(fpX) 

562 fpYAll.append(fpY) 

563 fpXAll = np.array(fpXAll).ravel() 

564 fpYAll = np.array(fpYAll).ravel() 

565 

566 tpParams = fixedParams.copy() 

567 tpParams[nCoeffsFixed:nCoeffsTP] = params[nCoeffsFPTot : nCoeffsFPTot + nCoeffsFree] 

568 tpParams[nCoeffsFixed + nCoeffsTP :] = params[nCoeffsFPTot + nCoeffsFree :] 

569 

570 tpX = _z_function(tpParams[:nCoeffsTP], fpXAll, fpYAll, order=tpDegree) 

571 tpY = _z_function(tpParams[nCoeffsTP:], fpXAll, fpYAll, order=tpDegree) 

572 return tpX, tpY 

573 

574 def min_function(params): 

575 # The least-squares function to be minimized. 

576 tpX, tpY = two_part_function(params) 

577 diff = ((targetX - tpX)) ** 2 + ((targetY - tpY)) ** 2 

578 result = diff.sum() 

579 return result 

580 

581 def jac(params): 

582 # The Jacobian of min_function, which is needed for the minimizer. 

583 tpX, tpY = two_part_function(params) 

584 dX = -2 * (targetX - tpX) 

585 dY = -2 * (targetY - tpY) 

586 jacobian = np.zeros(len(params)) 

587 fpParams = params[:nCoeffsFPTot] 

588 tpParams = fixedParams.copy() 

589 tpParams[nCoeffsFixed:nCoeffsTP] = params[nCoeffsFPTot : nCoeffsFPTot + nCoeffsFree] 

590 tpParams[nCoeffsFixed + nCoeffsTP :] = params[nCoeffsFPTot + nCoeffsFree :] 

591 fpXAll = [] 

592 fpYAll = [] 

593 # Fill in the derivatives for the pix->fp terms. 

594 for i in range(len(detectorList)): 

595 dX_i = dX[nX * i : nX * (i + 1)] 

596 dY_i = dY[nX * i : nX * (i + 1)] 

597 fpX = _z_function( 

598 fpParams[2 * nCoeffsFP * i : (2 * i + 1) * nCoeffsFP], self.x, self.y, order=fpDegree 

599 ) 

600 fpY = _z_function( 

601 fpParams[(2 * i + 1) * nCoeffsFP : 2 * nCoeffsFP * (1 + i)], 

602 self.x, 

603 self.y, 

604 order=fpDegree, 

605 ) 

606 fpXAll.append(fpX) 

607 fpYAll.append(fpY) 

608 

609 dTpX_dFpX = _z_function_dx(tpParams[:nCoeffsTP], fpX, fpY, order=tpDegree) 

610 dTpX_dFpY = _z_function_dy(tpParams[:nCoeffsTP], fpX, fpY, order=tpDegree) 

611 dTpY_dFpX = _z_function_dx(tpParams[nCoeffsTP:], fpX, fpY, order=tpDegree) 

612 dTpY_dFpY = _z_function_dy(tpParams[nCoeffsTP:], fpX, fpY, order=tpDegree) 

613 

614 dTpX_part = np.concatenate([xyArray * dTpX_dFpX, xyArray * dTpX_dFpY]) 

615 dTpY_part = np.concatenate([xyArray * dTpY_dFpX, xyArray * dTpY_dFpY]) 

616 jacobian_i = (dX_i * dTpX_part + dY_i * dTpY_part).sum(axis=1) 

617 jacobian[2 * nCoeffsFP * i : 2 * nCoeffsFP * (i + 1)] = jacobian_i 

618 

619 fpXAll = np.array(fpXAll).ravel() 

620 fpYAll = np.array(fpYAll).ravel() 

621 

622 # Fill in the derivatives for the fp->tp terms. 

623 for j in range(nCoeffsFree): 

624 tParams = np.zeros(nCoeffsTP) 

625 tParams[nCoeffsFixed + j] = 1 

626 tmpZ = _z_function(tParams, fpXAll, fpYAll, order=tpDegree) 

627 jacobian[nCoeffsFPTot + j] = (dX * tmpZ).sum() 

628 jacobian[nCoeffsFPTot + nCoeffsFree + j] = (dY * tmpZ).sum() 

629 return jacobian 

630 

631 def hessian(params): 

632 # The Hessian of min_function, which is needed for the minimizer. 

633 hessian = np.zeros((len(params), len(params))) 

634 

635 fpParams = params[:nCoeffsFPTot] 

636 tpParams = fixedParams.copy() 

637 tpParams[nCoeffsFixed:nCoeffsTP] = params[nCoeffsFPTot : nCoeffsFPTot + nCoeffsFree] 

638 tpParams[nCoeffsFixed + nCoeffsTP :] = params[nCoeffsFPTot + nCoeffsFree :] 

639 fpXAll = [] 

640 fpYAll = [] 

641 

642 # Loop over the detectors to fill in the d(pix->fp)**2 and 

643 # d(pix->fp)d(fp->tp) cross terms. 

644 for i in range(len(detectorList)): 

645 fpX = _z_function( 

646 fpParams[2 * nCoeffsFP * i : (2 * i + 1) * nCoeffsFP], self.x, self.y, order=fpDegree 

647 ) 

648 fpY = _z_function( 

649 fpParams[(2 * i + 1) * nCoeffsFP : 2 * nCoeffsFP * (1 + i)], 

650 self.x, 

651 self.y, 

652 order=fpDegree, 

653 ) 

654 fpXAll.append(fpX) 

655 fpYAll.append(fpY) 

656 dTpX_dFpX = _z_function_dx(tpParams[:nCoeffsTP], fpX, fpY, order=tpDegree) 

657 dTpX_dFpY = _z_function_dy(tpParams[:nCoeffsTP], fpX, fpY, order=tpDegree) 

658 dTpY_dFpX = _z_function_dx(tpParams[nCoeffsTP:], fpX, fpY, order=tpDegree) 

659 dTpY_dFpY = _z_function_dy(tpParams[nCoeffsTP:], fpX, fpY, order=tpDegree) 

660 

661 dTpX_part = np.concatenate([xyArray * dTpX_dFpX, xyArray * dTpX_dFpY]) 

662 dTpY_part = np.concatenate([xyArray * dTpY_dFpX, xyArray * dTpY_dFpY]) 

663 

664 for k in range(2 * nCoeffsFP): 

665 for m in range(2 * nCoeffsFP): 

666 hessian[2 * nCoeffsFP * i + k, 2 * nCoeffsFP * i + m] = ( 

667 2 * (dTpX_part[k] * dTpX_part[m] + dTpY_part[k] * dTpY_part[m]).sum() 

668 ) 

669 

670 for j in range(nCoeffsFree): 

671 tmpParams = np.zeros(nCoeffsTP) 

672 tmpParams[nCoeffsFixed + j] = 1 

673 tmpZ = _z_function(tmpParams, fpX, fpY, order=tpDegree) 

674 

675 hessX = 2 * (dTpX_part[k] * tmpZ).sum() 

676 hessY = 2 * (dTpY_part[k] * tmpZ).sum() 

677 # dTP_x part 

678 hessian[2 * nCoeffsFP * i + k, nCoeffsFPTot + j] = hessX 

679 hessian[nCoeffsFPTot + j, 2 * nCoeffsFP * i + k] = hessX 

680 # dTP_y part 

681 hessian[2 * nCoeffsFP * i + k, nCoeffsFPTot + nCoeffsFree + j] = hessY 

682 hessian[nCoeffsFPTot + nCoeffsFree + j, 2 * nCoeffsFP * i + k] = hessY 

683 

684 fpXAll = np.array(fpXAll).ravel() 

685 fpYAll = np.array(fpYAll).ravel() 

686 tmpZArray = np.zeros((nCoeffsFree, nX * len(detectorList))) 

687 # Finally, get the d(fp->tp)**2 terms 

688 for j in range(nCoeffsFree): 

689 tParams = np.zeros(nCoeffsTP) 

690 tParams[nCoeffsFixed + j] = 1 

691 tmpZArray[j] = _z_function(tParams, fpXAll, fpYAll, order=tpDegree) 

692 for j in range(nCoeffsFree): 

693 for m in range(nCoeffsFree): 

694 # X-Y cross terms are zero 

695 hess = 2 * (tmpZArray[j] * tmpZArray[m]).sum() 

696 hessian[nCoeffsFPTot + j, nCoeffsFPTot + m] = hess 

697 hessian[nCoeffsFPTot + nCoeffsFree + j, nCoeffsFPTot + nCoeffsFree + m] = hess 

698 return hessian 

699 

700 global nFunctionEval 

701 nFunctionEval = 0 

702 

703 def callbackMF(params): 

704 global nFunctionEval 

705 self.log.info(f"Iteration {nFunctionEval}, function value {min_function(params)}") 

706 nFunctionEval += 1 

707 

708 initGuess = np.zeros(nCoeffsFPTot + 2 * nCoeffsFree) 

709 if pixToFpGuess: 709 ↛ 710line 709 didn't jump to line 710 because the condition on line 709 was never true

710 useVar = min(nCoeffsFP, len(pixToFpGuess[0]["x"])) 

711 for i, det in enumerate(detectorList): 

712 initGuess[2 * nCoeffsFP * i : 2 * nCoeffsFP * i + useVar] = pixToFpGuess[det]["x"][:useVar] 

713 initGuess[(2 * i + 1) * nCoeffsFP : (2 * i + 1) * nCoeffsFP + useVar] = pixToFpGuess[det][ 

714 "y" 

715 ][:useVar] 

716 if fpToTpGuess: 716 ↛ 717line 716 didn't jump to line 717 because the condition on line 716 was never true

717 useVar = min(nCoeffsTP, len(fpToTpGuess["x"])) 

718 initGuess[nCoeffsFPTot : nCoeffsFPTot + useVar - nCoeffsFixed] = fpToTpGuess["x"][ 

719 nCoeffsFixed:useVar 

720 ] 

721 initGuess[nCoeffsFPTot + nCoeffsFree : nCoeffsFPTot + nCoeffsFree + useVar - nCoeffsFixed] = ( 

722 fpToTpGuess["y"][nCoeffsFixed:useVar] 

723 ) 

724 

725 self.log.info(f"Initial value of least squares function: {min_function(initGuess)}") 

726 res = scipy.optimize.minimize( 

727 min_function, 

728 initGuess, 

729 callback=callbackMF, 

730 method="Newton-CG", 

731 jac=jac, 

732 hess=hessian, 

733 options={"xtol": self.config.modelSplittingTolerance}, 

734 ) 

735 

736 # Convert parameters to a dictionary. 

737 pixToFP = {} 

738 for i, det in enumerate(detectorList): 

739 pixToFP[det] = { 

740 "x": res.x[2 * nCoeffsFP * i : (2 * i + 1) * nCoeffsFP], 

741 "y": res.x[(2 * i + 1) * nCoeffsFP : 2 * nCoeffsFP * (1 + i)], 

742 } 

743 

744 fpToTpAll = fixedParams.copy() 

745 fpToTpAll[nCoeffsFixed:nCoeffsTP] = res.x[nCoeffsFPTot : nCoeffsFPTot + nCoeffsFree] 

746 fpToTpAll[nCoeffsFixed + nCoeffsTP :] = res.x[nCoeffsFPTot + nCoeffsFree :] 

747 fpToTp = {"x": fpToTpAll[:nCoeffsTP], "y": fpToTpAll[nCoeffsTP:]} 

748 

749 return pixToFP, fpToTp 

750 

751 def make_ast_polymap_coeffs(self, order, xCoeffs, yCoeffs): 

752 """Convert polynomial coefficients in gbdes format to AST PolyMap input 

753 format. 

754 

755 Paramaters 

756 ---------- 

757 order: `int` 

758 Polynomial order 

759 xCoeffs, yCoeffs: `list` of `float` 

760 Forward or inverse polynomial coefficients for the x and y axes 

761 of output, in this order: 

762 x0y0, x1y0, x0y1, x2y0, x1y1, x0y2, ...xNy0, xN-1y1, ...x0yN 

763 where N is the polynomial order. 

764 Returns 

765 ------- 

766 polyArray : `np.ndarray` 

767 Array formatted for AST PolyMap input. 

768 """ 

769 N = len(xCoeffs) 

770 

771 polyArray = np.zeros((2 * N, 4)) 

772 

773 for i in range(order + 1): 

774 for j in range(order + 1): 

775 if (i + j) > order: 

776 continue 

777 vectorIndex = int(((i + j) * (i + j + 1)) / 2 + j) 

778 polyArray[vectorIndex] = [xCoeffs[vectorIndex], 1, i, j] 

779 polyArray[vectorIndex + N] = [yCoeffs[vectorIndex], 2, i, j] 

780 

781 return polyArray 

782 

783 def _translate_to_afw( 

784 self, pixToFocalPlane, focalPlaneToTangentPlane, detectorList, inputCamera, xScale, yScale 

785 ): 

786 """Convert the model parameters to a Camera object. 

787 

788 Parameters 

789 ---------- 

790 pixelsToFocalPlane : `dict` [`int`, [`string`, `float`]] 

791 Dictionary giving the per-detector pixel to focal plane mapping, 

792 with keys for each detector giving the x and y transformation 

793 polynomials. 

794 focalPlaneToTangentPlane : `dict` [`string`, `float`] 

795 Dictionary giving the focal plane to tangent plane mapping. 

796 

797 Returns 

798 ------- 

799 output_camera : `lsst.afw.cameraGeom.Camera` 

800 Camera object containing the pix->fp and fp->tp transforms. 

801 """ 

802 if self.config.modelSplitting == "basic": 

803 tpDegree = 1 

804 nCoeffsFP = len(pixToFocalPlane[detectorList[0]]["x"]) 

805 fpDegree = int(-1.5 + 0.5 * (1 + 8 * nCoeffsFP) ** 0.5) 

806 else: 

807 tpDegree = self.config.tangentPlaneDegree 

808 fpDegree = self.config.focalPlaneDegree 

809 

810 scaleConvert = (1 * degrees).asArcseconds() / self.config.plateScale 

811 

812 cameraBuilder = Camera.Builder(inputCamera.getName()) 

813 cameraBuilder.setPupilFactoryName(inputCamera.getPupilFactoryName()) 

814 

815 # Convert fp->tp to AST format: 

816 forwardCoeffs = self.make_ast_polymap_coeffs( 

817 tpDegree, focalPlaneToTangentPlane["x"], focalPlaneToTangentPlane["y"] 

818 ) 

819 

820 ccdZoom = ast.ZoomMap(2, 1 / scaleConvert) 

821 ccdToSky = ast.PolyMap( 

822 forwardCoeffs, 

823 2, 

824 "IterInverse=1, TolInverse=%s, NIterInverse=%s" 

825 % (self.config.astInversionTolerance / 2.0, self.config.astInversionMaxIter), 

826 ) 

827 toRadians = ast.ZoomMap(2, (1 * degrees).asRadians()) 

828 

829 fullMapping = ccdZoom.then(ccdToSky).then(toRadians) 

830 focalPlaneToTPMapping = TransformPoint2ToPoint2(fullMapping) 

831 cameraBuilder.setTransformFromFocalPlaneTo(FIELD_ANGLE, focalPlaneToTPMapping) 

832 

833 # Convert pix->fp to AST format: 

834 for detector in inputCamera: 

835 d = detector.getId() 

836 if (not self.config.includeMissingDetectors) and (d not in pixToFocalPlane): 

837 continue 

838 

839 detectorBuilder = cameraBuilder.add(detector.getName(), detector.getId()) 

840 detectorBuilder.setBBox(detector.getBBox()) 

841 detectorBuilder.setPixelSize(detector.getPixelSize()) 

842 for amp in detector.getAmplifiers(): 

843 detectorBuilder.append(amp.rebuild()) 

844 

845 zoomMap = ast.ZoomMap(2, scaleConvert) 

846 

847 if d not in pixToFocalPlane: 

848 # Copy the existing transforms, but scale them so that when the 

849 # focalPlaneToTPMapping is applied, it is at the right scale. 

850 # We cannot use just the PIXELS to FOCAL_PLANE part, because 

851 # the FOCAL_PLANE to FIELD_ANGLE may also contain physically 

852 # meaningful information. 

853 ccdToFAMapping = detector.getTransform(PIXELS, FIELD_ANGLE).getMapping() 

854 faToFPMapping = fullMapping.inverted() 

855 ccdToFPMapping = TransformPoint2ToPoint2(ccdToFAMapping.then(faToFPMapping)) 

856 detectorBuilder.setTransformFromPixelsTo(FOCAL_PLANE, ccdToFPMapping) 

857 else: 

858 normCoeffs = self.make_ast_polymap_coeffs( 

859 1, 

860 [-1.0, 2 / xScale, 0], 

861 [-1.0, 0, 2 / yScale], 

862 ) 

863 normMap = ast.PolyMap( 

864 normCoeffs, 

865 2, 

866 "IterInverse=1, TolInverse=%s, NIterInverse=%s" 

867 % (self.config.astInversionTolerance / 2.0, self.config.astInversionMaxIter), 

868 ) 

869 forwardDetCoeffs = self.make_ast_polymap_coeffs( 

870 fpDegree, pixToFocalPlane[d]["x"], pixToFocalPlane[d]["y"] 

871 ) 

872 ccdToFP = ast.PolyMap( 

873 forwardDetCoeffs, 

874 2, 

875 "IterInverse=1, TolInverse=%s, NIterInverse=%s" 

876 % (self.config.astInversionTolerance / 2.0, self.config.astInversionMaxIter), 

877 ) 

878 zoomMap = ast.ZoomMap(2, scaleConvert) 

879 fullDetMap = normMap.then(ccdToFP).then(zoomMap) 

880 ccdToFPMapping = TransformPoint2ToPoint2(fullDetMap) 

881 detectorBuilder.setTransformFromPixelsTo(FOCAL_PLANE, ccdToFPMapping) 

882 

883 outputCamera = cameraBuilder.finish() 

884 

885 return outputCamera