Debian Codegraph @

gavo/helpers/anet.py

raw
1 """
2 Code to obtain WCS headers for FITS files using astrometry.net
3
4 Astrometry.net has oodles of configurable parameters. Some of
5 them can be passed in via the solverParameters argument to getWCSFieldsFor,
6 a dictionary with keys including:
7
8 indices
9 (default: ``index-*.fits``, meaning all indices in your default index dir)
10 The file names from anet's index directory you want to have used.
11 glob patterns are expanded, but no recursion takes place.
12
13 This could be something like::
14
15 ["index-4211.fits", "index-4210.fits", "index-4209.fits"]
16
17 for largeish images or::
18
19 ["index-4203-*.fits", "index-4202-*.fits"]
20
21 for small ones. You can also give absolute path names for custom
22 indices that live, e.g., in your resource directory.
23
24 total_timelimit
25 (defaults to 600) -- number of seconds after which the anet run
26 should cancel itself.
27
28 tweak
29 (defaults to True) -- try to obtain a polynomic correction to the
30 entire image after obtaining a solution? This can go wrong in
31 particular for exposures with many objects, so you might want to
32 set it to off for such cases.
33
34 fields
35 (default to 1) -- FITS extension to work on
36
37 endob
38 (defaults to not given) -- last object to be processed. You don't want to
39 raise this too high. The library will only pass on 10 objects at a
40 time anyway, but going too high here will waste lots of time on images
41 that are probably not going to resolve anyway.
42
43 lower_pix
44 (defaults to not given) -- smallest permissible pixel size in arcsecs. If
45 at all possible, constrain this for much better results.
46
47 upper_pix
48 (defaults to not given) -- largest permissible pixel size in arcsecs.
49 See lower_pix.
50
51 plots
52 (defaults to False) -- generate all kinds of pretty plots?
53
54 downsample
55 (defaults to not given) -- factor to downsample the image before
56 trying to solve. This may be necessary when not using source-extractor,
57 and it should be something like 2, 3, or 4.
58 """
59
60 #c Copyright 2008-2025, the GAVO project <[email protected]>
61 #c
62 #c This program is free software, covered by the GNU GPL. See the
63 #c COPYING file in the source distribution.
64
65
66 import glob
67 import gzip
68 import os
69 import shutil
70 import subprocess
71
72 from gavo import base
73 from gavo import utils
74 from gavo.utils import fitstools
75 from gavo.utils import pyfits
76
77 __docformat__ = "restructuredtext en"
78
79 anetIndexPath = "/usr/local/astrometry/data"
80
81
82 PARAM_DEFAULTS = {
83 "total_timelimit": 600,
84 "fields": "1",
85 "endob": None,
86 "lower_pix": None,
87 "upper_pix": None,
88 "tweak": True,
89 "pix_units": "app",
90 "plots": False,
91 "downsample": None,
92 }
93
94
95 class Error(base.Error):
96 pass
97
98 class NotSolved(Error):
99 pass
100
101 class ObjectNotFound(Error):
102 pass
103
104 class ShellCommandFailed(Error):
105 def __init__(self, msg, retcode):
106 Error.__init__(self, msg)
107 self.msg, self.retcode = msg, retcode
108
109 def __str__(self):
110 return "External program failure (%s). Program output: %s"%(
111 self.retcode, self.msg)
112
113
114 def _feedFile(origDir, fName):
115 """links fName to "in.fits" in the sandbox.
116
117 If fName ends with .gz, the function assumes it's a gzipped file and
118 unzips it to in.fits instead.
119 """
120 srcName = os.path.join(origDir, fName)
121 destName = "img.fits"
122 if fName.endswith(".gz"):
123 with open(destName, "wb") as destF:
124 utils.cat(gzip.open(srcName), destF)
125 else:
126 os.symlink(srcName, destName)
127
128
129 def _runShellCommand(cmd, args):
130 with open("lastCommand.log", "a") as logF:
131 logF.write("\n\n================\nNow running: %s\n\n"%
132 " ".join([cmd]+args))
133 logF.flush()
134 proc = subprocess.Popen([cmd]+args, stdout=logF,
135 stderr=subprocess.STDOUT)
136 proc.communicate()
137
138 if proc.returncode==-2:
139 raise KeyboardInterrupt("Child was siginted")
140 elif proc.returncode:
141 raise ShellCommandFailed(open("lastCommand.log").read(), proc.returncode)
142
143
144 def _copyCurrentTree(copyTo):
145 if copyTo is not None:
146 try:
147 shutil.rmtree(copyTo)
148 except os.error:
149 pass
150 shutil.copytree(".", copyTo)
151
152
153 # Minimal configuration for source-extractor for anet use.
154 # Do not override values in here in your sourceExtractorConfig-s.
155 _ANET_SX_STUB = """# source-extractor control file for astrometry.net
156 CATALOG_TYPE FITS_1.0
157 # The output file name
158 CATALOG_NAME img.axy
159 # The name of the file containing _ANET_SX_PARAM
160 PARAMETERS_NAME anet.param
161 FILTER_NAME anet.filter
162 """
163
164 # export column spec for source-extractor; referenced in _ANET_SX_STUB
165 _ANET_SX_PARAM = """X_IMAGE
166 Y_IMAGE
167 MAG_ISO
168 FLUX_AUTO
169 ELONGATION
170 """
171
172 # Blatantly stolen from anet...
173 _ANET_SX_FILTER = """CONV NORM
174 # 5x5 convolution mask of a gaussian PSF with FWHM = 2.0 pixels.
175 0.006319 0.040599 0.075183 0.040599 0.006319
176 0.040599 0.260856 0.483068 0.260856 0.040599
177 0.075183 0.483068 0.894573 0.483068 0.075183
178 0.040599 0.260856 0.483068 0.260856 0.040599
179 0.006319 0.040599 0.075183 0.040599 0.006319
180 """
181
182
183 def _createSourceExtractorFiles(sourceExtractorControl):
184 with open("anet.control", "w") as f:
185 f.write(_ANET_SX_STUB+sourceExtractorControl)
186 with open("anet.param", "w") as f:
187 f.write(_ANET_SX_PARAM)
188 with open("anet.filter", "w") as f:
189 f.write(_ANET_SX_FILTER)
190
191
192 def _extractSources(filterFunc=None):
193 """does source extraction using source-extractor.
194
195 If filterFunc is not None, it is called before sorting the extracted
196 objects. It must change the file named in the argument in place.
197 """
198 _runShellCommand("source-extractor", ["-c", "anet.control", "img.fits"])
199 if filterFunc is not None:
200 filterFunc("img.axy")
201
202
203 _PARAMETER_MAP = [
204 ("total_timelimit", "--cpulimit"),
205 ("fields", "--fields"),
206 ("lower_pix", "--scale-low"),
207 ("upper_pix", "--scale-high"),
208 ("pix_units", "--scale-units"),
209 ("endob", "--depth"),
210 ("downsample", "--downsample"),
211 ]
212
213 def _addArgsFor(actPars, args):
214 if not actPars["tweak"]:
215 args.append("--no-tweak")
216 if not actPars["plots"]:
217 args.append("--no-plots")
218 for key, opthead in _PARAMETER_MAP:
219 if actPars[key] is not None:
220 args.extend([opthead, str(actPars[key])])
221
222
223 def _solveField(fName,
224 solverParameters,
225 sourceExtractorControl,
226 objectFilter,
227 indexPath,
228 verbose):
229 """tries to solve an image anet's using solve-field.
230
231 See _resolve for the meaning of the arguments.
232 """
233 args = ["--continue"]
234 objectSource = "img.fits"
235 if sourceExtractorControl is not None:
236 _createSourceExtractorFiles(sourceExtractorControl)
237 if sourceExtractorControl==None:
238 pass
239 elif sourceExtractorControl=="":
240 args.extend(["--use-source-extractor"])
241 else:
242 _extractSources(objectFilter)
243 width, height = fitstools.getPrimarySize("img.fits")
244 args.extend(["--x-column", "X_IMAGE",
245 "--y-column", "Y_IMAGE",
246 "--sort-column", "FLUX_AUTO",
247 "--use-source-extractor",
248 "--width", str(width), "--height", str(height)])
249 objectSource = "img.axy"
250 args.append("-v")
251
252 with open("backend.cfg", "w") as backendCfg:
253 if "indices" in solverParameters:
254 backendCfg.write(f"add_path {indexPath}\n")
255 for indF in solverParameters["indices"]:
256 fullPath = os.path.join(indexPath, indF)
257 for fName in glob.glob(fullPath):
258 backendCfg.write("index %s\n"%fName)
259 backendCfg.write("inparallel")
260
261 else:
262 backendCfg.write(f"add_path {indexPath}\nautoindex\n")
263
264 args.extend(["--backend-config", "backend.cfg"])
265
266 actPars = PARAM_DEFAULTS.copy()
267 actPars.update(solverParameters)
268 _addArgsFor(actPars, args)
269
270 args.append(objectSource)
271 if verbose:
272 print("Running %s %s"%("solve-field", " ".join(args)))
273 _runShellCommand("solve-field", args)
274
275 # staggered solving: This seemed like a good idea at some point but
276 # now probably no longer is.
277 # minInd, maxInd = int(actPars["startob"]), int(actPars["endob"])
278 # curStart = minInd
279 # while True:
280 # if curStart+10>maxInd:
281 # break
282 # args.extend(["--depth", "%s-%s"%(curStart+1, curStart+15), "img.fits"])
283 # _runShellCommand(solverBin, args)
284 # if os.path.exists("img.solved"):
285 # break
286 # curStart += 5
287 # args[-3:] = []
288
289
290 def _resolve(fName,
291 solverParameters,
292 sourceExtractorControl,
293 objectFilter,
294 copyTo,
295 indexPath,
296 verbose):
297 """runs the astrometric calibration pipeline.
298
299 solverParameters is a dictionary; most keys in it are simply turned
300 into command line options of solve-field.
301
302 This function litters the working directory with all kinds of files and does
303 not clean up, so you'd better run it in a sandbox.
304
305 It raises a NotSolved exception if no solution could be found; otherwise
306 you should find the solution in img.wcs.
307 """
308 if "_preparationFunction" in solverParameters:
309 solverParameters["_preparationFunction"]()
310 try:
311 _solveField(fName,
312 solverParameters,
313 sourceExtractorControl,
314 objectFilter,
315 indexPath,
316 verbose)
317 except Exception:
318 _copyCurrentTree(copyTo)
319 raise
320 _copyCurrentTree(copyTo)
321 if os.path.exists("img.solved"):
322 return
323 raise NotSolved(fName)
324
325
326 def getWCSFieldsFor(fName,
327 solverParameters,
328 sourceExtractorControl,
329 objectFilter,
330 copyTo,
331 indexPath,
332 verbose):
333 """returns a pyfits cardlist for the WCS fields on fName.
334
335 solverParameters is a dictionary mapping solver keys to their values,
336 sourceExtractorControl is a script for source-extractor,
337 and its presence means that
338 source-extractor should be used for source extraction rather than what anet
339 has built in. objectFilter is a function that is called with the
340 name of the FITS with the extracted sources. It can remove or add
341 sources to that file before astrometry.net tries to match.
342
343 To see what solverParameters are available, check the module docstring.
344 """
345 try:
346 with utils.sandbox() as origDir:
347 _feedFile(origDir, fName)
348 _resolve(fName,
349 solverParameters=solverParameters,
350 sourceExtractorControl=sourceExtractorControl,
351 objectFilter=objectFilter,
352 copyTo=copyTo,
353 indexPath=indexPath,
354 verbose=verbose)
355 return pyfits.getheader("img.wcs").cards
356 except NotSolved:
357 return None