Coverage for python/lsst/obs/lsst/script/generateCamera.py: 6%

171 statements  

« prev     ^ index     » next       coverage.py v6.4.2, created at 2022-07-14 17:07 -0700

1#!/usr/bin/env python 

2# This file is part of obs_lsst. 

3# 

4# Developed for the LSST Data Management System. 

5# This product includes software developed by the LSST Project 

6# (http://www.lsst.org). 

7# See the COPYRIGHT file at the top-level directory of this distribution 

8# for details of code ownership. 

9# 

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

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

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

13# (at your option) any later version. 

14# 

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

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

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

18# GNU General Public License for more details. 

19# 

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

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

22# see <http://www.lsstcorp.org/LegalNotices/>. 

23# 

24 

25__all__ = ("main",) 

26 

27import argparse 

28import os 

29import sys 

30import shutil 

31import yaml 

32import numpy as np 

33 

34 

35def findYamlOnPath(fileName, searchPath): 

36 """Find and return a file somewhere in the directories listed in 

37 searchPath""" 

38 for d in searchPath: 

39 f = os.path.join(d, fileName) 

40 if os.path.exists(f): 

41 return f 

42 

43 raise FileNotFoundError("Unable to find %s on path %s" % (fileName, ":".join(searchPath))) 

44 

45 

46def parseYamlOnPath(fileName, searchPath): 

47 """Find the named file in search path, parse the YAML, and return contents. 

48 """ 

49 yamlFile = findYamlOnPath(fileName, searchPath) 

50 with open(yamlFile) as fd: 

51 content = yaml.load(fd, Loader=yaml.CSafeLoader) 

52 return content 

53 

54 

55def build_argparser(): 

56 """Construct an argument parser for the ``generateCamera.py`` script. 

57 

58 Returns 

59 ------- 

60 argparser : `argparse.ArgumentParser` 

61 The argument parser that defines the ``translate_header.py`` 

62 command-line interface. 

63 """ 

64 

65 parser = argparse.ArgumentParser(description=""" 

66 Generate a camera.yaml file for a camera by assembling descriptions of 

67 rafts, sensors, etc. 

68 

69 Because we have many similar cameras, the assembly uses a :-separated 

70 search path of directories to find desired information. The _first_ 

71 occurrence of a filename is used. 

72 """) 

73 

74 parser.add_argument('outputFile', type=str, help="Name of generated file") 

75 parser.add_argument('--path', type=str, help="List of directories to search for components", 

76 default=False) 

77 parser.add_argument('--verbose', action="store_true", help="How chatty should I be?", default=False) 

78 

79 return parser 

80 

81 

82def applyRaftYaw(offset, raftYaw): 

83 """Apply raft yaw angle to internal offsets of the CCDs. 

84 

85 Parameters 

86 ---------- 

87 offset : `list` of `float` 

88 A list of the offsets to rotate: [x, y] 

89 raftYaw : `float` 

90 Raft yaw angle in degrees. 

91 

92 Returns 

93 ------- 

94 offsets : `list` of `float 

95 2-item sequence of floats containing the rotated offsets. 

96 """ 

97 if raftYaw == 0.: 

98 return offset 

99 new_offset = np.zeros(2, dtype=np.float) 

100 sinTheta = np.sin(np.radians(raftYaw)) 

101 cosTheta = np.cos(np.radians(raftYaw)) 

102 new_offset[0] = cosTheta*offset[0] - sinTheta*offset[1] 

103 new_offset[1] = sinTheta*offset[0] + cosTheta*offset[1] 

104 return new_offset 

105 

106 

107def generateCamera(cameraFile, path): 

108 """Generate a combined camera YAML definition from component parts. 

109 

110 Parameters 

111 ---------- 

112 cameraFile : `str` 

113 Path to output YAML file. 

114 path : `str` or `list` of `str` 

115 List of directories to search for component YAML files or a 

116 colon-separated path string. If relative paths are given they will be 

117 converted to absolute path by combining with directory specified with 

118 the output ``cameraFile``. 

119 """ 

120 cameraFileDir = os.path.dirname(cameraFile) 

121 # In some places, it's convenient to have aliases to rafts that should be 

122 # removed in the built camera. 

123 raftNameMap = {'R00W': 'R00', 'R44W': 'R44', 'R04W': 'R04', 'R40W': 'R40'} 

124 

125 if not cameraFile.endswith(".yaml"): 

126 raise RuntimeError(f"Output file name ({cameraFile}) does not end with .yaml") 

127 

128 if isinstance(path, str): 

129 path = path.split(":") 

130 searchPath = [os.path.join(cameraFileDir, d) for d in path] 

131 

132 cameraSkl = parseYamlOnPath("cameraHeader.yaml", searchPath) 

133 cameraTransforms = parseYamlOnPath("cameraTransforms.yaml", searchPath) 

134 raftData = parseYamlOnPath("rafts.yaml", searchPath) 

135 ccdData = parseYamlOnPath("ccdData.yaml", searchPath) 

136 

137 # See if we have an override of the name 

138 try: 

139 nameYaml = parseYamlOnPath("name.yaml", searchPath) 

140 except FileNotFoundError: 

141 nameOverride = None 

142 else: 

143 nameOverride = nameYaml["name"] 

144 

145 # Copy the camera header, replacing the name if needed. We can not 

146 # write out the cameraSkl dataset because that will expand all the 

147 # YAML references. We must edit the file itself. 

148 inputHeader = findYamlOnPath("cameraHeader.yaml", searchPath) 

149 if nameOverride: 

150 with open(inputHeader) as infd: 

151 with open(cameraFile, "w") as outfd: 

152 replaced = False 

153 for line in infd: 

154 if not replaced and line.startswith("name :") or line.startswith("name:"): 

155 line = f"name : {nameOverride}\n" 

156 replaced = True 

157 print(line, file=outfd, end="") 

158 if not replaced: 

159 raise RuntimeError(f"Override name {nameOverride} specified but no name" 

160 f" to replace in {inputHeader}") 

161 else: 

162 shutil.copyfile(inputHeader, cameraFile) 

163 

164 nindent = 0 # current number of indents 

165 

166 def indent(): 

167 """Return the current indent string""" 

168 dindent = 2 # number of spaces per indent 

169 return(nindent*dindent - 1)*" " # print will add the extra " " 

170 

171 with open(cameraFile, "a") as fd: 

172 print(""" 

173# 

174# Specify the geometrical transformations relevant to the camera in all appropriate 

175# (and known!) coordinate systems 

176#""", file=fd) 

177 for k, v in cameraTransforms.items(): 

178 print("%s : %s" % (k, v), file=fd) 

179 

180 print(""" 

181# 

182# Define our specific devices 

183# 

184# All the CCDs present in this file 

185# 

186CCDs :\ 

187""", file=fd) 

188 

189 for raftName, perRaftData in raftData["rafts"].items(): 

190 try: 

191 raftCcdData = parseYamlOnPath(f"{raftName}.yaml", searchPath)[raftName] 

192 except FileNotFoundError: 

193 print("Unable to load CCD descriptions for raft %s" % raftName, file=sys.stderr) 

194 continue 

195 

196 try: 

197 detectorType = raftCcdData["detectorType"] 

198 except KeyError: 

199 raise RuntimeError("Unable to lookup detector type for %s" % raftName) 

200 

201 try: 

202 _ccds = cameraSkl['RAFT_%s' % detectorType]["ccds"] # describe this *type* of raft 

203 except KeyError: 

204 raise RuntimeError("No raft for detector type %s" % detectorType) 

205 

206 try: 

207 sensorTypes = raftCcdData["sensorTypes"] 

208 except KeyError: 

209 sensorTypes = None 

210 

211 # only include CCDs in the raft for which we have a serial 

212 # (the value isn't checked) 

213 ccds = {} 

214 for ccdName in raftCcdData["ccdSerials"]: 

215 try: 

216 ccds[ccdName] = _ccds[ccdName] 

217 except KeyError: 

218 raise RuntimeError("Unable to look up CCD %s in %s" % 

219 (ccdName, 'RAFT_%s' % detectorType)) 

220 del _ccds 

221 

222 try: 

223 amps = cameraSkl['CCD_%s' % detectorType]["amplifiers"] # describe this *type* of ccd 

224 except KeyError: 

225 raise RuntimeError("Unable to lookup amplifiers for CCD type CCD_%s" % detectorType) 

226 

227 try: 

228 crosstalkCoeffs = ccdData["crosstalk"][detectorType] 

229 except KeyError: 

230 crosstalkCoeffs = None 

231 

232 nindent += 1 

233 

234 raftOffset = perRaftData["offset"] 

235 id0 = perRaftData['id0'] 

236 try: 

237 raftYaw = perRaftData['yaw'] 

238 except KeyError: 

239 raftYaw = 0. 

240 geometryWithinRaft = raftCcdData.get('geometryWithinRaft', {}) 

241 

242 for ccdName, ccdLayout in ccds.items(): 

243 if ccdName in geometryWithinRaft: 

244 doffset = geometryWithinRaft[ccdName]['offset'] 

245 yaw = geometryWithinRaft[ccdName]['yaw'] + raftYaw 

246 else: 

247 doffset = (0.0, 0.0,) 

248 yaw = None 

249 

250 print(indent(), "%s_%s : " % (raftNameMap.get(raftName, raftName), ccdName), file=fd) 

251 nindent += 1 

252 print(indent(), "<< : *%s_%s" % (ccdName, detectorType), file=fd) 

253 if sensorTypes is not None: 

254 print(indent(), "detectorType : %i" % (sensorTypes[ccdName]), file=fd) 

255 print(indent(), "id : %s" % (id0 + ccdLayout['id']), file=fd) 

256 print(indent(), "serial : %s" % (raftCcdData['ccdSerials'][ccdName]), file=fd) 

257 print(indent(), "physicalType : %s" % (detectorType), file=fd) 

258 print(indent(), "refpos : %s" % (ccdLayout['refpos']), file=fd) 

259 ccdLayoutOffset = applyRaftYaw([el1+el2 for el1, el2 in zip(ccdLayout['offset'], doffset)], 

260 raftYaw) 

261 print(indent(), "offset : [%g, %g]" % (ccdLayoutOffset[0] + raftOffset[0], 

262 ccdLayoutOffset[1] + raftOffset[1]), 

263 file=fd) 

264 if yaw is not None: 

265 print(indent(), "yaw : %g" % (yaw), file=fd) 

266 

267 if crosstalkCoeffs is not None: 

268 print(indent(), "crosstalk : [", file=fd) 

269 nindent += 1 

270 print(indent(), file=fd, end="") 

271 for iAmp in amps: 

272 for jAmp in amps: 

273 print("%11.3e," % crosstalkCoeffs[iAmp][jAmp], file=fd, end='') 

274 print(file=fd, end="\n" + indent()) 

275 nindent -= 1 

276 print("]", file=fd) 

277 

278 try: 

279 amplifierData = raftCcdData['amplifiers'][ccdName] 

280 except KeyError: 

281 raise RuntimeError("Unable to lookup amplifier data for detector %s_%s" % 

282 (raftName, ccdName)) 

283 

284 print(indent(), "amplifiers :", file=fd) 

285 nindent += 1 

286 for ampName, ampData in amps.items(): 

287 print(indent(), "%s :" % ampName, file=fd) 

288 

289 if ampName not in amplifierData: 

290 raise RuntimeError("Unable to lookup amplifier data for amp %s in detector %s_%s" % 

291 (ampName, raftName, ccdName)) 

292 

293 nindent += 1 

294 print(indent(), "<< : *%s_%s" % (ampName, detectorType), file=fd) 

295 print(indent(), "gain : %g" % (amplifierData[ampName]['gain']), file=fd) 

296 print(indent(), "readNoise : %g" % (amplifierData[ampName]['readNoise']), file=fd) 

297 saturation = amplifierData[ampName].get('saturation') 

298 if saturation: # if known, override the per-CCD-type default from cameraHeader.yaml 

299 print(indent(), "saturation : %g" % (saturation), file=fd) 

300 nindent -= 1 

301 nindent -= 1 

302 

303 nindent -= 1 

304 

305 nindent -= 1 

306 

307 

308def main(): 

309 args = build_argparser().parse_args() 

310 

311 try: 

312 generateCamera(args.outputFile, args.path) 

313 except Exception as e: 

314 print(f"{e}", file=sys.stderr) 

315 return 1 

316 return 0