Coverage for python/lsst/meas/extensions/piff/piffPsf.py: 91%

101 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 07:07 +0000

1# This file is part of meas_extensions_piff. 

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/>. 

21 

22__all__ = ["PiffPsf"] 

23 

24import pickle 

25import piff 

26from packaging.version import Version 

27import numpy as np 

28from lsst.afw.typehandling import StorableHelperFactory 

29from lsst.meas.algorithms import ImagePsf 

30from lsst.afw.image import Image, Color 

31from lsst.geom import Box2I, Point2I, Extent2I, Point2D 

32import logging 

33 

34 

35class PiffPsf(ImagePsf): 

36 _factory = StorableHelperFactory( 

37 "lsst.meas.extensions.piff.piffPsf", 

38 "PiffPsf" 

39 ) 

40 

41 def __init__(self, width, height, piffResult, log=None): 

42 assert width == height 

43 ImagePsf.__init__(self) 

44 self.width = width 

45 self.height = height 

46 self.dimensions = Extent2I(width, height) 

47 self._piffResult = piffResult 

48 self._averagePosition = None 

49 self._averageColor = None 

50 self.log = log or logging.getLogger(__name__) 

51 

52 self._color_type = None 

53 if self.hasColor: 

54 # PiffPsfDeterminerTask enforces a single colorType on all stars. 

55 self._color_type = self._piffResult.stars[0].data.properties['colorType'] 

56 

57 @property 

58 def piffResult(self): 

59 return self._piffResult 

60 

61 @property 

62 def hasColor(self): 

63 """Whether this PSF model includes a color dependence (`bool`). 

64 

65 True if ``colorValue`` was one of the interpolation keys of the Piff 

66 fit, i.e. the chromatic fit was actually done. When False, any color 

67 passed to the ``compute*`` methods is ignored. 

68 """ 

69 return 'colorValue' in self._piffResult.interp_property_names 

70 

71 # Storable overrides 

72 

73 def isPersistable(self): 

74 return True 

75 

76 def _getPersistenceName(self): 

77 return "PiffPsf" 

78 

79 def _getPythonModule(self): 

80 return "lsst.meas.extensions.piff.piffPsf" 

81 

82 def _write(self): 

83 return pickle.dumps((self.width, self.height, self._piffResult)) 

84 

85 @staticmethod 

86 def _read(pkl): 

87 width, height, piffResult = pickle.loads(pkl) 

88 # We need to do surgery on pickles created with earlier versions of 

89 # piff when using piff version 1.4 or later. 

90 if Version(piff.version) >= Version("1.4"): 90 ↛ 96line 90 didn't jump to line 96 because the condition on line 90 was always true

91 if not hasattr(piffResult, "_num"): 

92 piffResult._num = None 

93 piffResult.model._num = None 

94 piffResult.model._fit_flux = None 

95 piffResult.interp._num = None 

96 if not hasattr(piffResult.model, "_maxk"): 

97 piffResult.model._maxk = 0 

98 if not hasattr(piffResult.model, "_stepk"): 

99 piffResult.model._stepk = 0 

100 return PiffPsf(width, height, piffResult) 

101 

102 # ImagePsf overrides 

103 

104 def __deepcopy__(self, meta=None): 

105 return PiffPsf(self.width, self.height, self._piffResult) 

106 

107 def resized(self, width, height): 

108 assert width == height 

109 return PiffPsf(width, height, self._piffResult) 

110 

111 def _doComputeImage(self, position, color): 

112 return self._doImage(position, center=None, color=color) 

113 

114 def _doComputeKernelImage(self, position, color): 

115 return self._doImage(position, center=True, color=color) 

116 

117 def _doComputeBBox(self, position, color): 

118 return self._doBBox(Point2I(0, 0), center=True) 

119 

120 def getAveragePosition(self): 

121 if self._averagePosition is None: 

122 x = np.mean([s.image_pos.x for s in self._piffResult.stars 

123 if not s.is_flagged and not s.is_reserve]) 

124 y = np.mean([s.image_pos.y for s in self._piffResult.stars 

125 if not s.is_flagged and not s.is_reserve]) 

126 self._averagePosition = Point2D(x, y) 

127 return self._averagePosition 

128 

129 def getAverageColor(self): 

130 if self._averageColor is None: 

131 if self.hasColor: 

132 c = np.nanmean([s.data.properties['colorValue'] for s in self._piffResult.stars 

133 if not s.is_flagged and not s.is_reserve]) 

134 self._averageColor = Color(colorValue=c, colorType=self._color_type) 

135 else: 

136 self._averageColor = Color() # set value to nan. 

137 return self._averageColor 

138 

139 # Internal private methods 

140 

141 def _doImage(self, position, center, color=None): 

142 # Follow Piff conventions for center. 

143 # None => draw as if star at position 

144 # True => draw in center of image 

145 if self.hasColor: 

146 if color is None or color.isIndeterminate(): 146 ↛ 156line 146 didn't jump to line 156 because the condition on line 146 was always true

147 meanColor = np.nan 

148 if self._averageColor is None: 

149 meanColor = self.getAverageColor().getColorValue() 

150 else: 

151 meanColor = self._averageColor.getColorValue() 

152 kwargs = {'colorValue': meanColor} 

153 # PSF model need a color information. 

154 # Set to mean color from PSF fit right now. 

155 else: 

156 ctype = color.getColorType() 

157 if self._color_type != color.getColorType(): 

158 raise ValueError(f"Invalid Color type. Need {self._color_type} but {ctype} is provided") 

159 kwargs = {'colorValue': color.getColorValue()} 

160 else: 

161 kwargs = {} 

162 gsimg = self._piffResult.draw( 

163 position.x, position.y, stamp_size=self.width, center=center, **kwargs, 

164 ) 

165 bbox = self._doBBox(position, center) 

166 img = Image(bbox, dtype=np.float64) 

167 img.array[:] = gsimg.array 

168 img.array /= np.sum(img.array) 

169 return img 

170 

171 def _doBBox(self, position, center): 

172 origin = -(self.dimensions//2) 

173 if center is None: 

174 origin = Point2I(position) + origin 

175 return Box2I(Point2I(origin), self.dimensions)