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

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#
25__all__ = ("main",)
27import argparse
28import os
29import sys
30import shutil
31import yaml
32import numpy as np
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
43 raise FileNotFoundError("Unable to find %s on path %s" % (fileName, ":".join(searchPath)))
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
55def build_argparser():
56 """Construct an argument parser for the ``generateCamera.py`` script.
58 Returns
59 -------
60 argparser : `argparse.ArgumentParser`
61 The argument parser that defines the ``translate_header.py``
62 command-line interface.
63 """
65 parser = argparse.ArgumentParser(description="""
66 Generate a camera.yaml file for a camera by assembling descriptions of
67 rafts, sensors, etc.
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 """)
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)
79 return parser
82def applyRaftYaw(offset, raftYaw):
83 """Apply raft yaw angle to internal offsets of the CCDs.
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.
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
107def generateCamera(cameraFile, path):
108 """Generate a combined camera YAML definition from component parts.
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'}
125 if not cameraFile.endswith(".yaml"):
126 raise RuntimeError(f"Output file name ({cameraFile}) does not end with .yaml")
128 if isinstance(path, str):
129 path = path.split(":")
130 searchPath = [os.path.join(cameraFileDir, d) for d in path]
132 cameraSkl = parseYamlOnPath("cameraHeader.yaml", searchPath)
133 cameraTransforms = parseYamlOnPath("cameraTransforms.yaml", searchPath)
134 raftData = parseYamlOnPath("rafts.yaml", searchPath)
135 ccdData = parseYamlOnPath("ccdData.yaml", searchPath)
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"]
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)
164 nindent = 0 # current number of indents
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 " "
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)
180 print("""
181#
182# Define our specific devices
183#
184# All the CCDs present in this file
185#
186CCDs :\
187""", file=fd)
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
196 try:
197 detectorType = raftCcdData["detectorType"]
198 _ccds = cameraSkl['RAFT_%s' % detectorType]["ccds"] # describe this *type* of raft
200 try:
201 sensorTypes = raftCcdData["sensorTypes"]
202 except KeyError:
203 sensorTypes = None
205 # only include CCDs in the raft for which we have a serial
206 # (the value isn't checked)
207 ccds = {}
208 for ccdName in raftCcdData["ccdSerials"]:
209 ccds[ccdName] = _ccds[ccdName]
210 del _ccds
212 amps = cameraSkl['CCD_%s' % detectorType]["amplifiers"] # describe this *type* of ccd
213 except KeyError:
214 raise RuntimeError("Unknown detector type %s" % detectorType)
216 try:
217 crosstalkCoeffs = ccdData["crosstalk"][detectorType]
218 except KeyError:
219 crosstalkCoeffs = None
221 nindent += 1
223 raftOffset = perRaftData["offset"]
224 id0 = perRaftData['id0']
225 try:
226 raftYaw = perRaftData['yaw']
227 except KeyError:
228 raftYaw = 0.
229 geometryWithinRaft = raftCcdData.get('geometryWithinRaft', {})
231 for ccdName, ccdLayout in ccds.items():
232 if ccdName in geometryWithinRaft:
233 doffset = geometryWithinRaft[ccdName]['offset']
234 yaw = geometryWithinRaft[ccdName]['yaw'] + raftYaw
235 else:
236 doffset = (0.0, 0.0,)
237 yaw = None
239 print(indent(), "%s_%s : " % (raftNameMap.get(raftName, raftName), ccdName), file=fd)
240 nindent += 1
241 print(indent(), "<< : *%s_%s" % (ccdName, detectorType), file=fd)
242 if sensorTypes is not None:
243 print(indent(), "detectorType : %i" % (sensorTypes[ccdName]), file=fd)
244 print(indent(), "id : %s" % (id0 + ccdLayout['id']), file=fd)
245 print(indent(), "serial : %s" % (raftCcdData['ccdSerials'][ccdName]), file=fd)
246 print(indent(), "physicalType : %s" % (detectorType), file=fd)
247 print(indent(), "refpos : %s" % (ccdLayout['refpos']), file=fd)
248 ccdLayoutOffset = applyRaftYaw([el1+el2 for el1, el2 in zip(ccdLayout['offset'], doffset)],
249 raftYaw)
250 print(indent(), "offset : [%g, %g]" % (ccdLayoutOffset[0] + raftOffset[0],
251 ccdLayoutOffset[1] + raftOffset[1]),
252 file=fd)
253 if yaw is not None:
254 print(indent(), "yaw : %g" % (yaw), file=fd)
256 if crosstalkCoeffs is not None:
257 print(indent(), "crosstalk : [", file=fd)
258 nindent += 1
259 print(indent(), file=fd, end="")
260 for iAmp in amps:
261 for jAmp in amps:
262 print("%11.3e," % crosstalkCoeffs[iAmp][jAmp], file=fd, end='')
263 print(file=fd, end="\n" + indent())
264 nindent -= 1
265 print("]", file=fd)
267 print(indent(), "amplifiers :", file=fd)
268 nindent += 1
269 for ampName, ampData in amps.items():
270 amplifierData = raftCcdData['amplifiers'][ccdName]
272 print(indent(), "%s :" % ampName, file=fd)
274 nindent += 1
275 print(indent(), "<< : *%s_%s" % (ampName, detectorType), file=fd)
276 print(indent(), "gain : %g" % (amplifierData[ampName]['gain']), file=fd)
277 print(indent(), "readNoise : %g" % (amplifierData[ampName]['readNoise']), file=fd)
278 nindent -= 1
279 nindent -= 1
281 nindent -= 1
283 nindent -= 1
286def main():
287 args = build_argparser().parse_args()
289 try:
290 generateCamera(args.outputFile, args.path)
291 except Exception as e:
292 print(f"{e}", file=sys.stderr)
293 return 1
294 return 0