| 1 |
""" |
| 2 |
An abstract processor and some helping code. |
| 3 |
|
| 4 |
Currently, I assume a plain text interface for those. It might be |
| 5 |
a good idea to use the event mechanism here. |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
import io |
| 15 |
import os |
| 16 |
import sys |
| 17 |
import textwrap |
| 18 |
import threading |
| 19 |
import traceback |
| 20 |
from contextlib import contextmanager |
| 21 |
|
| 22 |
from PIL import Image |
| 23 |
|
| 24 |
from gavo import base |
| 25 |
from gavo import rsc |
| 26 |
from gavo import utils |
| 27 |
from gavo.helpers import anet |
| 28 |
from gavo.helpers import fitstricks |
| 29 |
from gavo.utils import fitstools |
| 30 |
from gavo.utils import pyfits |
| 31 |
|
| 32 |
|
| 33 |
# matplotlib is an expensive import. Only do that if we're sure |
| 34 |
# we need it. |
| 35 |
matplotlib = utils.DeferredImport("matplotlib", "import matplotlib") |
| 36 |
figure = utils.DeferredImport("figure", "from matplotlib import figure") |
| 37 |
|
| 38 |
_MPL_LOCK = threading.RLock() |
| 39 |
@contextmanager |
| 40 |
def matplotlibLock(): |
| 41 |
_MPL_LOCK.acquire() |
| 42 |
matplotlib.use("Agg") |
| 43 |
try: |
| 44 |
yield |
| 45 |
finally: |
| 46 |
_MPL_LOCK.release() |
| 47 |
|
| 48 |
|
| 49 |
class CannotComputeHeader(Exception): |
| 50 |
"""is raised when no FITS header was generated by a HeaderProcessor. |
| 51 |
|
| 52 |
Specifically, this is what gets raised when ``_getHeader`` returns ``None``. |
| 53 |
""" |
| 54 |
|
| 55 |
|
| 56 |
class FileProcessor(object): |
| 57 |
"""An abstract base for a source file processor. |
| 58 |
|
| 59 |
In concrete classes, you need to define a ``process(accref)`` method |
| 60 |
receiving a source as returned by the dd (i.e., usually an inputsDir-relative |
| 61 |
file name). |
| 62 |
|
| 63 |
You can override the method ``_createAuxiliaries(dataDesc)`` to compute |
| 64 |
things like source catalogues, etc. Thus, you should not need to |
| 65 |
override the constructor. |
| 66 |
|
| 67 |
These objects are usually constructed thorough ``api.procmain`` as |
| 68 |
discussed in :dachsdoc:`processing.html`. |
| 69 |
""" |
| 70 |
inputsDir = base.getConfig("inputsDir") |
| 71 |
|
| 72 |
def __init__(self, opts, dd): |
| 73 |
self.opts, self.dd = opts, dd |
| 74 |
self._createAuxiliaries(dd) |
| 75 |
|
| 76 |
def _createAuxiliaries(self, dd): |
| 77 |
# There's been a typo here in previous DaCHS versions; try |
| 78 |
# to call old methods if they are still there |
| 79 |
if hasattr(self, "_createAuxillaries"): |
| 80 |
self._createAuxillaries(dd) |
| 81 |
|
| 82 |
def classify(self, srcName): |
| 83 |
return "unknown" |
| 84 |
|
| 85 |
def process(self, accref): |
| 86 |
pass |
| 87 |
|
| 88 |
def addClassification(self, srcName): |
| 89 |
label = self.classify(srcName) |
| 90 |
self.reportDict.setdefault(label, []).append(os.path.basename(srcName)) |
| 91 |
|
| 92 |
def printTableSize(self): |
| 93 |
try: |
| 94 |
tableName = self.dd.makes[0].table.getQName() |
| 95 |
with base.AdhocQuerier(base.getAdminConn) as q: |
| 96 |
itemsInDB = list(q.query("SELECT count(*) from %s"%tableName))[0][0] |
| 97 |
print("Items currently in assumed database table: %d\n"%itemsInDB) |
| 98 |
except (base.DBError, IndexError): |
| 99 |
pass |
| 100 |
|
| 101 |
def printReport(self, processed, ignored): |
| 102 |
print("\n\nProcessor Report\n================\n") |
| 103 |
if ignored: |
| 104 |
print("Warning: There were %d errors during classification"%ignored) |
| 105 |
repData = sorted(zip([len(l) for l in list(self.reportDict.values())], |
| 106 |
list(self.reportDict.keys()))) |
| 107 |
print(utils.formatSimpleTable(repData)) |
| 108 |
print("\n") |
| 109 |
self.printTableSize() |
| 110 |
|
| 111 |
def printVerboseReport(self, processed, ignored): |
| 112 |
print("\n\nProcessor Report\n================\n") |
| 113 |
if ignored: |
| 114 |
print("Warning: There were %d errors during classification"%ignored) |
| 115 |
repData = sorted(zip(list(self.reportDict.values()), |
| 116 |
list(self.reportDict.keys())), |
| 117 |
key=lambda v: -len(v[0])) |
| 118 |
print("\n%s\n%s\n"%(repData[0][1], "-"*len(repData[0][1]))) |
| 119 |
print("%d items\n"%(len(repData[0][0]))) |
| 120 |
for items, label in repData[1:]: |
| 121 |
print("\n%s\n%s\n"%(label, "-"*len(label))) |
| 122 |
items.sort() |
| 123 |
print("%d items:\n"%(len(items))) |
| 124 |
print("\n".join(textwrap.wrap(", ".join(items)))) |
| 125 |
print("\n") |
| 126 |
self.printTableSize() |
| 127 |
|
| 128 |
@staticmethod |
| 129 |
def addOptions(parser): |
| 130 |
parser.add_option("--filter", dest="requireFrag", metavar="STR", |
| 131 |
help="Only process files with names containing STR", default=None) |
| 132 |
parser.add_option("--bail", help="Bail out on a processor error," |
| 133 |
" dumping a traceback", action="store_true", dest="bailOnError", |
| 134 |
default=False) |
| 135 |
parser.add_option("--report", help="Output a report only", |
| 136 |
action="store_true", dest="doReport", default=False) |
| 137 |
parser.add_option("--verbose", help="Be more talkative", |
| 138 |
action="store_true", dest="beVerbose", default=False) |
| 139 |
parser.add_option("--n-procs", "-j", help="Run NUM processes in" |
| 140 |
" parallel", action="store", dest="nParallel", default=1, |
| 141 |
metavar="NUM", type=int) |
| 142 |
|
| 143 |
_doneSentinel = ("MAGIC: QUEUE DONE",) |
| 144 |
|
| 145 |
def iterJobs(self, nParallel): |
| 146 |
"""executes process() in parallel for all sources and iterates |
| 147 |
over the results. |
| 148 |
|
| 149 |
We use this rather than multiprocessing's Pool, as that cannot |
| 150 |
call methods. I'm working around this here. |
| 151 |
""" |
| 152 |
import multiprocessing |
| 153 |
|
| 154 |
taskQueue = multiprocessing.Queue(nParallel*4) |
| 155 |
doneQueue = multiprocessing.Queue() |
| 156 |
|
| 157 |
def worker(inQueue, outQueue): |
| 158 |
if hasattr(self, "conn"): |
| 159 |
self.conn = base.getDBConnection("trustedquery") |
| 160 |
for srcId in iter(inQueue.get, None): |
| 161 |
if (self.opts.requireFrag is not None |
| 162 |
and not self.opts.requireFrag in srcId): |
| 163 |
continue |
| 164 |
|
| 165 |
try: |
| 166 |
outQueue.put(self.process(srcId)) |
| 167 |
except base.SkipThis: |
| 168 |
continue |
| 169 |
except Exception as ex: |
| 170 |
ex.source = srcId |
| 171 |
if self.opts.bailOnError: |
| 172 |
sys.stderr.write("*** %s\n"%srcId) |
| 173 |
traceback.print_exc() |
| 174 |
outQueue.put(ex) |
| 175 |
outQueue.put(self._doneSentinel) |
| 176 |
|
| 177 |
# create nParallel workers |
| 178 |
activeWorkers = 0 |
| 179 |
# close my connection; it'll be nothing but trouble once |
| 180 |
# the workers see (and close) it, too |
| 181 |
if hasattr(self, "conn"): |
| 182 |
self.conn.close() |
| 183 |
for i in range(nParallel): |
| 184 |
multiprocessing.Process(target=worker, |
| 185 |
args=(taskQueue, doneQueue)).start() |
| 186 |
activeWorkers += 1 |
| 187 |
if hasattr(self, "conn"): |
| 188 |
self.conn = base.getDBConnection("trustedquery") |
| 189 |
|
| 190 |
# feed them their tasks |
| 191 |
toDo = self.iterIdentifiers() |
| 192 |
while True: |
| 193 |
try: |
| 194 |
taskQueue.put(next(toDo)) |
| 195 |
except StopIteration: |
| 196 |
break |
| 197 |
|
| 198 |
while not doneQueue.empty(): |
| 199 |
yield doneQueue.get() |
| 200 |
|
| 201 |
# ask them to quit and wait until all have said they're quitting |
| 202 |
for i in range(nParallel): |
| 203 |
taskQueue.put(None) |
| 204 |
taskQueue.close() |
| 205 |
while activeWorkers: |
| 206 |
item = doneQueue.get() |
| 207 |
if item==self._doneSentinel: |
| 208 |
activeWorkers -= 1 |
| 209 |
else: |
| 210 |
yield item |
| 211 |
|
| 212 |
def _runProcessor(self, procFunc, nParallel=1): |
| 213 |
"""calls procFunc for all sources in self.dd. |
| 214 |
|
| 215 |
This is the default, single-tasking implementation. |
| 216 |
""" |
| 217 |
processed, ignored = 0, 0 |
| 218 |
|
| 219 |
if nParallel==1: |
| 220 |
def iterProcResults(): |
| 221 |
for source in self.iterIdentifiers(): |
| 222 |
if (self.opts.requireFrag is not None |
| 223 |
and not self.opts.requireFrag in source): |
| 224 |
continue |
| 225 |
|
| 226 |
try: |
| 227 |
yield procFunc(source) |
| 228 |
except base.SkipThis: |
| 229 |
continue |
| 230 |
except Exception as ex: |
| 231 |
ex.source = source |
| 232 |
if self.opts.bailOnError: |
| 233 |
sys.stderr.write("*** %s\n"%source) |
| 234 |
traceback.print_exc() |
| 235 |
yield ex |
| 236 |
resIter = iterProcResults() |
| 237 |
else: |
| 238 |
resIter = self.iterJobs(nParallel) |
| 239 |
|
| 240 |
while True: |
| 241 |
try: |
| 242 |
res = next(resIter) |
| 243 |
if isinstance(res, Exception): |
| 244 |
raise res |
| 245 |
except StopIteration: |
| 246 |
break |
| 247 |
except KeyboardInterrupt: |
| 248 |
sys.exit(2) |
| 249 |
except Exception as msg: |
| 250 |
if self.opts.bailOnError: |
| 251 |
sys.exit(1) |
| 252 |
sys.stderr.write("Skipping source %s: (%s, %s)\n"%( |
| 253 |
getattr(msg, "source", "(unknown)"), msg.__class__.__name__, |
| 254 |
repr(msg))) |
| 255 |
ignored += 1 |
| 256 |
processed += 1 |
| 257 |
sys.stdout.write("%6d (-%5d)\r"%(processed, ignored)) |
| 258 |
sys.stdout.flush() |
| 259 |
return processed, ignored |
| 260 |
|
| 261 |
def iterIdentifiers(self): |
| 262 |
"""iterates over all identifiers that should be processed. |
| 263 |
|
| 264 |
This is usually the paths of the files to be processed. |
| 265 |
You can, however, override it to do something else if that |
| 266 |
fits your problem (example: Previews in SSA use the accref). |
| 267 |
""" |
| 268 |
return iter(self.dd.sources) |
| 269 |
|
| 270 |
def processAll(self): |
| 271 |
"""calls the process method of processor for all sources of the data |
| 272 |
descriptor dd. |
| 273 |
""" |
| 274 |
if self.opts.doReport: |
| 275 |
self.reportDict = {} |
| 276 |
procFunc = self.addClassification |
| 277 |
else: |
| 278 |
procFunc = self.process |
| 279 |
processed, ignored = self._runProcessor(procFunc, |
| 280 |
nParallel=self.opts.nParallel) |
| 281 |
if self.opts.doReport: |
| 282 |
if self.opts.beVerbose: |
| 283 |
self.printVerboseReport(processed, ignored) |
| 284 |
else: |
| 285 |
self.printReport(processed, ignored) |
| 286 |
return processed, ignored |
| 287 |
|
| 288 |
######### Utility methods |
| 289 |
|
| 290 |
def getProductKey(self, srcName): |
| 291 |
return utils.getRelativePath(str(srcName), self.inputsDir) |
| 292 |
|
| 293 |
|
| 294 |
class ImmediateHeaderProcessor(FileProcessor): |
| 295 |
"""An base for processors doing simple FITS manipulations to the primary |
| 296 |
FITS header. |
| 297 |
|
| 298 |
To define these, override ``_isProcessed(self, srcName, hdr)`` and |
| 299 |
``_changeHeader(self, hdr)``. |
| 300 |
|
| 301 |
``_changeHeader`` can change the pyfits header ``hdr`` in place. It |
| 302 |
will then be replaced on the actual file. |
| 303 |
|
| 304 |
For complex operations, it is probably advisable to use ``HeaderProcessor`` |
| 305 |
which gives you a two-step process of first having the detached headers |
| 306 |
that you can check before applying them. |
| 307 |
""" |
| 308 |
def _isProcessed(self, srcName, hdr): |
| 309 |
return False |
| 310 |
|
| 311 |
def process(self, accref): |
| 312 |
srcName = str(self.inputsDir / accref) |
| 313 |
with open(srcName, "rb") as f: |
| 314 |
hdr = fitstools.readPrimaryHeaderQuick(f) |
| 315 |
if not self.opts.reProcess: |
| 316 |
if self._isProcessed(srcName, hdr): |
| 317 |
return |
| 318 |
|
| 319 |
self._changeHeader(srcName, hdr) |
| 320 |
fitstools.replacePrimaryHeaderInPlace(srcName, hdr) |
| 321 |
|
| 322 |
@staticmethod |
| 323 |
def addOptions(optParser): |
| 324 |
FileProcessor.addOptions(optParser) |
| 325 |
optParser.add_option("--reprocess", help="Recompute all headers", |
| 326 |
action="store_true", dest="reProcess", default=False) |
| 327 |
|
| 328 |
|
| 329 |
class HeaderProcessor(FileProcessor): |
| 330 |
"""A base for processors doing FITS header manipulations. |
| 331 |
|
| 332 |
The processor builds naked FITS headers alongside the actual files, with an |
| 333 |
added extension .hdr (or whatever is in the headerExt attribute). The |
| 334 |
presence of a FITS header indicates that a file has been processed. The |
| 335 |
headers on the actual FITS files are only replaced if necessary. |
| 336 |
|
| 337 |
The basic flow is: Check if there is a header. If not, call |
| 338 |
_getNewHeader(srcFile) -> hdr. Store hdr to cache. Insert cached |
| 339 |
header in the new FITS if it's not there yet. |
| 340 |
|
| 341 |
You have to implement the _getHeader(srcName) -> pyfits header object |
| 342 |
function. It must raise an exception if it cannot come up with a |
| 343 |
header. You also have to implement _isProcessed(srcName) -> boolean |
| 344 |
returning True if you think srcName already has a processed header. |
| 345 |
|
| 346 |
This basic flow is influenced by the following opts attributes: |
| 347 |
|
| 348 |
* reProcess -- even if a cache is present, recompute header values |
| 349 |
* applyHeaders -- actually replace old headers with new headers |
| 350 |
* reHeader -- even if _isProcessed returns True, write a new header |
| 351 |
* compute -- perform computations |
| 352 |
|
| 353 |
The idea is that you can: |
| 354 |
|
| 355 |
* generate headers without touching the original files: proc |
| 356 |
* write all cached headers to files that don't have them: |
| 357 |
``proc --apply --nocompute`` |
| 358 |
* after a bugfix force all headers to be regenerated: |
| 359 |
``proc --reprocess --apply --reheader`` |
| 360 |
|
| 361 |
All this leads to the messy logic. Sorry about this. |
| 362 |
""" |
| 363 |
headerExt = ".hdr" |
| 364 |
maxHeaderBlocks = 40 |
| 365 |
cardSequence = None |
| 366 |
|
| 367 |
def _makeCacheName(self, srcName): |
| 368 |
return srcName+self.headerExt |
| 369 |
|
| 370 |
def _writeCache(self, srcName, hdr): |
| 371 |
dest = self._makeCacheName(srcName) |
| 372 |
|
| 373 |
# nuke info on sizes that may still lurk; we don't want that in the |
| 374 |
# cache |
| 375 |
hdr = hdr.copy() |
| 376 |
hdr.set("BITPIX", 8) |
| 377 |
hdr.set("NAXIS", 0) |
| 378 |
if "NAXIS1" in hdr: |
| 379 |
del hdr["NAXIS1"] |
| 380 |
if "NAXIS2" in hdr: |
| 381 |
del hdr["NAXIS2"] |
| 382 |
|
| 383 |
hdr = fitstools.sortHeaders(hdr, |
| 384 |
commentFilter=self.commentFilter, |
| 385 |
historyFilter=self.historyFilter, |
| 386 |
cardSequence=self.cardSequence) |
| 387 |
|
| 388 |
serialized = fitstools.serializeHeader(hdr) |
| 389 |
with open(dest, "wb") as f: |
| 390 |
f.write(serialized) |
| 391 |
hdus = pyfits.open(dest) |
| 392 |
hdus.verify() |
| 393 |
hdus.close() |
| 394 |
|
| 395 |
def _readCache(self, srcName): |
| 396 |
"""returns a pyfits header object for the cached result in srcName. |
| 397 |
|
| 398 |
If there is no cache, None is returned. |
| 399 |
""" |
| 400 |
src = self._makeCacheName(srcName) |
| 401 |
if os.path.exists(src): |
| 402 |
with open(src, "rb") as f: |
| 403 |
hdr = fitstools.readPrimaryHeaderQuick(f, self.maxHeaderBlocks) |
| 404 |
return hdr |
| 405 |
|
| 406 |
def _makeCache(self, srcName): |
| 407 |
if self.opts.compute: |
| 408 |
if self.opts.beVerbose: |
| 409 |
print("Now computing for", srcName) |
| 410 |
hdr = self._getHeader(srcName) |
| 411 |
if hdr is None: |
| 412 |
raise CannotComputeHeader("_getHeader returned None") |
| 413 |
self._writeCache(srcName, hdr) |
| 414 |
|
| 415 |
# headers copied from original file rather than the cached header |
| 416 |
keepKeys = set(["SIMPLE", "BITPIX", "NAXIS", "NAXIS1", "NAXIS2", |
| 417 |
"EXTEND", "BZERO", "BSCALE"]) |
| 418 |
|
| 419 |
def _fixHeaderDataKeys(self, srcName, header): |
| 420 |
oldHeader = self.getPrimaryHeader(srcName) |
| 421 |
for key in self.keepKeys: |
| 422 |
if key in oldHeader: |
| 423 |
header.set(key, oldHeader[key]) |
| 424 |
|
| 425 |
def commentFilter(self, value): |
| 426 |
"""returns true if the comment value should be preserved. |
| 427 |
|
| 428 |
You may want to override this. |
| 429 |
""" |
| 430 |
return True |
| 431 |
|
| 432 |
def historyFilter(self, value): |
| 433 |
"""returns true if the history item value should be preserved. |
| 434 |
""" |
| 435 |
return True |
| 436 |
|
| 437 |
def _writeHeader(self, srcName, header): |
| 438 |
self._fixHeaderDataKeys(srcName, header) |
| 439 |
header = fitstools.sortHeaders(header, commentFilter=self.commentFilter, |
| 440 |
historyFilter=self.historyFilter) |
| 441 |
fitstools.replacePrimaryHeaderInPlace(srcName, header) |
| 442 |
|
| 443 |
def _isProcessed(self, srcName): |
| 444 |
"""override. |
| 445 |
""" |
| 446 |
return False |
| 447 |
|
| 448 |
def _mungeHeader(self, srcName, header): |
| 449 |
"""override this or _getHeader. |
| 450 |
""" |
| 451 |
return header |
| 452 |
|
| 453 |
def _getHeader(self, srcName): |
| 454 |
"""override this or _mungeHeader. |
| 455 |
""" |
| 456 |
return self._mungeHeader(srcName, self.getPrimaryHeader(srcName)) |
| 457 |
|
| 458 |
@staticmethod |
| 459 |
def getPrimaryHeader(srcName): |
| 460 |
"""returns the primary header of srcName. |
| 461 |
|
| 462 |
This is a convenience function for user derived classes. |
| 463 |
""" |
| 464 |
f = open(srcName, "rb") |
| 465 |
hdr = utils.readPrimaryHeaderQuick(f) |
| 466 |
f.close() |
| 467 |
return hdr |
| 468 |
|
| 469 |
def process(self, accref): |
| 470 |
srcName = str(self.inputsDir / accref) |
| 471 |
if (not (self.opts.reProcess or self.opts.reHeader) |
| 472 |
and self._isProcessed(srcName)): |
| 473 |
return |
| 474 |
cache = self._readCache(srcName) |
| 475 |
if cache is None or self.opts.reProcess: |
| 476 |
self._makeCache(srcName) |
| 477 |
cache = self._readCache(srcName) |
| 478 |
if cache is None: |
| 479 |
return |
| 480 |
if not self.opts.applyHeaders: |
| 481 |
return |
| 482 |
if self.opts.reHeader or not self._isProcessed(srcName): |
| 483 |
self._writeHeader(srcName, cache) |
| 484 |
|
| 485 |
@staticmethod |
| 486 |
def addOptions(optParser): |
| 487 |
FileProcessor.addOptions(optParser) |
| 488 |
optParser.add_option("--reprocess", help="Recompute all headers", |
| 489 |
action="store_true", dest="reProcess", default=False) |
| 490 |
optParser.add_option("--no-compute", help="Only use cached headers", |
| 491 |
action="store_false", dest="compute", default=True) |
| 492 |
optParser.add_option("--apply", help="Write cached headers to" |
| 493 |
" source files", action="store_true", dest="applyHeaders", |
| 494 |
default=False) |
| 495 |
optParser.add_option("--reheader", help="Write cached headers" |
| 496 |
" to source files even if it looks like they already have" |
| 497 |
" been written", action="store_true", dest="reHeader", |
| 498 |
default=False) |
| 499 |
|
| 500 |
|
| 501 |
class AnetHeaderProcessor(HeaderProcessor): |
| 502 |
"""A file processor for calibrating FITS frames using astrometry.net. |
| 503 |
|
| 504 |
It might provide calibration for "simple" cases out of the box. You |
| 505 |
will usually want to override some solver parameters. To do that, |
| 506 |
define class attributes sp_<parameter name>, where the parameters |
| 507 |
available are discussed in helpers.anet's docstring. sp_indices is |
| 508 |
one thing you will typically need to override. |
| 509 |
|
| 510 |
To use SExtractor rather than anet's source extractor, override |
| 511 |
sexControl, to use an object filter (see anet.getWCSFieldsFor), override |
| 512 |
the objectFilter attribute. |
| 513 |
|
| 514 |
To add additional fields, override _getHeader and call the parent |
| 515 |
class' _getHeader method. To change the way astrometry.net is |
| 516 |
called, override the _solveAnet method (it needs to return some |
| 517 |
result anet.of getWCSFieldsFor) and call _runAnet with your |
| 518 |
custom arguments for getWCSFieldsFor. |
| 519 |
|
| 520 |
See :dachsdoc:`processors#astrometry-net` for details. |
| 521 |
""" |
| 522 |
sourceExtractorControl = None |
| 523 |
objectFilter = None |
| 524 |
indexPath = base.getConfig("rootDir") / "astrometry-indexes" |
| 525 |
|
| 526 |
noCopyHeaders = set(["simple", "bitpix", "naxis", "imageh", "imagew", |
| 527 |
"naxis1", "naxis2", "datamin", "datamax", "date"]) |
| 528 |
|
| 529 |
@staticmethod |
| 530 |
def addOptions(optParser): |
| 531 |
def storeDestPath(opt, opt_str, value, parser): |
| 532 |
parser.values.copyTo = os.path.join( |
| 533 |
os.getcwd(), |
| 534 |
os.path.expanduser(value)) |
| 535 |
|
| 536 |
HeaderProcessor.addOptions(optParser) |
| 537 |
optParser.add_option("--no-anet", help="Do not run anet, fail if" |
| 538 |
" no cache is present to take anet headers from", action="store_false", |
| 539 |
dest="runAnet", default=True) |
| 540 |
optParser.add_option("--copy-to", help="Copy astrometry.net sandbox to" |
| 541 |
" this directory (WARNING: it will be deleted if it exists!)." |
| 542 |
" Probably most useful with --bail", type="str", |
| 543 |
action="callback", callback=storeDestPath) |
| 544 |
optParser.set_defaults(copyTo=None) |
| 545 |
|
| 546 |
def _isProcessed(self, srcName): |
| 547 |
return "CD1_1" in self.getPrimaryHeader(srcName) |
| 548 |
|
| 549 |
def _runAnet(self, srcName): |
| 550 |
return anet.getWCSFieldsFor( |
| 551 |
srcName, self.solverParameters, |
| 552 |
self.sourceExtractorControl, |
| 553 |
self.objectFilter, |
| 554 |
getattr(self.opts, "copyTo", None), |
| 555 |
self.indexPath, |
| 556 |
self.opts.beVerbose) |
| 557 |
|
| 558 |
@property |
| 559 |
def solverParameters(self): |
| 560 |
return dict( |
| 561 |
(n[3:], getattr(self, n)) |
| 562 |
for n in dir(self) if n.startswith("sp_")) |
| 563 |
|
| 564 |
def _solveAnet(self, srcName): |
| 565 |
if self.opts.runAnet: |
| 566 |
return self._runAnet(srcName) |
| 567 |
else: |
| 568 |
oldCards = self._readCache(srcName) |
| 569 |
if oldCards is None: |
| 570 |
raise CannotComputeHeader("No cached headers and you asked" |
| 571 |
" not to run astrometry.net") |
| 572 |
return oldCards.cards |
| 573 |
|
| 574 |
def _shouldRunAnet(self, srcName, hdr): |
| 575 |
return True |
| 576 |
|
| 577 |
def _getHeader(self, srcName): |
| 578 |
hdr = self.getPrimaryHeader(srcName) |
| 579 |
if self._shouldRunAnet(srcName, hdr): |
| 580 |
wcsCards = self._solveAnet(srcName) |
| 581 |
if not wcsCards: |
| 582 |
raise CannotComputeHeader("astrometry.net did not" |
| 583 |
" find a solution") |
| 584 |
fitstricks.copyFields(hdr, wcsCards, self.noCopyHeaders) |
| 585 |
return self._mungeHeader(srcName, hdr) |
| 586 |
|
| 587 |
def commentFilter(self, value): |
| 588 |
return ( "Index name" in value or |
| 589 |
"Cxdx margin" in value or |
| 590 |
"Field scale lower" in value or |
| 591 |
"Field scale upper" in value or |
| 592 |
"Start obj" in value or |
| 593 |
"End obj" in value or |
| 594 |
"Tweak" in value or |
| 595 |
"code error" in value) |
| 596 |
|
| 597 |
def historyFilter(self, value): |
| 598 |
return ("suite" in value or |
| 599 |
"blind" in value) |
| 600 |
|
| 601 |
|
| 602 |
class PreviewMaker(FileProcessor): |
| 603 |
"""A file processor for generating previews. |
| 604 |
|
| 605 |
For these, define a method getPreviewData(accref) -> string returning |
| 606 |
the raw preview data. |
| 607 |
""" |
| 608 |
@staticmethod |
| 609 |
def addOptions(optParser): |
| 610 |
FileProcessor.addOptions(optParser) |
| 611 |
optParser.add_option("--force", help="Generate previews even" |
| 612 |
" where they already exist", action="store_true", |
| 613 |
dest="force", default=False) |
| 614 |
|
| 615 |
def iterIdentifiers(self): |
| 616 |
"""iterates over the accrefs in the first table of dd. |
| 617 |
""" |
| 618 |
tableId = self.dd.makes[0].table.getQName() |
| 619 |
for r in self.conn.queryToDicts("select accref from %s"%tableId): |
| 620 |
yield r["accref"] |
| 621 |
|
| 622 |
def _createAuxiliaries(self, dd): |
| 623 |
self.previewDir = dd.rd.getAbsPath( |
| 624 |
dd.getProperty("previewDir")) |
| 625 |
if not os.path.isdir(self.previewDir): |
| 626 |
os.makedirs(self.previewDir) |
| 627 |
self.conn = base.getDBConnection("trustedquery") |
| 628 |
FileProcessor._createAuxiliaries(self, dd) |
| 629 |
|
| 630 |
def getPreviewPath(self, accref): |
| 631 |
res = list(self.conn.query("select preview from dc.products where" |
| 632 |
" accref=%(accref)s", {"accref": accref})) |
| 633 |
if not res: |
| 634 |
raise IOError("%s is not in the products table. Update/import" |
| 635 |
" the resource?"%accref) |
| 636 |
if res[0][0]=="AUTO": |
| 637 |
raise base.ReportableError("Preview path in the product table is AUTO." |
| 638 |
" Will not write preview there. Make sure you have properly" |
| 639 |
" bound the preview parameter in //products#define and re-import.") |
| 640 |
return str(self.inputsDir / res[0][0]) |
| 641 |
|
| 642 |
def classify(self, srcName, previewPath): |
| 643 |
if self.opts.force: |
| 644 |
return "without" |
| 645 |
if os.path.exists(previewPath): |
| 646 |
return "with" |
| 647 |
else: |
| 648 |
return "without" |
| 649 |
|
| 650 |
def process(self, accref): |
| 651 |
srcName = str(self.inputsDir / accref) |
| 652 |
previewPath = self.getPreviewPath(accref) |
| 653 |
if self.classify(srcName, previewPath)=="with": |
| 654 |
return |
| 655 |
|
| 656 |
dirPart = os.path.dirname(previewPath) |
| 657 |
if not os.path.exists(dirPart): |
| 658 |
os.makedirs(dirPart) |
| 659 |
os.chmod(dirPart, 0o775) |
| 660 |
|
| 661 |
with utils.safeReplaced(previewPath) as f: |
| 662 |
f.write(self.getPreviewData(str(srcName))) |
| 663 |
os.chmod(previewPath, 0o664) |
| 664 |
|
| 665 |
|
| 666 |
class OneDPreviewMaker(PreviewMaker): |
| 667 |
"""A preview maker for 1D data. |
| 668 |
|
| 669 |
This is for when you produce your data sets from datalink using |
| 670 |
an embedded grammar using a datalink descriptor as the source token. |
| 671 |
That's what we recommend for time series (and probably for |
| 672 |
spectra too, soon). |
| 673 |
|
| 674 |
To make this work, derive from it and define the following class |
| 675 |
attributes: |
| 676 |
|
| 677 |
* abscName -- abscisssa, the name of the x axis column (preconfigured |
| 678 |
for timeseries#phot-0, override otherwise) |
| 679 |
* ordName -- ordinate, the name of the y axis column |
| 680 |
* builderId -- the ID of the data item building the data collection |
| 681 |
(must define a previews property) |
| 682 |
* logOrd=False -- logarithmic ordinate |
| 683 |
* connectPoints=True -- or do a scatter plot |
| 684 |
|
| 685 |
Then define a method getSource(srcName) –> something that |
| 686 |
returns something that the builder's grammar can use. See |
| 687 |
SpectralPreviewMaker and DLPreviewMaker for examples. |
| 688 |
|
| 689 |
For context, see :dachsref:`processors.html#precomputing-previews`. |
| 690 |
""" |
| 691 |
logOrd = False |
| 692 |
abscName = "obs_time" |
| 693 |
ordName = "phot" |
| 694 |
connectPoints = True |
| 695 |
builderId = None |
| 696 |
|
| 697 |
def _createAuxiliaries(self, dd): |
| 698 |
if self.builderId is None: |
| 699 |
raise base.ReportableError("Concrete OneDPreviewMakers" |
| 700 |
" need a non-None builderId.") |
| 701 |
|
| 702 |
PreviewMaker._createAuxiliaries(self, dd) |
| 703 |
self.builderDD = self.dd.rd.getById(self.builderId) |
| 704 |
|
| 705 |
@staticmethod |
| 706 |
def get2DPlot(tuples, linear=False, connectPoints=True): |
| 707 |
"""returns a png-compressed pixel image for a 2D plot of (x,y) |
| 708 |
tuples. |
| 709 |
""" |
| 710 |
with matplotlibLock(): |
| 711 |
fig = figure.Figure(figsize=(4,2)) |
| 712 |
ax = fig.add_axes([0,0,1,1], frameon=False) |
| 713 |
|
| 714 |
if linear: |
| 715 |
plotter = ax.plot |
| 716 |
else: |
| 717 |
plotter = ax.semilogy |
| 718 |
|
| 719 |
if connectPoints: |
| 720 |
linestyle = "-" |
| 721 |
else: |
| 722 |
linestyle = "o" |
| 723 |
|
| 724 |
plotter( |
| 725 |
[r[0] for r in tuples], |
| 726 |
[r[1] for r in tuples], |
| 727 |
linestyle, |
| 728 |
color="black") |
| 729 |
ax.xaxis.set_major_locator(matplotlib.ticker.NullLocator()) |
| 730 |
ax.yaxis.set_major_locator(matplotlib.ticker.NullLocator()) |
| 731 |
ax.yaxis.set_minor_locator(matplotlib.ticker.NullLocator()) |
| 732 |
|
| 733 |
rendered = io.BytesIO() |
| 734 |
fig.savefig(rendered, format="png", dpi=50) |
| 735 |
|
| 736 |
rendered = io.BytesIO(rendered.getvalue()) |
| 737 |
im = Image.open(rendered) |
| 738 |
im = im.convert("L") |
| 739 |
im = im.convert("P", palette=Image.ADAPTIVE, colors=8) |
| 740 |
compressed = io.BytesIO() |
| 741 |
im.save(compressed, format="png", bits=3) |
| 742 |
return compressed.getvalue() |
| 743 |
|
| 744 |
def getSource(self, srcName): |
| 745 |
raise NotImplementedError("Concrete preview makers need to" |
| 746 |
" define a getSource method.") |
| 747 |
|
| 748 |
def getPreviewData(self, srcName): |
| 749 |
table = rsc.makeData(self.builderDD, forceSource=self.getSource(srcName) |
| 750 |
).getPrimaryTable() |
| 751 |
data = [(r[self.abscName], r[self.ordName]) for r in table.rows] |
| 752 |
data.sort() |
| 753 |
|
| 754 |
return self.get2DPlot(data, not self.logOrd, self.connectPoints) |
| 755 |
|
| 756 |
|
| 757 |
class SpectralPreviewMaker(OneDPreviewMaker): |
| 758 |
"""a preview maker for DaCHS' sdm spectra generators. |
| 759 |
|
| 760 |
You typically only need to fill out sdmId; class attribute you might |
| 761 |
want to change are linearFluxes, connectPoints and porbably not |
| 762 |
spectralColumn and fluxColumn. |
| 763 |
""" |
| 764 |
linearFluxes = False |
| 765 |
spectralColumn = "spectral" |
| 766 |
fluxColumn = "flux" |
| 767 |
connectPoints = True |
| 768 |
sdmId = None |
| 769 |
|
| 770 |
def __init__(self, opts, dd): |
| 771 |
# translate legacy attribute names to the OneDPreviewMaker ones. |
| 772 |
self.abscName = self.spectralColumn |
| 773 |
self.ordName = self.fluxColumn |
| 774 |
self.logOrd = not self.linearFluxes |
| 775 |
self.builderId = self.sdmId |
| 776 |
OneDPreviewMaker.__init__(self, opts, dd) |
| 777 |
|
| 778 |
def getSource(self, srcName): |
| 779 |
return {"accref": self.getProductKey(srcName)} |
| 780 |
|
| 781 |
|
| 782 |
class DLPreviewMaker(OneDPreviewMaker): |
| 783 |
"""A preview maker for building from embedded grammars that take |
| 784 |
datalink descriptors as source tokens. |
| 785 |
|
| 786 |
In DaCHS, we typically use these for time series. |
| 787 |
|
| 788 |
In addition to what OneDPreviewMaker wants, this needs a dlId, the |
| 789 |
Id of the datalink service producing the data. |
| 790 |
""" |
| 791 |
dlId = None |
| 792 |
|
| 793 |
def _createAuxiliaries(self, dd): |
| 794 |
if self.dlId is None: |
| 795 |
raise base.ReportableError("Concrete DLPreviewMakers" |
| 796 |
" need a non-None dlId.") |
| 797 |
self.descriptorGenerator = self.dd.rd.getById(self.dlId |
| 798 |
).core.descriptorGenerator.compile() |
| 799 |
|
| 800 |
OneDPreviewMaker._createAuxiliaries(self, dd) |
| 801 |
|
| 802 |
def getSource(self, srcName): |
| 803 |
"""returns a descriptor generator for a source name. |
| 804 |
|
| 805 |
This assumes the accref is just the inputsDir-relative file name. |
| 806 |
If this assumption is wrong, you need to re-implement this. |
| 807 |
""" |
| 808 |
accref = self.getProductKey(srcName) |
| 809 |
return self.descriptorGenerator(accref, {}) |
| 810 |
|
| 811 |
|
| 812 |
def procmain(processorClass, rdId, ddId): |
| 813 |
"""The "standard" main function for processor scripts. |
| 814 |
|
| 815 |
The function returns the instantiated processor so you can communicate |
| 816 |
from your processor back to your own main. |
| 817 |
|
| 818 |
See :dachsdoc:`processors.html` for details. |
| 819 |
""" |
| 820 |
import optparse |
| 821 |
from gavo import rscdesc #noflake: for registration |
| 822 |
rd = base.caches.getRD(rdId) |
| 823 |
dd = rd.getById(ddId) |
| 824 |
|
| 825 |
parser = optparse.OptionParser() |
| 826 |
processorClass.addOptions(parser) |
| 827 |
opts, args = parser.parse_args() |
| 828 |
if args: |
| 829 |
parser.print_help(file=sys.stderr) |
| 830 |
sys.exit(1) |
| 831 |
if opts.beVerbose: |
| 832 |
from gavo.user import logui |
| 833 |
logui.LoggingUI(base.ui) |
| 834 |
base.DEBUG = True |
| 835 |
|
| 836 |
proc = processorClass(opts, dd) |
| 837 |
processed, ignored = proc.processAll() |
| 838 |
print("%s files processed, %s files with errors"%(processed, ignored)) |
| 839 |
return proc |