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# 

2# LSST Data Management System 

3# Copyright 2012,2015 LSST Corporation. 

4# 

5# This product includes software developed by the 

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

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 <http://www.lsstcorp.org/LegalNotices/>. 

21# 

22import os 

23import re 

24 

25 

26from lsst.daf.butler import ButlerURI, Formatter 

27from astro_metadata_translator import fix_header, DecamTranslator 

28from lsst.afw.fits import readMetadata 

29from lsst.pipe.tasks.ingest import ParseTask, IngestTask, IngestArgumentParser 

30from lsst.obs.base.ingest import RawFileData 

31import lsst.obs.base 

32 

33__all__ = ["DecamRawIngestTask", "DecamIngestArgumentParser", "DecamIngestTask", "DecamParseTask"] 

34 

35 

36class DecamRawIngestTask(lsst.obs.base.RawIngestTask): 

37 """Task for ingesting raw DECam data into a Gen3 Butler repository. 

38 """ 

39 def extractMetadata(self, filename: ButlerURI) -> RawFileData: 

40 datasets = [] 

41 try: 

42 with filename.as_local() as local_file: 

43 fitsData = lsst.afw.fits.Fits(local_file.ospath, 'r') 

44 # NOTE: The primary header (HDU=0) does not contain detector data. 

45 for i in range(1, fitsData.countHdus()): 

46 fitsData.setHdu(i) 

47 header = fitsData.readMetadata() 

48 if header['CCDNUM'] > 62: # ignore the guide CCDs 

49 continue 

50 datasets.append(self._calculate_dataset_info(header, filename)) 

51 except Exception as e: 

52 self.log.debug("Problem extracting metadata from %s: %s", filename, e) 

53 # Indicate to the caller that we failed to read. 

54 # Do not try to ingest partial contents of file. 

55 datasets = [] 

56 formatterClass = Formatter 

57 instrument = None 

58 self._on_metadata_failure(filename, e) 

59 if self.config.failFast: 

60 raise RuntimeError(f"Problem extracting metadata for file {filename}") from e 

61 else: 

62 # The data model currently assumes that whilst multiple datasets 

63 # can be associated with a single file, they must all share the 

64 # same formatter. 

65 instrument, formatterClass = self._determine_instrument_formatter(datasets[0].dataId, filename) 

66 if instrument is None: 

67 datasets = [] 

68 

69 self.log.debug(f"Found images for {len(datasets)} detectors in {filename}") 

70 return RawFileData(datasets=datasets, filename=filename, 

71 FormatterClass=formatterClass, 

72 instrumentClass=type(instrument)) 

73 

74 

75class DecamIngestArgumentParser(IngestArgumentParser): 

76 """Gen2 DECam ingest additional arguments. 

77 """ 

78 

79 def __init__(self, *args, **kwargs): 

80 super(DecamIngestArgumentParser, self).__init__(*args, **kwargs) 

81 self.add_argument("--filetype", default="raw", choices=["instcal", "raw"], 

82 help="Data processing level of the files to be ingested") 

83 

84 

85class DecamIngestTask(IngestTask): 

86 """Gen2 DECam file ingest task. 

87 """ 

88 ArgumentParser = DecamIngestArgumentParser 

89 

90 def __init__(self, *args, **kwargs): 

91 super(DecamIngestTask, self).__init__(*args, **kwargs) 

92 

93 def run(self, args): 

94 """Ingest all specified files and add them to the registry 

95 """ 

96 if args.filetype == "instcal": 

97 root = args.input 

98 with self.register.openRegistry(root, create=args.create, dryrun=args.dryrun) as registry: 

99 for infile in args.files: 

100 fileInfo, hduInfoList = self.parse.getInfo(infile, args.filetype) 

101 if len(hduInfoList) > 0: 

102 outfileInstcal = os.path.join(root, self.parse.getDestination(args.butler, 

103 hduInfoList[0], 

104 infile, "instcal")) 

105 outfileDqmask = os.path.join(root, self.parse.getDestination(args.butler, 

106 hduInfoList[0], infile, 

107 "dqmask")) 

108 outfileWtmap = os.path.join(root, self.parse.getDestination(args.butler, 

109 hduInfoList[0], infile, 

110 "wtmap")) 

111 

112 ingestedInstcal = self.ingest(fileInfo["instcal"], outfileInstcal, 

113 mode=args.mode, dryrun=args.dryrun) 

114 ingestedDqmask = self.ingest(fileInfo["dqmask"], outfileDqmask, 

115 mode=args.mode, dryrun=args.dryrun) 

116 ingestedWtmap = self.ingest(fileInfo["wtmap"], outfileWtmap, 

117 mode=args.mode, dryrun=args.dryrun) 

118 

119 if not (ingestedInstcal or ingestedDqmask or ingestedWtmap): 

120 continue 

121 

122 for info in hduInfoList: 

123 self.register.addRow(registry, info, dryrun=args.dryrun, create=args.create) 

124 

125 elif args.filetype == "raw": 

126 IngestTask.run(self, args) 

127 

128 

129class DecamParseTask(ParseTask): 

130 """Parse an image filename to get the required information to 

131 put the file in the correct location and populate the registry. 

132 """ 

133 

134 _translatorClass = DecamTranslator 

135 

136 def __init__(self, *args, **kwargs): 

137 super(ParseTask, self).__init__(*args, **kwargs) 

138 

139 self.expnumMapper = None 

140 

141 # Note that these should be syncronized with the fields in 

142 # root.register.columns defined in config/ingest.py 

143 self.instcalPrefix = "instcal" 

144 self.dqmaskPrefix = "dqmask" 

145 self.wtmapPrefix = "wtmap" 

146 

147 def _listdir(self, path, prefix): 

148 for file in os.listdir(path): 

149 fileName = os.path.join(path, file) 

150 md = readMetadata(fileName) 

151 fix_header(md, translator_class=self._translatorClass) 

152 if "EXPNUM" not in md: 

153 return 

154 expnum = md["EXPNUM"] 

155 if expnum not in self.expnumMapper: 

156 self.expnumMapper[expnum] = {self.instcalPrefix: None, 

157 self.wtmapPrefix: None, 

158 self.dqmaskPrefix: None} 

159 self.expnumMapper[expnum][prefix] = fileName 

160 

161 def buildExpnumMapper(self, basepath): 

162 """Extract exposure numbers from filenames to set self.expnumMapper 

163 

164 Parameters 

165 ---------- 

166 basepath : `str` 

167 Location on disk of instcal, dqmask, and wtmap subdirectories. 

168 """ 

169 self.expnumMapper = {} 

170 

171 instcalPath = basepath 

172 dqmaskPath = re.sub(self.instcalPrefix, self.dqmaskPrefix, instcalPath) 

173 wtmapPath = re.sub(self.instcalPrefix, self.wtmapPrefix, instcalPath) 

174 if instcalPath == dqmaskPath: 

175 raise RuntimeError("instcal and mask directories are the same") 

176 if instcalPath == wtmapPath: 

177 raise RuntimeError("instcal and weight map directories are the same") 

178 

179 if not os.path.isdir(dqmaskPath): 

180 raise OSError("Directory %s does not exist" % (dqmaskPath)) 

181 if not os.path.isdir(wtmapPath): 

182 raise OSError("Directory %s does not exist" % (wtmapPath)) 

183 

184 # Traverse each directory and extract the expnums 

185 for path, prefix in zip((instcalPath, dqmaskPath, wtmapPath), 

186 (self.instcalPrefix, self.dqmaskPrefix, self.wtmapPrefix)): 

187 self._listdir(path, prefix) 

188 

189 def getInfo(self, filename, filetype="raw"): 

190 """Get metadata header info from multi-extension FITS decam image file. 

191 

192 The science pixels, mask, and weight (inverse variance) are 

193 stored in separate files each with a unique name but with a 

194 common unique identifier EXPNUM in the FITS header. We have 

195 to aggregate the 3 filenames for a given EXPNUM and return 

196 this information along with that returned by the base class. 

197 

198 Parameters 

199 ---------- 

200 filename : `str` 

201 Image file to retrieve info from. 

202 filetype : `str` 

203 One of "raw" or "instcal". 

204 

205 Returns 

206 ------- 

207 phuInfo : `dict` 

208 Primary header unit info. 

209 infoList : `list` of `dict` 

210 Info for the other HDUs. 

211 

212 Notes 

213 ----- 

214 For filetype="instcal", we expect a directory structure that looks 

215 like the following: 

216 

217 .. code-block:: none 

218 

219 dqmask/ 

220 instcal/ 

221 wtmap/ 

222 

223 The user creates the registry by running: 

224 

225 .. code-block:: none 

226 

227 ingestImagesDecam.py outputRepository --filetype=instcal --mode=link instcal/*fits 

228 """ 

229 if filetype == "instcal": 

230 if self.expnumMapper is None: 

231 self.buildExpnumMapper(os.path.dirname(os.path.abspath(filename))) 

232 

233 # Note that phuInfo will have 

234 # 'side': 'X', 'ccd': 0 

235 phuInfo, infoList = super(DecamParseTask, self).getInfo(filename) 

236 expnum = phuInfo["visit"] 

237 phuInfo[self.instcalPrefix] = self.expnumMapper[expnum][self.instcalPrefix] 

238 phuInfo[self.dqmaskPrefix] = self.expnumMapper[expnum][self.dqmaskPrefix] 

239 phuInfo[self.wtmapPrefix] = self.expnumMapper[expnum][self.wtmapPrefix] 

240 for info in infoList: 

241 expnum = info["visit"] 

242 info[self.instcalPrefix] = self.expnumMapper[expnum][self.instcalPrefix] 

243 info[self.dqmaskPrefix] = self.expnumMapper[expnum][self.dqmaskPrefix] 

244 info[self.wtmapPrefix] = self.expnumMapper[expnum][self.wtmapPrefix] 

245 

246 elif filetype == "raw": 

247 phuInfo, infoList = super(DecamParseTask, self).getInfo(filename) 

248 for info in infoList: 

249 info[self.instcalPrefix] = "" 

250 info[self.dqmaskPrefix] = "" 

251 info[self.wtmapPrefix] = "" 

252 

253 # Some data IDs can not be extracted from the zeroth extension 

254 # of the MEF. Add them so Butler does not try to find them 

255 # in the registry which may still yet to be created. 

256 for key in ("ccdnum", "hdu", "ccd", "calib_hdu"): 

257 if key not in phuInfo: 

258 phuInfo[key] = 0 

259 

260 return phuInfo, infoList 

261 

262 def getDestination(self, butler, info, filename, filetype="raw"): 

263 """Get destination for the file 

264 

265 Parameters 

266 ---------- 

267 butler : `lsst.daf.persistence.Butler` 

268 Data butler. 

269 info : data ID 

270 File properties, used as dataId for the butler. 

271 filename : `str` 

272 Input filename. 

273 

274 Returns 

275 ------- 

276 raw : `str` 

277 Destination filename. 

278 """ 

279 raw = butler.get("%s_filename"%(filetype), info)[0] 

280 # Ensure filename is devoid of cfitsio directions about HDUs 

281 c = raw.find("[") 

282 if c > 0: 

283 raw = raw[:c] 

284 return raw