IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Ignore:
Timestamp:
Dec 14, 2014, 5:30:49 PM (12 years ago)
Author:
heather
Message:

diff batch progress (sas 37) - metadata is correct, diff detection is in but needs testing

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/ippToPsps/jython/diffbatch.py

    r36697 r37748  
     1#!/usr/bin/env jython
     2
     3import os.path
     4import sys
     5import glob
     6import time
     7import stilts
     8
     9from java.lang import *
     10from java.sql import *
     11
     12from java.lang import Math
     13from org.apache.commons.math.special import Erf
     14
     15from xml.etree.ElementTree import ElementTree, Element, tostring
     16
     17from batch import Batch
     18from gpc1db import Gpc1Db
     19from ipptopspsdb import IppToPspsDb
     20from scratchdb import ScratchDb
     21from sqlUtility import sqlUtility
     22
     23import logging.config
     24
     25'''
     26DiffBatch class
     27
     28This class, a sub-class of Batch, processes single exposures in the form of IPP smf files
     29
     30'''
     31class 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.fits = gpc1Db.getDiffStageCmf(skychunk.dvoLabel, diffSkyFileID)
     77       self.header = self.fits.getPrimaryHeader()
     78       tessName = self.getKeyValue(self.header, 'TESS_ID')
     79       self.tessID = self.scratchDb.getTessID(tessName)
     80
     81
     82       # XXX EAM 20140812 : I am hardwiring the parsing logic for RINGS vs LOCAL
     83       if tessName == 'RINGS.V3':
     84           # skycell is, eg "skycell.1133.081"
     85           #                 0123456789012345
     86           self.projectionID = self.skycellName[8:12]
     87           self.skycellID = self.skycellName[13:]
     88       else:
     89           # skycell is, eg "skycell.081"
     90           #                 01234567890
     91           self.projectionID = 0
     92           self.skycellID = self.skycellName[8:11]
     93       if self.skycellID == "":
     94           self.skycellID = -1
     95
     96
     97       # drop the existing tables   
     98
     99       self.dropTableVerbose("DiffMeta")
     100       self.dropTableVerbose("DiffToImage")
     101       self.dropTableVerbose("DiffDetection")
     102
     103       
     104
     105
     106       self.logger.infoPair("I can haz",diffSkyFileID)
     107
     108
     109
     110       if not self.analVer: self.analVer = -999
     111
     112       # create an output filename, which is {expID}.FITS
     113       self.outputFitsFile = "%08d.FITS" % self.diffSkyFileID
     114       self.outputFitsPath = "%s/%s" % (self.localOutPath, self.outputFitsFile)
     115       print "got here"
     116       self.photoCalID = str(self.scratchDb.getPhotoCalID(self.diffSkyFileID))
     117       print "got photocalid"
     118       self.calibModNum = 0;
     119       self.dataRelease = skychunk.dataRelease;
     120       
     121       self.filterID = self.scratchDb.getFilterID(self.filterName[0])
     122       
     123       print self.filterName
     124       print self.filterName[0]
     125       print self.filterID
     126        # insert what we know about this stack batch into the stack table
     127       self.ippToPspsDb.insertDiffMeta(self.batchID, self.filterName[0], self.difftypeID)
     128
     129       # dump stuff to log
     130       self.logger.infoPair("diff_skyfile_ID", "%d" % self.diffSkyFileID)
     131
     132
     133    '''
     134    Populates the FrameMeta table, mainly from dictionary values found in IPP FITS header
     135    '''
     136    def populateDiffMeta(self):
     137        self.logger.infoPair("Proccesing table", "DiffMeta")
     138
     139        sqlLine = sqlUtility("INSERT INTO DiffMeta (")
     140
     141        sqlLine.group("diffMetaID",            str(self.diffSkyFileID));
     142        sqlLine.group("difftypeID",            self.difftypeID);
     143        sqlLine.group("posImageID",            self.posImageID);
     144        sqlLine.group("negImageID",            self.negImageID);
     145        sqlLine.group("skycellID",             self.skycellID);
     146        sqlLine.group("photoCalID",            self.photoCalID);
     147        sqlLine.group("magSat",                self.getKeyFloat(self.header, "%.8f", 'FSATUR'));
     148        sqlLine.group("analVer",               str(self.analVer));
     149        sqlLine.group("expTime",               self.expTime);
     150        sqlLine.group("ctype1",                self.getKeyValue(self.header, 'CTYPE1'));
     151        sqlLine.group("ctype2",                self.getKeyValue(self.header, 'CTYPE2'));
     152        sqlLine.group("crval1",                self.getKeyFloat(self.header, "%.8f", 'CRVAL1'));
     153        sqlLine.group("crval2",                self.getKeyFloat(self.header, "%.8f", 'CRVAL2'));
     154        sqlLine.group("crpix1",                self.getKeyFloat(self.header, "%.8f", 'CRPIX1'));
     155        sqlLine.group("crpix2",                self.getKeyFloat(self.header, "%.8f", 'CRPIX2'));
     156        sqlLine.group("cdelt1",                self.getKeyFloat(self.header, "%.8e", 'CDELT1'));
     157        sqlLine.group("cdelt2",                self.getKeyFloat(self.header, "%.8e", 'CDELT2'));
     158        sqlLine.group("pc001001",              self.getKeyFloat(self.header, "%.8e", 'PC001001'));
     159        sqlLine.group("pc001002",              self.getKeyFloat(self.header, "%.8e", 'PC001002'));
     160        sqlLine.group("pc002001",              self.getKeyFloat(self.header, "%.8e", 'PC002001'));
     161        sqlLine.group("pc002002",              self.getKeyFloat(self.header, "%.8e", 'PC002002'));
     162
     163        sql = sqlLine.make(") VALUES ( ", ")")
     164
     165        try: self.scratchDb.execute(sql)
     166        except:
     167            self.logger.errorPair('failed sql: ', sql)
     168            raise
     169        self.logger.infoPair("DiffMeta","final stuff")
     170        self.scratchDb.updateAllRows("DiffMeta", "batchID", str(self.batchID))
     171        self.scratchDb.updateAllRows("DiffMeta", "surveyID", str(self.surveyID))
     172        self.scratchDb.updateFilterID("DiffMeta", self.filterName[0])
     173        self.scratchDb.updateAllRows("DiffMeta", "calibModNum", str(self.calibModNum))
     174        self.scratchDb.updateAllRows("DiffMeta", "dataRelease", str(self.skychunk.dataRelease))
     175        self.logger.infoPair("DiffMeta","done")
     176
     177    '''
     178    Populates the Diff table for this OTA
     179    '''
     180    def populateDiffTable(self, ota, results):
     181
     182        pspsTableName = "DiffDetection"
     183        ippTableName =  "diff_psf"
     184       
     185        results['ORIGINALTOTAL'] = self.scratchDb.getRowCount(ippTableName)
     186
     187        # drop then re-create table
     188        self.scratchDb.dropTable(pspsTableName)
     189        sql = "CREATE TABLE " + pspsTableName + " LIKE DiffDetection"
     190        try: self.scratchDb.execute(sql)
     191        except: pass
     192       
     193        # XXX we no longer delete detections with funny mags (eg PSF_INST_MAG < -17.5)
     194        # for examples of code which do this, go to r35097 or earlier
     195
     196        BEFORE = self.scratchDb.getRowCount(ippTableName)
     197        results['SATDET'] = 0
     198
     199        extTimeString = str(self.expTime)
     200
     201        # insert all detections into table : do NOT include the IGNORE unless we have to
     202        # sqlLine = sqlUtility("INSERT IGNORE INTO " + pspsTableName + " (")
     203        sqlLine = sqlUtility("INSERT INTO " + pspsTableName + " (")
     204
     205        # XXX WARNING: need to apply platescale to convert sizes to arcsec
     206        # XXX apFluxF or apFluxNpix + apFluxRadius?
     207
     208        sqlLine.group("ippDetectID",     "IPP_IDET")                                               
     209        sqlLine.group("randomDiffID",     "FLOOR(RAND("+str(self.batchID)+")*9223372036854775807)")                       
     210        sqlLine.group("filterID",        str(self.filterID))                                       
     211        sqlLine.group("surveyID",        str(self.surveyID))                                       
     212        ##sqlLine.group("obsTime",         str(self.obsTime))     I have expTime
     213        sqlLine.group("expTime",         str(self.expTime))                                   
     214        sqlLine.group("xPos",            "X_PSF")                                                   
     215        sqlLine.group("yPos",            "Y_PSF")                                                   
     216        sqlLine.group("xPosErr",         "X_PSF_SIG")                                               
     217        sqlLine.group("yPosErr",         "Y_PSF_SIG")                                               
     218        if (self.id >= 982483):
     219            sqlLine.group("pltScale",        "PLTSCALE")                                     
     220            sqlLine.group("posAngle",        "POSANGLE")                                     
     221#            sqlLine.group("raErr",           "X_PSF_SIG * abs(PLTSCALE)")
     222#            sqlLine.group("decErr",          "Y_PSF_SIG * abs(PLTSCALE)")
     223        else:
     224            sqlLine.group("pltScale",        "0.257")                                     
     225            sqlLine.group("posAngle",        "-999")                                     
     226#            sqlLine.group("raErr",           "X_PSF_SIG * 0.257")
     227#            sqlLine.group("decErr",          "Y_PSF_SIG * 0.257")
     228        sqlLine.group("psfFlux",         "PSF_INST_FLUX / " + extTimeString)
     229        sqlLine.group("psfFluxErr",      "PSF_INST_FLUX_SIG / " + extTimeString)
     230        if (self.id >= 982483):
     231            sqlLine.group("psfMajorFWHM",    "PSF_FWHM_MAJ")                                               
     232            sqlLine.group("psfMinorFWHM",    "PSF_FWHM_MIN")                                               
     233            sqlLine.group("psfCore",         "PSF_CORE")                                                   
     234        sqlLine.group("psfTheta",        "PSF_THETA")                                               
     235        sqlLine.group("psfQf",           "PSF_QF")                                                 
     236        sqlLine.group("psfQfPerfect",    "PSF_QF_PERFECT")                               
     237        sqlLine.group("psfChiSq",        "PSF_CHISQ")                                     
     238        sqlLine.group("psfLikelihood",   "psfLikelihood(EXT_NSIGMA)")                               
     239        sqlLine.group("momentXX",        "MOMENTS_XX")                                             
     240        sqlLine.group("momentXY",        "MOMENTS_XY")                                             
     241        sqlLine.group("momentYY",        "MOMENTS_YY")                                             
     242        sqlLine.group("momentR1",        "MOMENTS_R1")                                             
     243        sqlLine.group("momentRH",        "MOMENTS_RH")                                             
     244#        sqlLine.group("momentM3C",       "MOMENTS_M3C")                                             
     245#        sqlLine.group("momentM3S",       "MOMENTS_M3S")                                             
     246#        sqlLine.group("momentM4C",       "MOMENTS_M4C")                                             
     247#        sqlLine.group("momentM4S",       "MOMENTS_M4S")                                             
     248        if (self.id >= 982483):
     249            sqlLine.group("apFlux",          "AP_FLUX / " + extTimeString)
     250            sqlLine.group("apFluxErr",       "AP_FLUX_SIG / " + extTimeString)
     251            sqlLine.group("apFillF",         "AP_NPIX / (3.14159265359 * POW(AP_MAG_RADIUS - 0.5, 2))")
     252 #       sqlLine.group("apRadius",        "AP_MAG_RADIUS")
     253        sqlLine.group("kronFlux",        "KRON_FLUX / " + extTimeString)
     254        sqlLine.group("kronFluxErr",     "KRON_FLUX_ERR / " + extTimeString)
     255        sqlLine.group("kronRad",         "MOMENTS_R1 * 2.5")
     256        sqlLine.group("diffNPos",         "DIFF_NPOS")
     257        sqlLine.group("diffFRatio",         "DIFF_FRATIO")
     258        sqlLine.group("diffNBad",         "DIFF_NRATIO_BAD")
     259        sqlLine.group("diffNMask",         "DIFF_NRATIO_MASK")
     260        sqlLine.group("diffNAll",         "DIFF_NRATIO_ALL")
     261        sqlLine.group("diffPdist",         "DIFF_R_P")
     262        sqlLine.group("diffNdist",         "DIFF_R_M")
     263        sqlLine.group("diffPSN",         "DIFF_SN_P")
     264        sqlLine.group("diffNSN",         "DIFF_SN_M")
     265        sqlLine.group("sky",             "SKY  / " + extTimeString)
     266        sqlLine.group("skyErr",          "SKY_SIGMA  / " + extTimeString)
     267        sqlLine.group("infoFlag",        "FLAGS")                         
     268        sqlLine.group("infoFlag2",       "FLAGS2")                         
     269        sqlLine.group("dataRelease",     str(self.skychunk.dataRelease))                 
     270
     271        sql = sqlLine.makeRaw(") SELECT ", " FROM " + ippTableName)
     272
     273        try: self.scratchDb.execute(sql)
     274        except:
     275            self.logger.errorPair("failed sql: ", sql)
     276            raise
     277
     278        # NOTE : Flux limits : in the current PSPS schema, negative fluxes
     279        # cause problems for sql queries which work in mags as SQL cannot do
     280        # something like (f < 0.0) ? -999 : -2.5*log10(f)
     281        # as a result, the negative fluxes here result in floating point errors
     282        # XXX EAM 2014072 : Is this still a problem?
     283 #       sql = "UPDATE " + pspsTableName + " SET psfFlux = 1e20 WHERE psfFlux <= 0.0"
     284 #       self.scratchDb.execute(sql)
     285       
     286 #       sql = "UPDATE " + pspsTableName + " SET apFlux = 1e20 WHERE apFlux <= 0.0"
     287 #       self.scratchDb.execute(sql)
     288
     289 #       sql = "UPDATE " + pspsTableName + " SET kronFlux = 1e20 WHERE kronFlux <= 0.0"
     290 #       self.scratchDb.execute(sql)
     291
     292        # we don't delete these anymore
     293        results['NULLINSTFLUX'] = 0;
     294
     295
     296# insert stuff from dvo
     297
     298
     299
     300    '''
     301    Applies indexes and other constraints to the PSPS tables
     302    '''
     303    def alterPspsTables(self):
     304
     305        self.logger.debug("Altering PSPS tables")
     306        self.logger.debug("Creating indexes on PSPS tables")
     307        self.scratchDb.makeColumnUnique("DiffDetection", "objID")
     308        self.scratchDb.makeColumnPrimaryKey("DiffDetection", "ippDetectID")
     309
     310        self.populateDiffMeta()
     311     
     312        # dictionary objects to hold imageIDs for later
     313        self.imageIDs = {}
     314        self.sourceIDs = {}
     315
     316        # loop through all OTAs and populate ImageMeta extensions
     317        # the column in PSPS
     318        self.scratchDb.execute("ALTER TABLE DiffDetection CHANGE dec_ `dec` double")
     319
     320        return True
     321
     322
     323    '''
     324    Applies indexes to the IPP tables
     325    '''
     326    def indexIppTables(self):
     327
     328        self.logger.infoPair("Creating indexes on", "IPP tables")
     329
     330        self.scratchDb.createIndex(extension, "IPP_IDET")
     331        # try the test Chip
     332        self.scratchDb.createIndex("Chip_psf", "IPP_IDET")
     333
     334        self.logger.infoPair("created indexes on", "IPP tables")     
     335
     336    '''
     337    Updates provided table with DVO IDs from DVO table
     338    '''
     339    def updateDvoIDs(self, table, externID):
     340
     341        imageID = self.scratchDb.getImageIDFromExternID(externID)
     342        self.logger.debug("Updating table '" + table + "' with DVO IDs using imageID = %d" % imageID)
     343
     344        sql = "UPDATE IGNORE " + table + " AS a, " + self.scratchDb.dvoDetectionTable + " AS b SET \
     345               a.objID        = b.objID, \
     346               a.detectID     = b.detectID, \
     347               a.ippObjID     = b.ippObjID, \
     348               a.dvoRegionID  = b.catID, \
     349               a.ra           = b.ra, \
     350               a.dec          = b.dec_, \
     351               a.zp           = b.zp, \
     352               a.telluricExt  = b.telluricExt, \
     353               a.airmass      = b.airmass, \
     354               a.expTime      = b.expTime, \
     355               a.infoFlag2    = (b.flags << 13) | a.infoFlag2 \
     356               WHERE a.ippDetectID = b.ippDetectID \
     357               AND b.imageID = " + str(imageID)
     358
     359        self.scratchDb.execute(sql)
     360
     361    '''
     362    Updates table and generates pspsuniqueids
     363    '''
     364
     365    def updatePspsUniqueIDs(self,table):
     366        sql = "UPDATE "+table+" join (select @r:=@r+1 rownum, objID from \
     367        (select @r:=0) r, "+table+" t) as foo using (objID) set \
     368        uniquePspsP2id = ((" +str(self.batchID)+ "*1000000000 ) + rownum)"
     369        try: self.scratchDb.execute(sql)
     370        except:
     371            self.logger.errorPair('failed sql',sql)
     372            return
     373       
     374    '''
     375    Does the processing, i.e. pulling stuff from IPP tables into PSPS tables
     376    '''
     377    def populatePspsTablesChip(self, chipname, x, y, results, tables):
     378        # XXX EAM NOTE: drop tables Detection_* here so
     379        # they do not polute the db?
     380        # XXX or put an explicit drop at the end of the loop?
     381
     382        # self.logger.infoTitle("Processing " + chipname)
     383        # this is a bit crude: if the chip is not present, this test will fail and the chip
     384        # will be (correctly) skipped.  would be better to carry that information explicitly ("chip is missing")
     385
     386        # XXX keep this in or not?
     387        # if not self.scratchDb.astrometricSolutionOK(chipname):
     388        #     self.logger.info("| %5s |            ------------- Bad astrometric solution : rejecting ------------                    |" % chipname)
     389        #     return False
     390
     391        # does this chip exist in the DVO image table (if NOT, then skip it)
     392        if not self.scratchDb.haveThisChip(self.imageIDs[chipname], self.sourceIDs[chipname]):
     393            self.logger.info("| %5s |            ------------- Chip not in DVO : rejecting ------------                    |" % chipname)
     394            return False
     395
     396        #self.logger.info("populate stuff ");
     397        # populate remainder of tables
     398        self.populateDetectionTable(chipname, results)
     399        #self.logger.info("successful populate ");
     400        # now add DVO IDs
     401        self.updateDvoIDs("Detection_" + chipname, self.imageIDs[chipname])
     402        #self.logger.info("updated dvoids")
     403        results['NULLOBJID'] = self.scratchDb.reportAndDeleteRowsWithNULLS("Detection_" + chipname, "objID")
     404        #self.logger.info("deleted nulls")
     405        self.logger.info("add psps unique p2 ids")
     406        self.updatePspsUniqueIDs("Detection_" + chipname, self.imageIDs[chipname])
     407        self.updateImageID("Detection_" + chipname, x, y)
     408        #self.logger.info("updateImageId")
     409        rowCount = self.scratchDb.getRowCount("Detection_" + chipname)
     410        #self.logger.info("got row count")
     411        self.logger.info("| %5s | %13d | %13d | %13d | %13d | %13d |",
     412                chipname,
     413                results['ORIGINALTOTAL'],
     414                results['SATDET'],
     415                results['NULLINSTFLUX'],
     416                results['NULLOBJID'],
     417                rowCount)
     418        self.totalOriginal     = self.totalOriginal + results['ORIGINALTOTAL']
     419        self.totalSatDet       = self.totalSatDet + results['SATDET']
     420        self.totalNulIInstFlux = self.totalNulIInstFlux + results['NULLINSTFLUX']
     421        self.totalNullObjID    = self.totalNullObjID + results['NULLOBJID']
     422        self.totalDetections   = self.totalDetections + rowCount
     423
     424        fractionKept = float(rowCount) / float(results['ORIGINALTOTAL'])
     425        # print "kept ", str(fractionKept), " detections from ", chipname
     426
     427        if fractionKept < 0.8:
     428            # print "Too many rejected detections (", str(fractionKept), ", fail on exposure for", chipname
     429            self.logger.infoPair("Too many rejected detections, fail on exposure for", chipname)
     430            self.skipBatch = True
     431            return False;
     432
     433        #self.logger.info("updated totals")
     434        # check we have something in this Detection table TODO add this to table above
     435        if rowCount < 1:
     436            self.logger.infoPair("Empty table for chip, fail on exposure", chipname)
     437            self.skipBatch = True
     438            return False;
     439
     440        # update ImageMeta with count of detections for this CHIPNAME and photoCodeID
     441        sql = "UPDATE ImageMeta_" + chipname + " \
     442               SET nDetect = %d, photoCalID = %d" % (self.scratchDb.getRowCount("Detection_" + chipname), self.scratchDb.getPhotoCalID(self.imageIDs[chipname]))
     443        self.scratchDb.execute(sql)
     444       
     445        # add these to list of tables to export later
     446        self.tablesToExport.append("ImageMeta_" + chipname)
     447        self.logger.info("export ImageMeta")
     448
     449        self.tablesToExport.append("Detection_" + chipname)
     450        self.logger.info("export Detection")
     451
     452        tables.append("Detection_" + chipname)
     453        self.logger.info("updated detection")
     454
     455        self.validChips.append(chipname)
     456
     457        return True
     458
     459    '''
     460    Does the processing, i.e. pulling stuff from IPP tables into PSPS tables
     461    '''
     462    def populatePspsTables(self):
     463
     464        # loop through all OTAs again to update with DVO IDs
     465        self.skipBatch = False
     466        self.validChips = []   
     467        self.tablesToExport = []   
     468        self.tablesToExport.append("DiffMeta")
     469        tables = []   
     470        otaCount = 0
     471        results = {}
     472        self.totalOriginal = self.totalSatDet = self.totalNulIInstFlux = self.totalNullPeakFlux = self.totalNullObjID = self.totalDetections = 0
     473        self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+")
     474        self.logger.info("|  OTA  | Initial total |   Sat Det     | NULL instFlux | NULL obj ID   |  Remainder    |")
     475        self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+")
     476        for x in range(self.startX, self.endX):
     477            for y in range(self.startY, self.endY):
     478               
     479                # dodge the corners
     480                if x==0 and y==0: continue
     481                if x==0 and y==7: continue
     482                if x==7 and y==0: continue
     483                if x==7 and y==7: continue
     484
     485                ota = "XY%d%d" % (x, y)
     486                if ota not in self.imageIDs: continue
     487
     488                if False and self.config.test and not ((x == 0) and (y == 1)):
     489                    print "skipping ota " + ota
     490                    continue
     491
     492                if self.populatePspsTablesChip(ota, x, y, results, tables): otaCount = otaCount + 1
     493                if self.skipBatch:
     494                    self.logger.error("fatal problem for exposure, skipping")
     495                    return False
     496
     497        if "Chip" in self.imageIDs:
     498            if self.populatePspsTablesChip("Chip", 0, 0, results, tables): otaCount = otaCount + 1
     499            if self.skipBatch:
     500                self.logger.error("fatal problem for exposure, skipping")
     501                return False
     502
     503        # print totals
     504        self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+")
     505        self.logger.info("| Total | %13d | %13d | %13d | %13d | %13d | %13d |",
     506                self.totalOriginal,
     507                self.totalSatDet,
     508                self.totalNulIInstFlux,
     509                self.totalNullPeakFlux,
     510                self.totalNullObjID,
     511                self.totalDetections)
     512        self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+")
     513
     514        # if we only have one table export, i.e. FrameMeta, then get out of here (skip batch, but do not abort)
     515        if len(self.tablesToExport) == 1:
     516            self.skipBatch = True
     517            self.logger.error("No tables to export")
     518            return False
     519
     520        # XXX EAM : turn this on (and fix up the code) if we need it
     521        # self.removeDuplicateObjects()
     522
     523        self.setMinMaxObjID(tables)
     524
     525        # update FrameMeta with count OTAs in this file and total number of photometric reference sources
     526        sql = "UPDATE FrameMeta SET nOTA = %d, numPhotoRef = %d" % (otaCount, self.totalNumPhotoRef)
     527        self.scratchDb.execute(sql)
     528        #to make it stop
     529        #test = self.scratchDb.getRowCount("Object")
     530        #return False
     531       
     532        return True
     533
     534    def removeDuplicateObjects(self):
     535
     536        sql = "DROP TABLE SkinnyObject_All"
     537        try:
     538            self.scratchDb.execute(sql)
     539        except:
     540            print "SkinnyObject_All table not yet defined"
     541
     542        sql = "CREATE TABLE SkinnyObject_All (objID bigint, ippObjID bigint, chipID char(16))"
     543        try:
     544            self.scratchDb.execute(sql)
     545        except:
     546            print "failed to create table SkinnyObject_All"
     547            raise
     548
     549        for chipname in self.validChips:
     550           
     551            sql = "INSERT INTO SkinnyObject_All (objID, ippObjID, chipID) \
     552                   SELECT objID, ippObjID, '" + chipname + "' from SkinnyObject_" + chipname
     553            try:
     554                self.scratchDb.execute(sql)
     555            except:
     556                print "failed to insert entry SkinnyObject_All: ", chipname
     557                raise
     558           
     559
     560        Nduplicates = 0
     561        sql = "SELECT n, objID from (select count(objID) as n, objID from SkinnyObject_All group by objID) as tmp where n > 1"
     562        try:
     563            rs = self.scratchDb.executeQuery(sql)
     564            while (rs.next()):
     565                objID = rs.getInt(1)
     566                chipID = rs.getString(3)
     567                print "delete: ", str(objID), chipID
     568                Nduplicates += 1
     569
     570            rs.close()
     571        except:
     572            print "failed to get duplicates"
     573            raise
     574
     575        print "duplicates found: ", str(Nduplicates)
     576
     577    '''
     578    Updates imageID {EXP_ID}{OTA} in the provided table
     579    '''
     580    def updateImageID(self, tableName, x, y):
     581
     582        sql = "UPDATE " + tableName + " SET imageID = %d%d%d" % (self.expID, x, y)
     583        self.scratchDb.execute(sql)
     584
     585    '''
     586    Overriding this method
     587    '''
     588    def reportNullsInAllPspsTables(self, showPartials):
     589
     590        # loops round all imported tables, but we want to check one OTA's worth
     591        for table in self.pspsTables:
     592            if table.name == "FrameMeta": self.scratchDb.reportNulls(table.name, showPartials)
     593            else: self.scratchDb.reportNulls(table.name + "_XY33", showPartials)
     594
     595
     596    '''
     597    This function reads the cmf/smf file and loads it into the database as its own table
     598    Overriding this method. Filter to only import *.psf extensions
     599    '''
     600    def importIppTables(self, filter=""):
     601       
     602        regex = ".*.psf"
     603        if False and self.config.test and self.config.camera == "gpc1":
     604            regex = "XY01.psf"
     605           
     606        print "my ID: " + str(self.id)
     607
     608        if (self.id < 982483):
     609            # XXX EAM NOTE : this is fragile : requires PS1_V4
     610            columns = "IPP_IDET X_PSF Y_PSF X_PSF_SIG Y_PSF_SIG                   PSF_INST_FLUX PSF_INST_FLUX_SIG       PSF_MAJOR PSF_MINOR PSF_THETA          PSF_QF PSF_QF_PERFECT PSF_CHISQ EXT_NSIGMA MOMENTS_XX MOMENTS_XY MOMENTS_YY MOMENTS_R1 MOMENTS_RH MOMENTS_M3C MOMENTS_M3S MOMENTS_M4C MOMENTS_M4S                             AP_MAG_RADIUS KRON_FLUX KRON_FLUX_ERR SKY SKY_SIGMA FLAGS FLAGS2"
     611        else:
     612            # XXX EAM NOTE : this is fragile : requires PS1_V5
     613            columns = "IPP_IDET X_PSF Y_PSF X_PSF_SIG Y_PSF_SIG POSANGLE PLTSCALE PSF_INST_FLUX PSF_INST_FLUX_SIG PSF_FWHM_MAJ PSF_FWHM_MIN PSF_THETA PSF_CORE PSF_QF PSF_QF_PERFECT PSF_CHISQ EXT_NSIGMA MOMENTS_XX MOMENTS_XY MOMENTS_YY MOMENTS_R1 MOMENTS_RH MOMENTS_M3C MOMENTS_M3S MOMENTS_M4C MOMENTS_M4S AP_FLUX AP_FLUX_SIG AP_NPIX AP_MAG_RADIUS KRON_FLUX KRON_FLUX_ERR SKY SKY_SIGMA FLAGS FLAGS2"
     614
     615        return super(DetectionBatch, self).importIppTables(columns, regex)
     616
     617    '''
     618    Overriding this method. Use regex to trim off, eg _XY33 extension
     619    '''
     620    def exportPspsTablesToFits(self, regex="(.*)"):
     621       return super(DetectionBatch, self).exportPspsTablesToFits("([a-zA-Z]+)")
Note: See TracChangeset for help on using the changeset viewer.