Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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 

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

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

124 

125 if isinstance(path, str): 

126 path = path.split(":") 

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

128 

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

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

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

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

133 

134 # See if we have an override of the name 

135 try: 

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

137 except FileNotFoundError: 

138 nameOverride = None 

139 else: 

140 nameOverride = nameYaml["name"] 

141 

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

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

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

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

146 if nameOverride: 

147 with open(inputHeader) as infd: 

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

149 replaced = False 

150 for line in infd: 

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

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

153 replaced = True 

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

155 if not replaced: 

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

157 f" to replace in {inputHeader}") 

158 else: 

159 shutil.copyfile(inputHeader, cameraFile) 

160 

161 nindent = 0 # current number of indents 

162 

163 def indent(): 

164 """Return the current indent string""" 

165 dindent = 2 # number of spaces per indent 

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

167 

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

169 print(""" 

170# 

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

172# (and known!) coordinate systems 

173#""", file=fd) 

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

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

176 

177 print(""" 

178# 

179# Define our specific devices 

180# 

181# All the CCDs present in this file 

182# 

183CCDs :\ 

184""", file=fd) 

185 

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

187 try: 

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

189 except FileNotFoundError: 

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

191 continue 

192 

193 try: 

194 detectorType = raftCcdData["detectorType"] 

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

196 

197 try: 

198 sensorTypes = raftCcdData["sensorTypes"] 

199 except KeyError: 

200 sensorTypes = None 

201 

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

203 # (the value isn't checked) 

204 ccds = {} 

205 for ccdName in raftCcdData["ccdSerials"]: 

206 ccds[ccdName] = _ccds[ccdName] 

207 del _ccds 

208 

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

210 except KeyError: 

211 raise RuntimeError("Unknown detector type %s" % detectorType) 

212 

213 try: 

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

215 except KeyError: 

216 crosstalkCoeffs = None 

217 

218 nindent += 1 

219 

220 raftOffset = perRaftData["offset"] 

221 id0 = perRaftData['id0'] 

222 try: 

223 raftYaw = perRaftData['yaw'] 

224 except KeyError: 

225 raftYaw = 0. 

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

227 

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

229 if ccdName in geometryWithinRaft: 

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

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

232 else: 

233 doffset = (0.0, 0.0,) 

234 yaw = None 

235 

236 print(indent(), "%s_%s : " % (raftName.split('_')[0], ccdName), file=fd) 

237 nindent += 1 

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

239 if sensorTypes is not None: 

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

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

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

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

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

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

246 raftYaw) 

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

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

249 file=fd) 

250 if yaw is not None: 

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

252 

253 if crosstalkCoeffs is not None: 

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

255 nindent += 1 

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

257 for iAmp in amps: 

258 for jAmp in amps: 

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

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

261 nindent -= 1 

262 print("]", file=fd) 

263 

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

265 nindent += 1 

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

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

268 

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

270 

271 nindent += 1 

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

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

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

275 nindent -= 1 

276 nindent -= 1 

277 

278 nindent -= 1 

279 

280 nindent -= 1 

281 

282 

283def main(): 

284 args = build_argparser().parse_args() 

285 

286 try: 

287 generateCamera(args.outputFile, args.path) 

288 except Exception as e: 

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

290 return 1 

291 return 0