- Timestamp:
- Jan 11, 2015, 1:31:50 PM (12 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/eam_branches/ipp-20140904/ippToPsps/jython/diffbatch.py
r36697 r37801 1 #!/usr/bin/env jython 2 3 import os.path 4 import sys 5 import glob 6 import time 7 import stilts 8 import re 9 from java.lang import * 10 from java.sql import * 11 12 from java.lang import Math 13 from org.apache.commons.math.special import Erf 14 15 from xml.etree.ElementTree import ElementTree, Element, tostring 16 17 from batch import Batch 18 from gpc1db import Gpc1Db 19 from ipptopspsdb import IppToPspsDb 20 from scratchdb import ScratchDb 21 from sqlUtility import sqlUtility 22 23 import logging.config 24 25 ''' 26 DiffBatch class 27 28 This class, a sub-class of Batch, processes single exposures in the form of IPP smf files 29 30 ''' 31 class DiffBatch(Batch): 32 33 ''' 34 Constructor 35 ''' 36 def __init__(self, 37 logger, 38 config, 39 skychunk, 40 gpc1Db, 41 ippToPspsDb, 42 scratchDb, 43 diffSkyFileID, 44 batchID): 45 46 super(DiffBatch, self).__init__( 47 logger, 48 config, 49 skychunk, 50 gpc1Db, 51 ippToPspsDb, 52 scratchDb, 53 diffSkyFileID, 54 batchID, 55 "DF", 56 None) 57 # gpc1Db.getDiffStageCmf(skychunk.dvoLabel,diffSkyFileID)) 58 59 # get diff meta data 60 # if error about catID you are usings an old ipptopsps_scratch db 61 self.logger.infoPair("getting diff" ," metadata") 62 meta = self.gpc1Db.getDiffStageMeta(diffSkyFileID) 63 self.logger.infoPair("ok, I guess that worked","now doing this") 64 self.diffSkyFileID = diffSkyFileID 65 if not meta: 66 self.logger.errorPair("Could not get", "diff metadata") 67 raise 68 self.logger.infoPair("so meta", "much amaze") 69 self.filterName = meta[0]; 70 self.difftypeID = meta[1]; 71 self.posImageID = meta[2]; 72 self.negImageID = meta[3]; 73 self.skycellName = meta[4]; 74 self.analVer = meta[5]; 75 self.expTime = meta[6]; 76 self.obsTime = meta[7]; 77 self.fits = gpc1Db.getDiffStageCmf(skychunk.dvoLabel, diffSkyFileID) 78 self.header = self.fits.getPrimaryHeader() 79 tessName = self.getKeyValue(self.header, 'TESS_ID') 80 self.tessID = self.scratchDb.getTessID(tessName) 81 82 83 # XXX EAM 20140812 : I am hardwiring the parsing logic for RINGS vs LOCAL 84 if tessName == 'RINGS.V3': 85 # skycell is, eg "skycell.1133.081" 86 # 0123456789012345 87 self.projectionID = self.skycellName[8:12] 88 self.skycellID = self.skycellName[13:] 89 self.skycellID = self.skycellName[8:] 90 else: 91 # skycell is, eg "skycell.081" 92 # 01234567890 93 self.projectionID = 0 94 self.skycellID = self.skycellName[8:11] 95 self.skycellID=self.skycellName[8:] 96 if self.skycellID == "": 97 self.skycellID = -1 98 99 100 # drop the existing tables 101 102 self.dropTableVerbose("DiffMeta") 103 self.dropTableVerbose("DiffToImage") 104 self.dropTableVerbose("DiffDetection") 105 106 107 108 109 self.logger.infoPair("I can haz",diffSkyFileID) 110 111 112 113 if not self.analVer: self.analVer = -999 114 115 # create an output filename, which is {expID}.FITS 116 self.outputFitsFile = "%08d.FITS" % self.diffSkyFileID 117 self.outputFitsPath = "%s/%s" % (self.localOutPath, self.outputFitsFile) 118 print "got here" 119 self.photoCalID = str(self.scratchDb.getPhotoCalID(self.diffSkyFileID)) 120 print "got photocalid" 121 self.calibModNum = 0; 122 self.dataRelease = skychunk.dataRelease; 123 124 self.filterID = self.scratchDb.getFilterID(self.filterName[0]) 125 126 print self.filterName 127 print self.filterName[0] 128 print self.filterID 129 # insert what we know about this stack batch into the stack table 130 self.ippToPspsDb.insertDiffMeta(self.batchID, self.filterName[0], self.difftypeID) 131 132 # dump stuff to log 133 self.logger.infoPair("diff_skyfile_ID", "%d" % self.diffSkyFileID) 134 135 136 ''' 137 Populates the FrameMeta table, mainly from dictionary values found in IPP FITS header 138 ''' 139 def populateDiffMeta(self): 140 self.logger.infoPair("Proccesing table", "DiffMeta") 141 142 sqlLine = sqlUtility("INSERT INTO DiffMeta (") 143 144 sqlLine.group("diffMetaID", str(self.diffSkyFileID)); 145 sqlLine.group("difftypeID", self.difftypeID); 146 sqlLine.group("posImageID", self.posImageID); 147 sqlLine.group("negImageID", self.negImageID); 148 sqlLine.group("skycellID", self.skycellID); 149 sqlLine.group("photoCalID", self.photoCalID); 150 sqlLine.group("magSat", self.getKeyFloat(self.header, "%.8f", 'FSATUR')); 151 sqlLine.group("analVer", str(self.analVer)); 152 sqlLine.group("expTime", self.expTime); 153 sqlLine.group("ctype1", self.getKeyValue(self.header, 'CTYPE1')); 154 sqlLine.group("ctype2", self.getKeyValue(self.header, 'CTYPE2')); 155 sqlLine.group("crval1", self.getKeyFloat(self.header, "%.8f", 'CRVAL1')); 156 sqlLine.group("crval2", self.getKeyFloat(self.header, "%.8f", 'CRVAL2')); 157 sqlLine.group("crpix1", self.getKeyFloat(self.header, "%.8f", 'CRPIX1')); 158 sqlLine.group("crpix2", self.getKeyFloat(self.header, "%.8f", 'CRPIX2')); 159 sqlLine.group("cdelt1", self.getKeyFloat(self.header, "%.8e", 'CDELT1')); 160 sqlLine.group("cdelt2", self.getKeyFloat(self.header, "%.8e", 'CDELT2')); 161 sqlLine.group("pc001001", self.getKeyFloat(self.header, "%.8e", 'PC001001')); 162 sqlLine.group("pc001002", self.getKeyFloat(self.header, "%.8e", 'PC001002')); 163 sqlLine.group("pc002001", self.getKeyFloat(self.header, "%.8e", 'PC002001')); 164 sqlLine.group("pc002002", self.getKeyFloat(self.header, "%.8e", 'PC002002')); 165 166 sql = sqlLine.make(") VALUES ( ", ")") 167 168 try: self.scratchDb.execute(sql) 169 except: 170 self.logger.errorPair('failed sql: ', sql) 171 raise 172 self.logger.infoPair("DiffMeta","final stuff") 173 self.scratchDb.updateAllRows("DiffMeta", "batchID", str(self.batchID)) 174 self.scratchDb.updateAllRows("DiffMeta", "surveyID", str(self.surveyID)) 175 self.scratchDb.updateFilterID("DiffMeta", self.filterName[0]) 176 self.scratchDb.updateAllRows("DiffMeta", "calibModNum", str(self.calibModNum)) 177 self.scratchDb.updateAllRows("DiffMeta", "dataRelease", str(self.skychunk.dataRelease)) 178 self.logger.infoPair("DiffMeta","done") 179 180 ''' 181 Populates the Diff table for this OTA 182 ''' 183 def populateDiffDetectionTable(self): 184 185 pspsTableName = "DiffDetection" 186 ippTableName = "SkyChip_psf" 187 188 #results['ORIGINALTOTAL'] = self.scratchDb.getRowCount(ippTableName) 189 190 # drop then re-create table 191 #self.scratchDb.dropTable(pspsTableName) 192 #sql = "CREATE TABLE " + pspsTableName + " LIKE DiffDetection" 193 #try: self.scratchDb.execute(sql) 194 #except: pass 195 196 # XXX we no longer delete detections with funny mags (eg PSF_INST_MAG < -17.5) 197 # for examples of code which do this, go to r35097 or earlier 198 199 BEFORE = self.scratchDb.getRowCount(ippTableName) 200 #results['SATDET'] = 0 201 202 extTimeString = str(self.expTime) 203 204 # insert all detections into table : do NOT include the IGNORE unless we have to 205 # sqlLine = sqlUtility("INSERT IGNORE INTO " + pspsTableName + " (") 206 sqlLine = sqlUtility("INSERT INTO " + pspsTableName + " (") 207 208 # XXX WARNING: need to apply platescale to convert sizes to arcsec 209 # XXX apFluxF or apFluxNpix + apFluxRadius? 210 211 sqlLine.group("ippDetectID", "IPP_IDET") 212 sqlLine.group("diffDetMetaID", str(self.diffSkyFileID)); 213 sqlLine.group("randomDiffID", "FLOOR(RAND("+str(self.batchID)+")*9223372036854775807)") 214 sqlLine.group("filterID", str(self.filterID)) 215 sqlLine.group("surveyID", str(self.surveyID)) 216 sqlLine.group("skycellID", str(self.skycellID)) 217 ## sqlLine.group("obsTime", str(self.obsTime)) 218 sqlLine.group("expTime", str(self.expTime)) 219 sqlLine.group("obsTime", str(self.obsTime)) 220 sqlLine.group("xPos", "X_PSF") 221 sqlLine.group("yPos", "Y_PSF") 222 sqlLine.group("xPosErr", "X_PSF_SIG") 223 sqlLine.group("yPosErr", "Y_PSF_SIG") 224 if (self.id >= 982483): 225 sqlLine.group("pltScale", "PLTSCALE") 226 sqlLine.group("posAngle", "POSANGLE") 227 # sqlLine.group("raErr", "X_PSF_SIG * abs(PLTSCALE)") 228 # sqlLine.group("decErr", "Y_PSF_SIG * abs(PLTSCALE)") 229 else: 230 sqlLine.group("pltScale", "0.257") 231 sqlLine.group("posAngle", "-999") 232 # sqlLine.group("raErr", "X_PSF_SIG * 0.257") 233 # sqlLine.group("decErr", "Y_PSF_SIG * 0.257") 234 sqlLine.group("psfFlux", "PSF_INST_FLUX / " + extTimeString) 235 sqlLine.group("psfFluxErr", "PSF_INST_FLUX_SIG / " + extTimeString) 236 # if (self.id >= 982483): #we don't have PSF_FWHM_MAJ or MIN or PSF_CORE 237 # sqlLine.group("psfMajorFWHM", "PSF_FWHM_MAJ") 238 # sqlLine.group("psfMinorFWHM", "PSF_FWHM_MIN") 239 # sqlLine.group("psfCore", "PSF_CORE") 240 sqlLine.group("psfTheta", "PSF_THETA") 241 sqlLine.group("psfQf", "PSF_QF") 242 sqlLine.group("psfQfPerfect", "PSF_QF_PERFECT") 243 sqlLine.group("psfChiSq", "PSF_CHISQ") 244 sqlLine.group("psfLikelihood", "psfLikelihood(EXT_NSIGMA)") 245 sqlLine.group("momentXX", "MOMENTS_XX") 246 sqlLine.group("momentXY", "MOMENTS_XY") 247 sqlLine.group("momentYY", "MOMENTS_YY") 248 sqlLine.group("momentR1", "MOMENTS_R1") 249 sqlLine.group("momentRH", "MOMENTS_RH") 250 # sqlLine.group("momentM3C", "MOMENTS_M3C") 251 # sqlLine.group("momentM3S", "MOMENTS_M3S") 252 # sqlLine.group("momentM4C", "MOMENTS_M4C") 253 # sqlLine.group("momentM4S", "MOMENTS_M4S") 254 if (self.id >= 982483): 255 sqlLine.group("apFlux", "AP_FLUX / " + extTimeString) 256 sqlLine.group("apFluxErr", "AP_FLUX_SIG / " + extTimeString) 257 # sqlLine.group("apFillF", "AP_NPIX / (3.14159265359 * POW(AP_MAG_RADIUS - 0.5, 2))") 258 # sqlLine.group("apRadius", "AP_MAG_RADIUS") 259 sqlLine.group("kronFlux", "KRON_FLUX / " + extTimeString) 260 sqlLine.group("kronFluxErr", "KRON_FLUX_ERR / " + extTimeString) 261 sqlLine.group("kronRad", "MOMENTS_R1 * 2.5") 262 sqlLine.group("diffNPos", "DIFF_NPOS") 263 sqlLine.group("diffFRatio", "DIFF_FRATIO") 264 sqlLine.group("diffNBad", "DIFF_NRATIO_BAD") 265 sqlLine.group("diffNMask", "DIFF_NRATIO_MASK") 266 sqlLine.group("diffNAll", "DIFF_NRATIO_ALL") 267 sqlLine.group("diffPdist", "DIFF_R_P") 268 sqlLine.group("diffNdist", "DIFF_R_M") 269 sqlLine.group("diffPSN", "DIFF_SN_P") 270 sqlLine.group("diffNSN", "DIFF_SN_M") 271 sqlLine.group("sky", "SKY / " + extTimeString) 272 sqlLine.group("skyErr", "SKY_SIGMA / " + extTimeString) 273 sqlLine.group("infoFlag", "FLAGS") 274 sqlLine.group("infoFlag2", "FLAGS2") 275 sqlLine.group("dataRelease", str(self.skychunk.dataRelease)) 276 277 sql = sqlLine.makeRaw(") SELECT ", " FROM " + ippTableName) 278 279 try: self.scratchDb.execute(sql) 280 except: 281 self.logger.errorPair("failed sql: ", sql) 282 raise 283 284 # NOTE : Flux limits : in the current PSPS schema, negative fluxes 285 # cause problems for sql queries which work in mags as SQL cannot do 286 # something like (f < 0.0) ? -999 : -2.5*log10(f) 287 # as a result, the negative fluxes here result in floating point errors 288 # XXX EAM 2014072 : Is this still a problem? 289 # sql = "UPDATE " + pspsTableName + " SET psfFlux = 1e20 WHERE psfFlux <= 0.0" 290 # self.scratchDb.execute(sql) 291 292 # sql = "UPDATE " + pspsTableName + " SET apFlux = 1e20 WHERE apFlux <= 0.0" 293 # self.scratchDb.execute(sql) 294 295 # sql = "UPDATE " + pspsTableName + " SET kronFlux = 1e20 WHERE kronFlux <= 0.0" 296 # self.scratchDb.execute(sql) 297 298 # we don't delete these anymore 299 #results['NULLINSTFLUX'] = 0; 300 301 302 # insert stuff from dvo 303 self.logger.infoPair("inserting dvo info:find imageID"," from externID") 304 imageID = self.scratchDb.getImageIDFromExternID(self.diffSkyFileID) 305 self.logger.infoPair("updating","diffdetection") 306 sqlLine = sqlUtility("UPDATE DiffDetection as a, " + self.scratchDb.dvoDetectionTable + " as b SET ") 307 sqlLine.group("a.diffObjID", "b.objId") 308 sqlLine.group("a.diffDetID", "b.detectID") 309 sqlLine.group("a.ippObjID","b.ippObjID") 310 sqlLine.group("a.dvoRegionID", "b.catID") 311 sqlLine.group("a.ra", "b.ra") 312 sqlLine.group("a.dec", "b.dec_") 313 sqlLine.group("a.raErr", "b.raErr") 314 sqlLine.group("a.decErr", "b.decErr") 315 316 sqlLine.group("a.zp","b.zp") 317 sqlLine.group("a.telluricExt", "b.telluricExt") 318 sqlLine.group("a.airmass","b.airmass") 319 320 321 sql = sqlLine.makeEquals("WHERE a.ippDetectID = b.ippDetectID AND b.imageID = " +str( imageID)) 322 323 try: self.scratchDb.execute(sql) 324 except: 325 self.logger.errorPair("failed sql:",sql) 326 raise 327 self.logger.infoPair("need to cull"," nulls objid") 328 results= self.scratchDb.reportAndDeleteRowsWithNULLS("DiffDetection", "diffObjID") 329 self.logger.infoPair("adding","uniquePSPSDFid") 330 self.updatePspsUniqueIDs("DiffDetection") 331 332 ''' 333 Populates the DiffToImage table 334 ''' 335 def populateDiffToImage(self): 336 337 self.logger.infoPair("Procesing table", "DiffToImage") 338 339 imageIDs = self.gpc1Db.getImageIDsForThisDiffID(self.diffSkyFileID) 340 341 for imageID in imageIDs: 342 343 sql = "INSERT INTO DiffToImage (diffMetaID, imageID) \ 344 VALUES (\ 345 " + str(self.diffSkyFileID) + ", " + imageID + ")" 346 self.scratchDb.execute(sql) 347 348 # now update StackMeta with correct number of inputs 349 #sql = "UPDATE "+filter+"StackMeta SET nP2Images = (SELECT COUNT(distinct(floor(imageID/100))) FROM StackToImage where stackMetaID = "+str(stackmetaID)+")" 350 #self.scratchDb.execute(sql) 351 352 #self.tablesToExport.append("DiffToImage") 353 354 355 356 357 358 359 360 ''' 361 Applies indexes and other constraints to the PSPS tables 362 ''' 363 def alterPspsTables(self): 364 365 self.logger.debug("Altering PSPS tables") 366 self.logger.debug("Creating indexes on PSPS tables") 367 self.scratchDb.makeColumnUnique("DiffDetection", "objID") 368 self.scratchDb.makeColumnPrimaryKey("DiffDetection", "ippDetectID") 369 370 #self.populateDiffMeta() 371 372 # dictionary objects to hold imageIDs for later 373 self.imageIDs = {} 374 self.sourceIDs = {} 375 376 # loop through all OTAs and populate ImageMeta extensions 377 # the column in PSPS 378 self.scratchDb.execute("ALTER TABLE DiffDetection CHANGE dec_ `dec` double") 379 380 return True 381 382 383 ''' 384 Applies indexes to the IPP tables 385 ''' 386 def indexIppTables(self): 387 388 self.logger.infoPair("Creating indexes on", "IPP tables") 389 390 #self.scratchDb.createIndex(extension, "IPP_IDET") 391 # try the test Chip 392 self.scratchDb.createIndex("SkyChip_psf", "IPP_IDET") 393 394 self.logger.infoPair("created indexes on", "IPP tables") 395 396 ''' 397 Updates provided table with DVO IDs from DVO table 398 ''' 399 def updateDvoIDs(self, table, externID): 400 401 imageID = self.scratchDb.getImageIDFromExternID(externID) 402 self.logger.debug("Updating table '" + table + "' with DVO IDs using imageID = %d" % imageID) 403 404 sql = "UPDATE IGNORE " + table + " AS a, " + self.scratchDb.dvoDetectionTable + " AS b SET \ 405 a.objID = b.objID, \ 406 a.detectID = b.detectID, \ 407 a.ippObjID = b.ippObjID, \ 408 a.dvoRegionID = b.catID, \ 409 a.ra = b.ra, \ 410 a.dec = b.dec_, \ 411 a.zp = b.zp, \ 412 a.telluricExt = b.telluricExt, \ 413 a.airmass = b.airmass, \ 414 a.expTime = b.expTime, \ 415 a.infoFlag2 = (b.flags << 13) | a.infoFlag2 \ 416 WHERE a.ippDetectID = b.ippDetectID \ 417 AND b.imageID = " + str(imageID) 418 419 self.scratchDb.execute(sql) 420 421 ''' 422 Updates table and generates pspsuniqueids 423 ''' 424 425 def updatePspsUniqueIDs(self,table): 426 sql = "UPDATE "+table+" join (select @r:=@r+1 rownum, diffobjID from \ 427 (select @r:=0) r, "+table+" t) as foo using (diffobjID) set \ 428 uniquePspsDFid = ((" +str(self.batchID)+ "*1000000000 ) + rownum)" 429 try: self.scratchDb.execute(sql) 430 except: 431 self.logger.errorPair('failed sql',sql) 432 raise 433 434 ''' 435 Does the processing, i.e. pulling stuff from IPP tables into PSPS tables 436 ''' 437 438 ''' 439 Does the processing, i.e. pulling stuff from IPP tables into PSPS tables 440 ''' 441 def populatePspsTables(self): 442 self.logger.infoPair("starting","populatePspsTables for diffBatch") 443 # loop through all OTAs again to update with DVO IDs 444 self.skipBatch = False 445 self.tablesToExport = [] 446 self.tablesToExport.append("DiffMeta") 447 self.populateDiffMeta() 448 self.logger.infoPair("populated","DiffMeta") 449 self.tablesToExport.append("DiffToImage") 450 self.populateDiffToImage() 451 self.logger.infoPair("populated","DiffToImage") 452 self.tablesToExport.append("DiffDetection") 453 self.populateDiffDetectionTable() 454 self.logger.infoPair("populated","DiffDetection") 455 456 457 458 459 self.setMinMaxDiffObjID(["DiffDetection"]) 460 461 462 #test = self.scratchDb.getRowCount("Object") 463 #return False 464 465 return True 466 467 468 ''' 469 Imports IPP tables from FITS file 470 Accepts a regular expression to match the tables so not all tables need to be imported 471 (This regex feature is not currently used...) 472 ''' 473 def importIppTables(self, columns="*", tableRE=""): 474 475 if self.config.retry: return True 476 477 self.logger.infoPair("Importing DF tables with table match expression: ", tableRE) 478 479 count = 0 480 fileName = self.fits.getPath() 481 482 self.logger.infoPair("using filename:",fileName) 483 484 try: 485 tables = stilts.treads(fileName) 486 except: 487 self.logger.errorPair("STILTS could not import from", fileName) 488 return False 489 490 # count = 0 491 for table in tables: 492 493 match = re.match(tableRE, table.name) 494 if not match: continue 495 496 self.logger.infoPair("Reading IPP table", table.name) 497 table = stilts.tpipe(table, cmd='addcol table_index $0') 498 table = stilts.tpipe(table, cmd='explodeall') 499 500 # drop any previous tables before import 501 self.scratchDb.dropTable(table.name) 502 503 504 # IPP FITS files are littered with infinities, so remove these 505 self.logger.info("Removing Infinity values from all columns") 506 table = stilts.tpipe(table, cmd='keepcols "' + columns + '"') 507 table = stilts.tpipe(table, cmd='replaceval -Infinity null *') 508 table = stilts.tpipe(table, cmd='replaceval Infinity null *') 509 510 try: 511 table.write(self.scratchDb.url + '#' + table.name) 512 count = count + 1 513 except: 514 self.logger.exception("Problem writing table '" + table.name + "' to the database") 515 516 self.logger.infoPair("Done. Imported", "%d tables" % count) 517 self.indexIppTables() 518 519 return True 520 521 522 523 524 525 526 ''' 527 Overriding this method. Use regex to trim off, eg _XY33 extension 528 ''' 529 def exportPspsTablesToFits(self, regex="(.*)"): 530 return super(DiffBatch, self).exportPspsTablesToFits("([a-zA-Z]+)") 531 532 533 ''' 534 Drop a table and report hte drop 535 ''' 536 def dropTableVerbose(self, table): 537 self.logger.infoPair("dropping table:",table) 538 self.scratchDb.dropTable(table) 539
Note:
See TracChangeset
for help on using the changeset viewer.
