IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Changeset 37748


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

Location:
trunk/ippToPsps
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • trunk/ippToPsps/config/tables.DF.vot

    r37592 r37748  
    3636        <DESCRIPTION>saturation magnitude level</DESCRIPTION>
    3737      </FIELD>
    38       <FIELD name="analVer" arraysize="1" datatype="short" unit="dimensionless" default="-999">
     38      <FIELD name="analVer" arraysize="100" datatype="char" unit="alphanumeric" default="-999">
    3939        <DESCRIPTION>analysis version index</DESCRIPTION>
    4040      </FIELD>
  • 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]+)")
  • trunk/ippToPsps/jython/gpc1db.py

    r37551 r37748  
    108108                   AND mjd_obs <= (to_days('" + tend + "') - 678941) "
    109109           # self.logger.infoPair("sql",sql)     
    110         elif batchType == "DF":
     110        elif batchType == "DF":            # this is specifically only for WARPSTACK types of diffs -
     111            # it only makes sense for the date to come from the warp1
     112            # may need to be more clever if we do other types of diffs
    111113
    112114            stage = "diff"
    113             sql = "SELECT stuff from stufftable"
     115            sql = "SELECT DISTINCT stage_extra1, radeg,decdeg \
     116                   FROM addRun \
     117                   JOIN addProcessedExp using (add_id) \
     118                   JOIN minidvodbRun using (minidvodb_name) \
     119                   JOIN minidvodbProcessed using (minidvodb_id)  \
     120                   JOIN mergedvodbRun using (minidvodb_id) \
     121                   JOIN mergedvodbProcessed using (merge_id) \
     122                   JOIN diffInputSkyfile \
     123                   ON (diff_id = stage_id AND diff_skyfile_id = stage_extra1 \
     124                   AND stage = 'diff') \
     125                   JOIN skycell using (skycell_id, tess_id) \
     126                   JOIN warpRun on (warp1 = warp_id \
     127                   AND diffInputSkyfile.skycell_id = skycell_id) \
     128                   JOIN fakeRun using (fake_id) \
     129                   JOIN camRun using (cam_id) \
     130                   JOIN chipRun using (chip_id)  \
     131                   JOIN rawExp using (exp_id) \
     132                   WHERE  mergedvodbRun.mergedvodb = '" + dvoDb + "' \
     133                   AND minidvodbRun.state = 'merged' \
     134                   AND minidvodbProcessed.fault = 0 \
     135                   AND mergedvodbRun.state = 'full' \
     136                   AND mergedvodbProcessed.fault = 0 \
     137                   AND addRun.stage = '" + stage + "' \
     138                   AND addRun.state = 'full' \
     139                   AND decdeg BETWEEN " + str(minDec) + " AND " + str(maxDec) + " \
     140                   AND radeg BETWEEN " + str(minRA) + " AND " + str(maxRA) + " \
     141                   AND dateobs >= '" + tstart + "'\
     142                   AND dateobs <= '" + tend  + "'"
     143
    114144
    115145        elif batchType == "FW":
     
    123153                   JOIN mergedvodbProcessed USING (merge_id) \
    124154                   JOIN fullForceRun USING(ff_id) \
    125                    JOIN skycalRun using (skycal_id)
     155                   JOIN skycalRun using (skycal_id) \
    126156                   JOIN stackRun USING(stack_id) \
    127157                   JOIN stackSumSkyfile using (stack_id) \
     
    222252        return meta
    223253
     254
     255    '''
     256    Gets some stack-stage meta data for this sky_id # TODO this SQL could surely be improved
     257    '''
     258    def getDiffStageMeta(self, diffSkyfileID):
     259
     260        self.logger.debug("Querying GPC1 for stack meta data")
     261
     262        meta = []
     263        sql = "SELECT \
     264               filter,\
     265               diff_mode, \
     266               warp1, \
     267               stack2, \
     268               skycell_id, \
     269               diffRun.software_ver, \
     270               exp_time \
     271               FROM diffRun join diffInputSkyfile using (diff_id) \
     272               JOIN warpRun on (warp1=warp_id) \
     273               JOIN fakeRun using (fake_id) \
     274               JOIN camRun using (cam_id) \
     275               JOIN chipRun using (chip_id) \
     276               JOIN rawExp using (exp_id) \
     277               WHERE diff_skyfile_id = %d" % diffSkyfileID
     278               
     279        try:
     280            rs = self.executeQuery(sql)
     281            rs.first()
     282        except:
     283            self.logger.infoPair ("this sql is broken:",sql)
     284            self.logger.errorPair("Can't query for", "stack meta data")
     285           
     286        try:
     287            meta.append(rs.getString(1))
     288            meta.append(rs.getString(2))
     289            meta.append(rs.getString(3))
     290            meta.append(rs.getString(4))
     291            meta.append(rs.getString(5))
     292            meta.append(rs.getString(6))
     293            meta.append(rs.getString(7))
     294
     295        except:
     296            self.logger.errorPair("getDiffStageMeta()", "empty meta data")
     297     
     298        return meta
     299
     300    '''
     301    get diff stage cmf name
     302    '''
     303    def getDiffStageCmf(self, dvoDb, diffSkyfileID):
     304        print "got here, diffstagecmf"
     305        sql = "SELECT DISTINCT diffSkyfile.path_base \
     306               FROM mergedvodbRun join minidvodbRun using (minidvodb_id) \
     307               JOIN addRun using (minidvodb_name) \
     308               JOIN diffInputSkyfile on (diff_skyfile_id = stage_extra1 \
     309               AND diff_id = stage_id AND stage = 'diff') \
     310               JOIN diffSkyfile using (diff_id, skycell_id) \
     311               WHERE diff_skyfile_id = " + str(diffSkyfileID) + " \
     312               AND minidvodbRun.state = 'merged' \
     313               AND mergedvodbRun.state = 'full' \
     314               AND mergedvodbRun.mergedvodb = '" + dvoDb + "' \
     315               AND stage = 'diff'"
     316
     317        try:
     318            rs = self.executeQuery(sql)
     319            rs.first()
     320        except:
     321            self.logger.infoPair("failed sql", sql)
     322            self.logger.errorPair("can't query for diff cmf", "dfif_skyfile_id = %d" %diff_skyfile_id)
     323            return None
     324        print "query worked"
     325        try:
     326            pathBase = rs.getString(1)
     327        except:   
     328            self.logger.errorPair("no diff cms found for diff_skyfile_id = %d" %diff_skyfile_id)
     329            return None
     330        print pathBase
     331        files = []
     332        if pathBase.startswith("neb"):
     333            print "open"
     334            f=os.popen("neb-ls -p " + pathBase + ".cmf")
     335            for i in f.readlines():
     336                print "i",i
     337                files.append(i.rstrip())
     338                print "append"
     339        print i
     340        if len(files) < 1: return None
     341        fits = Fits(self.logger, self.config, files[0])
     342        return fits
     343
    224344    '''
    225345    Gets some camera-stage meta data for this cam_id
     
    394514    def getStackStageCmf(self, dvoDb, stackID):
    395515     
    396         '''
    397         sql = "SELECT DISTINCT staticskyResult.path_base \
    398                FROM staticskyRun  \
    399                JOIN staticskyInput USING(sky_id)  \
    400                JOIN staticskyResult USING(sky_id) \
    401                JOIN stackRun USING(stack_id)  \
    402                JOIN stackSumSkyfile USING(stack_id) \
    403                JOIN addRun ON sky_id = stage_id \
    404                JOIN minidvodbRun USING (minidvodb_name) \
    405                WHERE stack_id = " + str(stackID) + " \
    406                AND minidvodbRun.minidvodb_group = '" + dvoDb + "' \
    407                AND minidvodbRun.state = 'merged' \
    408                AND stage = 'staticsky'"
    409         '''
    410 
    411516        sql = "SELECT DISTINCT skycalResult.path_base \
    412517               FROM skycalRun  \
     
    458563        fits = Fits(self.logger, self.config, files[0])
    459564        return fits
    460 
    461         # XXX validate the file?
    462         # if fits.getPrimaryHeaderValue("STK_ID") == str(stackID):
    463 
    464             # now find and loop through all cmf files at this path_base
    465 
    466             ## XXX the code below was needed when we ingested from staticsky (N files per run)
    467             ## XXX ingesting from skycal solves this problem (1 file per run)
    468             ## files=os.popen("neb-ls " + pathBase + "%cmf")
    469             ## for i in files.readlines():
    470             ##     nebPath = i.rstrip()
    471             ##
    472             ##     # now attempt to run 'neb-ls -p' to actually read this cmf file
    473             ##     try:
    474             ##         self.logger.debug("Trying to neb-ls -p on '" + nebPath + "'")
    475             ##         paths=os.popen("neb-ls -p " + nebPath)
    476             ##         path = paths.readline().rstrip()
    477             ##         if len(path) < 1:
    478             ##            self.logger.debug("zero length path - skipping")
    479             ##            raise
    480             ##
    481             ##         print "starint stack stage cmf 3"
    482             ##
    483             ##         # if we get here, then the cmf is readable, now check the stack_id
    484             ##         fits = Fits(self.logger, self.config, path)
    485             ##         if fits.getPrimaryHeaderValue("STK_ID") == str(stackID):
    486             ##             # we have the right file!
    487             ##             self.logger.debug("SUCCESS!: %s == %s"% (fits.getPrimaryHeaderValue("STK_ID"), str(stackID)))
    488             ##             return fits
    489             ##         else:
    490             ##             # this is not the correct file
    491             ##             self.logger.debug("STACK ID: %s != %s"% (fits.getPrimaryHeaderValue("STK_ID"), str(stackID)))
    492             ##
    493             ##     # an exception here means that nebulous could not read this file, so we just skip it
    494             ##     except:
    495             ##         self.logger.debug("NEB FAILED SKIPPING")
    496             ##         pass
    497565
    498566    '''
  • trunk/ippToPsps/jython/initbatch.py

    r37246 r37748  
    1616from stackbatch import StackBatch
    1717from detectionbatch import DetectionBatch
     18#from diffbatch import DiffBatch
     19#from forcedwarpbatch import ForcedWarpBatch
     20#why no object stuffs
    1821
    1922'''
  • trunk/ippToPsps/jython/ipptopspsdb.py

    r37551 r37748  
    799799    def insertDiffMeta(self, batchID, filter, diffType):
    800800
    801         sql = "INSERT INTO stack ( \
     801        sql = "INSERT INTO diff ( \
    802802               batch_id \
    803803               ,filter \
  • trunk/ippToPsps/jython/loader.py

    r37355 r37748  
    2424from objectbatch import ObjectBatch
    2525
     26from diffbatch import DiffBatch
     27#from diffobjectbatch import DiffObjectBatch
     28
     29#
     30#
    2631'''
    2732Loader class
     
    191196        # loop round IDs of all items to be processed
    192197        self.ippToPspsDb.lockBatchTable()
    193         #self.logger.infoPair("heather:","lockbatchtable")
     198        self.logger.infoPair("heather:","lockbatchtable")
    194199        unattemptedCount = 0
    195200        for id in ids:
    196             #self.logger.infoPair("heather:","in ids")
     201            self.logger.infoPair("heather:","in ids")
    197202            #self.logger.infoPair("heather:id",str(id))
    198203            batchID = self.ippToPspsDb.createNewBatch(batchType, id)
     
    202207                unattemptedCount += 1
    203208                continue
    204             #self.logger.infoPair("heather:","passed logic")
     209            self.logger.infoPair("heather:","passed logic")
    205210
    206211            self.ippToPspsDb.unlockTables()
     
    244249   
    245250                elif batchType == "DF":
     251                    self.logger.infoPair("wegothere!","we are awesome")
    246252                    batch = DiffBatch(self.logger,
    247253                            self.config,
  • trunk/ippToPsps/jython/objectbatch.py

    r37592 r37748  
    9494        sql = "UPDATE ObjectThin join (select @r:=@r+1 rownum, objID from \
    9595        (select @r:=0) r, ObjectThin t) as foo using (objID) set \
    96         uniquePspsP2id = ((" +str(self.batchID) "*1000000000 ) + rownum)";
     96        uniquePspsOBid = ((" +str(self.batchID) +"*1000000000 ) + rownum)";
    9797        try: self.scratchDb.execute(sql)
    9898        except:
  • trunk/ippToPsps/jython/stackbatch.py

    r37592 r37748  
    955955        (select @r:=0) r, StackObjectThin t) as foo using (objID) set \
    956956        stackDetectRowID = ((" + str(self.batchID) + " << 32 ) + rownum), \
    957         uniquePspsSTid = ((" +str(self.batchID) "*1000000000 ) + rownum)";
     957        uniquePspsSTid = ((" +str(self.batchID)+ "*1000000000 ) + rownum)";
    958958        try: self.scratchDb.execute(sql)
    959959        except:
  • trunk/ippToPsps/pspsschema/SchemaNew19.0/PSPS_TABLES/MetaData_Tables/DiffMeta

    r37474 r37748  
    99photoCalID   dimensionless   INT 4 NA photometry code
    1010magSat       dimensionless   REAL 4 -999 saturation magnitude level
    11 analVer      dimensionless   SMALLINT 2 -999 analysis version index
     11analVer      alphanumeric   VARCHAR(100) 100 -999 analysis version index
    1212expTime      seconds         REAL 4 -999 exposure time of positive image
    1313ctype1       alphanumeric   VARCHAR(MAX) 8000 name of astrometric projection in RA
Note: See TracChangeset for help on using the changeset viewer.