IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Ignore:
Timestamp:
May 29, 2011, 11:26:31 AM (15 years ago)
Author:
eugene
Message:

merging changes from trunk

Location:
branches/eam_branches/ipp-20110505/ippToPsps/jython
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • branches/eam_branches/ipp-20110505/ippToPsps/jython/batch.py

    r31405 r31587  
    3232    "../config/2/tables.vot"
    3333    '''
    34     def __init__(self, logger, batchType, inputFitsPath="", survey="", useFullTables=False):
     34    def __init__(self,
     35                 logger,
     36                 gpc1Db,
     37                 ippToPspsDb,
     38                 scratchDb,
     39                 id,
     40                 batchType,
     41                 inputFitsPath="",
     42                 survey="",
     43                 useFullTables=False):
     44
     45        self.everythingOK = False
     46        self.readHeader = False
    3547
    3648        # set up logging
     
    4052
    4153        # set up class variables
     54        self.id = id
     55        self.gpc1Db = gpc1Db
     56        self.ippToPspsDb = ippToPspsDb
     57        self.scratchDb = scratchDb
    4258        self.batchType = batchType;
    4359        self.pspsVoTableFilePath = "../config/" + batchType + "/tables.vot"
     
    4662        self.useFullTables = useFullTables
    4763
     64        if self.alreadyProcessed(): return
     65
     66        # do we have an input file?
     67        if self.inputFitsPath != "":
     68
     69            if not self.readPrimaryHeader(): return
     70
    4871        # TODO
    4972        self.tablesToExport = []
     
    5174        # open config
    5275        doc = ElementTree(file="config.xml")
    53 
    54         # create Gpc1Db object
    55         self.gpc1Db = Gpc1Db(self.logger)
    56         self.ippToPspsDb = IppToPspsDb(logger)
    57         self.scratchDb = ScratchDb(logger, self.useFullTables)
    5876
    5977        if self.survey != "":
     
    88106        self.dateStr = now.strftime("%Y-%m-%d")
    89107
    90         if self.inputFitsPath != "":
    91             file = open(self.inputFitsPath)
    92             self.header = self.parseFitsHeader(file)
    93             self.logger.info("Read primary and found " + str(len(self.header)) + " header cards")
    94             # TODO close file?
    95 
    96108        # create DVO tables if accessing DVO directly
    97109        if not self.useFullTables: self.scratchDb.createDvoTables()
    98110
     111        self.everythingOK = True
     112
    99113    '''
    100114    Destructor
     
    103117
    104118        self.logger.debug("Batch destructor")
     119
     120
     121    '''
     122    Reads the primary header of the FITS file
     123    '''
     124    def readPrimaryHeader(self):
     125
     126        if self.readHeader: return True
     127
     128        # does it exist?
     129        if not os.path.isfile(self.inputFitsPath):
     130
     131            self.logger.error("Cannot read file at '" + self.inputFitsPath + "'")
     132            return False
     133
     134        file = open(self.inputFitsPath)
     135        self.header = self.parseFitsHeader(file)
     136        self.logger.info("Read primary header and found " + str(len(self.header)) + " header cards")
     137        # TODO close file?
     138
     139        self.readHeader = True
     140
     141        return True
    105142
    106143
     
    138175            file.seek(index + 2880, 0)
    139176           
    140         if found != True: self.logger.error("...could not find extension '" + name + "'")
    141         else: self.logger.info("...read header at '" + name + "' and found " + str(len(header)) + " header cards")
     177        if found != True:
     178            self.logger.error("...could not read header in extension '" + name + "'")
     179            return
     180        #else: self.logger.info("...read header at '" + name + "' and found " + str(len(header)) + " header cards")
    142181
    143182        return header
     
    262301
    263302        first = True
     303
     304        self.totalDetections = 0
    264305        for table in tables:
    265306
    266             sql = "SELECT MIN(objID), MAX(objID) FROM " + table
    267             rs = self.scratchDb.stmt.executeQuery(sql)
     307            sql = "SELECT MIN(objID), MAX(objID), COUNT(objID) FROM " + table
     308            rs = self.scratchDb.executeQuery(sql)
    268309            rs.first()
     310
     311            self.totalDetections = self.totalDetections + rs.getLong(3)
    269312
    270313            if first:
     
    276319
    277320            first = False
     321            rs.close()
    278322
    279323        self.ippToPspsDb.updateMinMaxObjID(self.batchID, self.minObjID, self.maxObjID)
     324        self.logger.info("Total detections = %ld min objID = %ld max objID = %ld" % (self.totalDetections, self.minObjID, self.maxObjID))
     325
    280326
    281327    '''
     
    313359         self.pspsTables = stilts.treads(self.pspsVoTableFilePath)
    314360         for table in self.pspsTables:
    315              self.logger.info("Creating PSPS table: " + table.name)
     361             self.logger.debug("Creating PSPS table: " + table.name)
    316362             table.write(self.scratchDb.url + '#' + table.name)
    317363             self.tablesToExport.append(table.name)
     
    337383    Accepts a regular expression filter so not all tables need to be imported
    338384    '''
    339     def importIppTables(self, filter):
     385    def importIppTables(self, filter=""):
    340386
    341387      self.logger.info("Attempting to import tables from input FITS file")
     
    347393          match = re.match(filter, table.name)
    348394          if not match: continue
    349           self.logger.info("   Reading IPP table " + table.name + " from FITS file")
     395          self.logger.info("Reading IPP table " + table.name + " from FITS file")
    350396          table = stilts.tpipe(table, cmd='explodeall')
    351397
    352398          # drop any previous tables before import
    353           self.scratchDb.dropTable(table.name)
     399          #self.scratchDb.dropTable(table.name)
    354400
    355401          # IPP FITS files are littered with infinities, so remove these
    356           self.logger.info("   Removing Infinity values from all columns")
     402          self.logger.debug("Removing Infinity values from all columns")
    357403          table = stilts.tpipe(table, cmd='replaceval -Infinity null *')
    358404          table = stilts.tpipe(table, cmd='replaceval Infinity null *')
     
    360406          try:
    361407              table.write(self.scratchDb.url + '#' + table.name)
     408              self.scratchDb.killLastConnectionID()
     409              count = count + 1
    362410          except:
    363               self.logger.exception("   Problem writing table '" + table.name + "' to the database")
    364           count = count + 1
     411              self.logger.exception("Problem writing table '" + table.name + "' to the database")
     412
    365413
    366414      self.logger.info("Done. Imported %d tables" % count)
    367 
    368415      self.indexIppTables()
    369416
     
    373420    def exportPspsTablesToFits(self, regex="(.*)"):
    374421
    375         self.logger.info("Replacing NULLs with -999 then exporting all PSPS tables to FITS")
     422        self.logger.info("Replacing NULLs with -999, changing tables names using regex: " + regex)
    376423        _tables = []
    377424
    378         self.logger.info("    Selecting database tables")
     425        self.logger.info("Selecting database tables")
    379426        for table in self.tablesToExport:
    380427
     
    383430
    384431           # get everything from table
    385            _table = stilts.tread(self.scratchDb.url + '#SELECT * FROM ' + table)
    386 
     432           try:
     433               _table = stilts.tread(self.scratchDb.url + '#SELECT * FROM ' + table)
     434               self.scratchDb.killLastConnectionID()
     435           except:
     436               self.logger.exception("Could not read from DB table: " + table)
     437               return False
     438               
    387439           # replace nulls and empty fields with weird PSPS -999 pseudo-null
    388440           _table = stilts.tpipe(_table, cmd='replaceval "" -999 *')
     
    395447           _tables.append(_table)
    396448
    397         self.logger.info("    Writing to FITS file '" + self.outputFitsPath + "'...")
    398         stilts.twrites(_tables, self.outputFitsPath, fmt='fits')
    399         self.logger.info("    ...done")
    400         self.ippToPspsDb.updateProcessed(self.batchID, 1)
     449        self.logger.info("Writing to FITS file '" + self.outputFitsPath + "'...")
     450        try:
     451            stilts.twrites(_tables, self.outputFitsPath, fmt='fits')
     452            self.ippToPspsDb.updateProcessed(self.batchID, 1)
     453        except:
     454            self.logger.exception("Could not write to FITS")
     455            return False
     456
     457        return True
    401458
    402459    '''
     
    447504    '''
    448505    def alreadyProcessed(self):
    449            self.logger.info("Not implemented")
    450 
    451 
    452 
     506        self.logger.info("Not implemented")
     507
     508
     509    '''
     510    Creates and publishes a batch
     511    '''
     512    def run(self):
     513
     514        if not self.everythingOK: return
     515
     516        self.createEmptyPspsTables()
     517        self.importIppTables()
     518        if self.populatePspsTables():
     519            if self.exportPspsTablesToFits():
     520                self.writeBatchManifest()
     521                self.createTarball()
     522                self.publishToDatastore()
     523                #self.reportNullsInAllPspsTables(False)
     524                #sys.exit()
     525        self.logger.info("Finished.")
     526
     527
  • branches/eam_branches/ipp-20110505/ippToPsps/jython/detectionbatch.py

    r31406 r31587  
    66from java.lang import *
    77from java.sql import *
     8
    89from batch import Batch
    910from gpc1db import Gpc1Db
     11from ipptopspsdb import IppToPspsDb
     12from scratchdb import ScratchDb
    1013
    1114import logging.config
     
    1922    Constructor
    2023    '''
    21     def __init__(self, logger, camID, inputFile, test=False, useFullTables=False):
     24    def __init__(self,
     25                 logger,
     26                 gpc1Db,
     27                 ippToPspsDb,
     28                 scratchDb,
     29                 camID,
     30                 inputFile,
     31                 test=False,
     32                 useFullTables=False):
     33
    2234       super(DetectionBatch, self).__init__(
    2335               logger,
     36               gpc1Db,
     37               ippToPspsDb,
     38               scratchDb,
     39               camID,
    2440               "detection",
    2541               inputFile,
    26                "MD04",
    27                useFullTables) # TODO
     42               "MD04", # TODO
    2843               #"3PI") # TODO
    29 
    30        self.logger.info("DetectionBatch constructor. Creating batch from: '" + inputFile + "'")
    31 
    32        meta = self.gpc1Db.getCameraStageMeta(camID)
    33      
    34        self.expID = meta[0];
    35        self.expName = meta[1];
    36        self.distGroup = meta[2];
    37 
    38        self.logger.info("Processing exposure with ID: %d, name: %s and distribution group: %s" % (self.expID, self.expName, self.distGroup))
     44               useFullTables)
     45
     46       if not self.everythingOK: return
     47
     48       # meta data to the log
     49       self.logger.info("New Detection Batch:")
     50       self.logger.info("Cam ID:             %d" % self.id)
     51       self.logger.info("file:               %s" % inputFile)
     52       self.logger.info("Exp ID:             %d" % self.expID)
     53       self.logger.info("Exp name:           %s" % self.expName)
     54       self.logger.info("Distribution group: %s" % self.distGroup)
    3955
    4056       # create an output filename, which is {expID}.FITS
     
    167183        ," + self.header['PCA2X0Y2'] + " \
    168184        )"
    169         self.scratchDb.stmt.execute(sql)
     185        self.scratchDb.execute(sql)
    170186
    171187        self.scratchDb.updateAllRows("FrameMeta", "surveyID", str(self.surveyID))
     
    184200        self.scratchDb.dropTable(tableName)
    185201        sql = "CREATE TABLE " + tableName + " LIKE ImageMeta"
    186         try: self.scratchDb.stmt.execute(sql)
     202        try: self.scratchDb.execute(sql)
    187203        except: pass
    188204
     
    310326               )"
    311327
    312         self.scratchDb.stmt.execute(sql)
     328        self.scratchDb.execute(sql)
    313329        self.scratchDb.updateFilterID(tableName, self.filter)
    314330        self.scratchDb.updateAllRows(tableName, "calibModNum", str(self.calibModNum))
    315331        self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.dataRelease))
    316         self.totalNumPhotoRef = self.totalNumPhotoRef + int(header['NASTRO'])
     332        if 'NASTRO' in header: self.totalNumPhotoRef = self.totalNumPhotoRef + int(header['NASTRO'])
    317333        self.scratchDb.replaceNullsInThisColumn(tableName, "polyOrder", "0")
    318334
     
    327343        self.scratchDb.dropTable(tableName)
    328344        sql = "CREATE TABLE " + tableName + " LIKE Detection"
    329         try: self.scratchDb.stmt.execute(sql)
     345        try: self.scratchDb.execute(sql)
    330346        except: pass
    331347
     
    375391               ,EXT_NSIGMA \
    376392               FROM " + ota + "_psf"
    377 
    378         self.scratchDb.stmt.execute(sql)
     393        self.scratchDb.execute(sql)
    379394
    380395        # set obsTime
    381396        sql = "UPDATE " + tableName + " SET obsTime = %f, assocDate = '%s', activeFlag = 0" % (self.obsTime, self.dateStr)
    382         self.scratchDb.stmt.execute(sql)
     397        self.scratchDb.execute(sql)
    383398        self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.dataRelease))
    384399        self.scratchDb.updateAllRows(tableName, "historyModNum", "0")
     
    387402        self.scratchDb.updateFilterID(tableName, self.filter)
    388403
    389         # now delete bad flux
     404        # now delete bad flux and bad chip positions
    390405        self.scratchDb.reportAndDeleteRowsWithNULLS(tableName, "instFlux")
    391406        self.scratchDb.reportAndDeleteRowsWithNULLS(tableName, "peakADU")
     
    401416        self.scratchDb.dropTable(tableName)
    402417        sql = "CREATE TABLE " + tableName + " LIKE SkinnyObject"
    403         try: self.scratchDb.stmt.execute(sql)
     418        try: self.scratchDb.execute(sql)
    404419        except: pass
    405420
     
    415430               ,surveyID \
    416431               FROM Detection_" + ota
    417         self.scratchDb.stmt.execute(sql)
     432        self.scratchDb.execute(sql)
    418433
    419434        self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.dataRelease))
     
    429444        self.scratchDb.dropTable(tableName)
    430445        sql = "CREATE TABLE " + tableName + " LIKE ObjectCalColor"
    431         try: self.scratchDb.stmt.execute(sql)
     446        try: self.scratchDb.execute(sql)
    432447        except: pass
    433448
     
    443458               ,filterID \
    444459               FROM Detection_" + ota
    445         self.scratchDb.stmt.execute(sql)
     460        self.scratchDb.execute(sql)
    446461
    447462        self.scratchDb.updateAllRows(tableName, "calibModNum", str(self.calibModNum))
     
    484499
    485500        imageID = self.scratchDb.getImageIDFromExternID(sourceID, externID)
    486         self.logger.info("Updating table '" + table + "' with DVO IDs using imageID = %d" % imageID)
     501        self.logger.debug("Updating table '" + table + "' with DVO IDs using imageID = %d" % imageID)
    487502        sql = "UPDATE IGNORE " + table + " AS a, " + self.scratchDb.dvoDetection + " AS b SET \
    488503               a.ippObjID = b.ippObjID, \
     
    494509               AND b.imageID = " + str(imageID)
    495510
    496         self.scratchDb.stmt.execute(sql)
     511        self.scratchDb.execute(sql)
    497512
    498513
     
    511526
    512527        # loop through all OTAs and populate ImageMeta extensions
     528        self.logger.info("Reading all fits headers and populating ImageMeta tables")
    513529        for x in range(self.startX, self.endX):
    514530            for y in range(self.startY, self.endY):
     
    524540                # load corresponding header into memory
    525541                header = self.findAndReadFITSHeader(ota + ".hdr", file)
     542                if not header:
     543                    self.logger.error("No header found for OTA " + ota)
     544                    continue
     545
    526546
    527547                # store sourceID/imageID combo in Db so DVO can look up later
     
    578598
    579599                # update ImageMeta with count of detections for this OTA and photoCodeID
    580                 sql = "UPDATE ImageMeta_" + ota + " SET nDetect = %d, photoCalID = %d" % (self.scratchDb.getRowCount("Detection_" + ota), self.scratchDb.getPhotoCalID(sourceIDs[ota], imageIDs[ota]))
    581                 self.scratchDb.stmt.execute(sql)
     600                sql = "UPDATE ImageMeta_" + ota + " \
     601                       SET nDetect = %d, photoCalID = %d" % (self.scratchDb.getRowCount("Detection_" + ota), self.scratchDb.getPhotoCalID(sourceIDs[ota], imageIDs[ota]))
     602                self.scratchDb.execute(sql)
    582603
    583604                self.populateSkinnyObjectTable(ota)
     
    603624        # update FrameMeta with count OTAs in this file and total number of photometric reference sources
    604625        sql = "UPDATE FrameMeta SET nOTA = %d, numPhotoRef = %d" % (otaCount, self.totalNumPhotoRef)
    605         self.scratchDb.stmt.execute(sql)
     626        self.scratchDb.execute(sql)
    606627       
    607628        return True
     
    613634
    614635        sql = "UPDATE " + tableName + " SET imageID = %d%d%d" % (self.expID, x, y)
    615         self.scratchDb.stmt.execute(sql)
     636        self.scratchDb.execute(sql)
    616637
    617638    '''
     
    619640    '''
    620641    def alreadyProcessed(self):
     642
     643        meta = self.gpc1Db.getCameraStageMeta(self.id)
     644        self.expID = meta[0];
     645        self.expName = meta[1];
     646        self.distGroup = meta[2];
    621647
    622648        return self.ippToPspsDb.alreadyProcessed("detection", "exp_id", self.expID)
     
    634660
    635661
     662    '''
     663    Overriding this method. Filter to only import *.psf extensions
     664    '''
     665    def importIppTables(self, filter=""):
     666       return super(DetectionBatch, self).importIppTables(".*.psf")
     667
     668
     669    '''
     670    Overriding this method. Use regex to trim off, eg _XY33 extension
     671    '''
     672    def exportPspsTablesToFits(self, regex="(.*)"):
     673       return super(DetectionBatch, self).exportPspsTablesToFits("([a-zA-Z]+)")
     674
     675
     676# TODO put in config
     677useFullTables=True
     678testMode=False
     679
    636680logging.config.fileConfig("logging.conf")
    637681logger = logging.getLogger("detectionbatch")
     682logger.setLevel(logging.INFO)
    638683logger.info("Starting")
    639684
    640685gpc1Db = Gpc1Db(logger)
     686ippToPspsDb = IppToPspsDb(logger)
     687scratchDb = ScratchDb(logger, useFullTables)
     688
    641689camIDs = gpc1Db.getIDsInThisDVODbForThisStage("MD04.V2", "cam")
    642690logger.info("Found %d exposures" % len(camIDs))
     
    645693for camID in camIDs:
    646694
    647     logger.info("-------------------------------------------------- cam ID: %d" % camID)
     695    #if camID < 43764: continue # TODO
    648696
    649697    file = gpc1Db.getCameraStageSmf(camID)
    650     if not os.path.isfile(file):
    651         logger.error("Cannot read file at '" + file)
    652         continue
    653 
    654     detectionBatch = DetectionBatch(logger, camID, file, False, True)
    655 
    656     if not detectionBatch.alreadyProcessed():
    657 
    658         detectionBatch.createEmptyPspsTables()
    659         detectionBatch.importIppTables(".*.psf")
    660         if detectionBatch.populatePspsTables():
    661             detectionBatch.exportPspsTablesToFits("([a-zA-Z]+)")
    662             detectionBatch.writeBatchManifest()
    663             #detectionBatch.reportNullsInAllPspsTables(False)
    664             #detectionBatch.createTarball()
    665             #detectionBatch.publishToDatastore()
    666    
    667             i = i+1
    668            # if i > 0: sys.exit()
    669 
     698
     699    detectionBatch = DetectionBatch(logger,
     700                                    gpc1Db,
     701                                    ippToPspsDb,
     702                                    scratchDb,
     703                                    camID,
     704                                    file,
     705                                    testMode,
     706                                    useFullTables)
     707    detectionBatch.run()
     708
  • branches/eam_branches/ipp-20110505/ippToPsps/jython/gpc1db.py

    r31400 r31587  
    2929        self.logger.debug("Gpc1Db destructor")
    3030
     31
     32    '''
     33    TODO
     34    '''
     35    def getIDsInThisDVODbForThisStageFudge(self):
     36
     37        sql = "SELECT staticskyRun.sky_id \
     38               FROM staticskyInput, staticskyRun, stackRun, staticskyResult \
     39               WHERE staticskyRun.sky_id = staticskyInput.sky_id \
     40               AND staticskyInput.stack_id = stackRun.stack_id \
     41               AND staticskyInput.sky_id = staticskyResult.sky_id \
     42               AND staticskyRun.label like 'MD04.staticsky' \
     43               AND stackRun.filter like 'i%'"
     44
     45        try:
     46            rs = self.executeQuery(sql)
     47        except:
     48            self.logger.exception("Can't query for ids in DVO")
     49
     50        ids = []
     51        while (rs.next()):
     52            ids.append(rs.getInt(1))
     53
     54        rs.close()
     55
     56        self.logger.info("Found %d items in DVO database '" % (len(ids)))
     57
     58        return ids
     59
    3160    '''
    3261    Gets a list of ids in this DVO database for this stage, could be cam or staticsky (so far)
     
    4069
    4170        try:
    42             rs = self.stmt.executeQuery(sql)
     71            rs = self.executeQuery(sql)
    4372        except:
    4473            self.logger.exception("Can't query for ids in DVO")
     
    5079        rs.close()
    5180
    52         self.logger.debug("Found %d items in DVO database '%s' for stage='%s'" % (len(ids), dvoDb, stage))
     81        self.logger.info("Found %d items in DVO database '%s' for stage='%s'" % (len(ids), dvoDb, stage))
    5382
    5483        return ids
     
    73102
    74103        try:
    75             rs = self.stmt.executeQuery(sql)
     104            rs = self.executeQuery(sql)
    76105        except:
    77106            self.logger.exception("Can't query for imageIDs")
     
    105134
    106135        try:
    107             rs = self.stmt.executeQuery(sql)
     136            rs = self.executeQuery(sql)
    108137            rs.first()
    109138            meta.append(rs.getInt(1))
     
    113142
    114143        return meta
     144
    115145    '''
    116146    Gets some camera-stage meta data for this cam_id
     
    127157
    128158        try:
    129             rs = self.stmt.executeQuery(sql)
     159            rs = self.executeQuery(sql)
    130160            rs.first()
    131161            meta.append(rs.getInt(1))
     
    150180
    151181        try:
    152             rs = self.stmt.executeQuery(sql)
     182            rs = self.executeQuery(sql)
    153183            rs.first()
    154184        except:
     
    171201            files = glob.glob(path + "/*.cmf")
    172202
     203        if len(files) < 1: return "NULL"
     204
    173205        return files[0] # TODO just returning first file - check
    174206
     
    186218
    187219        try:
    188             rs = self.stmt.executeQuery(sql)
     220            rs = self.executeQuery(sql)
    189221            rs.first()
    190222        except:
     
    200232
    201233            f=os.popen("neb-ls -p "+path+"%cmf")
    202             print "neb-ls -p "+path+"%cmf"
    203234            for i in f.readlines():
    204235                files.append(i.rstrip())
    205                 print i.rstrip()
    206236
    207237        # or not a neb path
     
    211241        return files
    212242
     243
     244    '''
     245    TODO hack to get exposure time for a stack
     246    '''
     247    def getStackExpTime(self, stackID):
     248
     249        self.logger.debug("Querying GPC1 for stack exposure time")
     250
     251        sql = "SELECT SUM(exp_time) * (COUNT(warp_id) - reject_images) / COUNT(warp_id) as EXPTIME \
     252               FROM staticskyRun JOIN staticskyInput using(sky_id) \
     253               JOIN stackRun using(stack_id) \
     254               JOIN stackSumSkyfile using(stack_id) \
     255               JOIN stackInputSkyfile using(stack_id) \
     256               JOIN warpRun using(warp_id) \
     257               JOIN fakeRun using(fake_id) \
     258               JOIN camRun using(cam_id) \
     259               JOIN chipRun using(chip_id) \
     260               JOIN rawExp using(exp_id) \
     261               WHERE stack_id = %d" % stackID
     262
     263        try:
     264            rs = self.executeQuery(sql)
     265            rs.first()
     266            return rs.getInt(1)
     267        except:
     268            self.logger.exception("Can't query for exposure time")
     269
     270        return 0.0
     271
     272
  • branches/eam_branches/ipp-20110505/ippToPsps/jython/ipptopspsdb.py

    r31355 r31587  
    3737               )"
    3838
    39         self.stmt.execute(sql)
     39        self.execute(sql)
    4040
    4141        sql = "SELECT MAX(batch_id) FROM batch"
     
    4444
    4545        try:
    46             rs = self.stmt.executeQuery(sql)
     46            rs = self.executeQuery(sql)
    4747            rs.first()
    4848            batchID = rs.getInt(1)
     
    6464               WHERE batch_id = " + str(batchID)
    6565
    66         self.stmt.execute(sql)
     66        self.execute(sql)
    6767
    6868    '''
     
    7575               WHERE batch_id = " + str(batchID)
    7676
    77         self.stmt.execute(sql)
     77        self.execute(sql)
    7878
    7979    '''
     
    8686               WHERE batch_id = " + str(batchID)
    8787
    88         self.stmt.execute(sql)
     88        self.execute(sql)
    8989
    9090    '''
     
    101101
    102102        try:
    103             rs = self.stmt.executeQuery(sql)
     103            rs = self.executeQuery(sql)
    104104            rs.first()
    105105            if rs.getInt(1) > 0:
     
    128128               )"
    129129
    130         self.stmt.execute(sql)
     130        self.execute(sql)
    131131
    132132    '''
     
    149149               )"
    150150
    151         self.stmt.execute(sql)
     151        self.execute(sql)
    152152
    153153
  • branches/eam_branches/ipp-20110505/ippToPsps/jython/mysql.py

    r31401 r31587  
    3737        self.url = "jdbc:mysql://"+self.dbHost+"/"+self.dbName+"?user="+self.dbUser+"&password="+self.dbPass
    3838        self.con = DriverManager.getConnection(self.url)
    39         self.stmt = self.con.createStatement()
     39        self.connectionID = self.getLastConnectionID()
     40        self.logger.info("MySQL connection to %s with ID %d" % (dbType, self.connectionID))
     41
     42        #self.stmt = self.con.createStatement()
     43
     44
     45    '''
     46    Disconnect from database
     47    '''
     48    def disconnect(self):
     49        self.con.close()
    4050
    4151    '''
     
    4555
    4656        self.logger.debug("MySql destructor")
    47         self.stmt.close()
    48         self.con.close()
     57        self.disconnect()
     58
     59    '''
     60    Kills the last connection ID, so long as it's not THIS connection ID
     61    '''
     62    def killLastConnectionID(self):
     63   
     64        connectionID = self.getLastConnectionID()
     65        if connectionID == self.connectionID:
     66            self.logger.error("NOT going to kill THIS connection ID")
     67            return
     68
     69        sql = "KILL %d" % connectionID
     70        self.execute(sql)
     71
     72    '''
     73    Gets the last connection ID
     74    '''
     75    def getLastConnectionID(self):
     76
     77        sql = "SELECT ID \
     78               FROM INFORMATION_SCHEMA.PROCESSLIST \
     79               WHERE DB='" + self.dbName + "' \
     80               ORDER BY ID"
     81        rs = self.executeQuery(sql)
     82        rs.last()
     83        return rs.getInt(1)
    4984
    5085    '''
     
    5489
    5590        sql = "UPDATE " + table + " SET " + column + " = " + value
    56         self.stmt.execute(sql)
     91        self.execute(sql)
    5792
    5893    '''
     
    6297
    6398        sql = "DROP TABLE " + table
    64         try: self.stmt.execute(sql)
     99        try: self.execute(sql)
    65100        except: return
    66101
     
    74109        sql = "ALTER TABLE " + table + " ADD UNIQUE (" + column + ")"
    75110        try:
    76             self.stmt.execute(sql)
     111            self.execute(sql)
    77112        except: pass
    78113            #self.logger.warn("Index already in place on '" + column + "' for table '" + table + "'")
     
    82117    def createIndex(self, table, column):
    83118
    84         self.logger.debug("Creating index on column '"+column+"' for table '"+table+"'")
     119        #self.logger.debug("Creating index on column '"+column+"' for table '"+table+"'")
    85120
    86121        sql = "CREATE INDEX "+table+"_"+column+"_index ON "+table+" ("+column+")"
    87122        try:
    88             self.stmt.execute(sql)
     123            self.execute(sql)
    89124        except: pass
    90125            #self.logger.warn("Index already in place on '" + column + "' for table '" + table + "'")
     126    '''
     127    TODO
     128    '''
     129    def execute(self, sql):
     130
     131        stmt = self.con.createStatement()
     132        stmt.execute(sql)
     133        stmt.close()
     134
     135    '''
     136    TODO
     137    '''
     138    def executeQuery(self, sql):
     139
     140        stmt = self.con.createStatement()
     141        rs = stmt.executeQuery(sql)
     142        #stmt.close()
     143        return rs
    91144
    92145    '''
     
    96149
    97150       sql = "SHOW COLUMNS FROM " + tableName
    98        rs = self.stmt.executeQuery(sql)
     151       rs = self.executeQuery(sql)
    99152       columns = []
    100153       while (rs.next()): columns.append(rs.getString(1))
     
    109162
    110163      sql = "UPDATE " + tableName + " SET " + column + " = " + sub + " WHERE " + column + " IS NULL"
    111       self.stmt.execute(sql)
     164      self.execute(sql)
    112165
    113166    '''
     
    123176         
    124177          sql = "UPDATE " + tableName + " SET " + column + " = " + sub + " WHERE " + column + " IS NULL"
    125           self.stmt.execute(sql)
     178          self.execute(sql)
    126179
    127180    '''
     
    131184
    132185        sql = "SELECT COUNT(*) FROM " + tableName + " WHERE " + columnName + " = " + value
    133         rs = self.stmt.executeQuery(sql)
     186        rs = self.executeQuery(sql)
    134187        rs.first()
    135         nBadFlux = rs.getInt(1)
    136         self.logger.info("%d NULL %s values in table %s. Deleting." % (nBadFlux, columnName, tableName))
     188        nBad = rs.getInt(1)
     189        self.logger.info("%5d NULL %s values in table %s. Deleting." % (nBad, columnName, tableName))
    137190
    138191        sql="DELETE from " + tableName + " WHERE " + columnName + " = " + value
    139         self.stmt.execute(sql)
     192        self.execute(sql)
    140193
    141194    '''
     
    145198
    146199        sql = "SELECT COUNT(*) FROM " + tableName + " WHERE " + columnName + " IS NULL"
    147         rs = self.stmt.executeQuery(sql)
     200        rs = self.executeQuery(sql)
    148201        rs.first()
    149         nBadFlux = rs.getInt(1)
    150         self.logger.info("%d NULL %s values in table %s. Deleting." % (nBadFlux, columnName, tableName))
     202        nBad = rs.getInt(1)
     203        self.logger.info("%5d NULL %s values in table %s. Deleting." % (nBad, columnName, tableName))
    151204
    152205        sql="DELETE from " + tableName + " WHERE " + columnName + " IS NULL"
    153         self.stmt.execute(sql)
     206        self.execute(sql)
    154207
    155208    '''
     
    160213       # first, count rows
    161214       sql = "SELECT COUNT(*) FROM " + tableName
    162        rs = self.stmt.executeQuery(sql)
     215       rs = self.executeQuery(sql)
    163216       rs.first()
    164217       numRows = rs.getInt(1)
     
    175228         
    176229          sql = "SELECT COUNT(*) FROM " + tableName + " WHERE " + column + " IS NULL"
    177           rs = self.stmt.executeQuery(sql)
     230          rs = self.executeQuery(sql)
    178231          rs.first()
    179232          if rs.getInt(1) == numRows:
     
    191244        sql = "SELECT COUNT(*) FROM " + table
    192245        try:
    193             rs = self.stmt.executeQuery(sql) 
     246            rs = self.executeQuery(sql) 
    194247            rs.first()
    195248            return rs.getInt(1)
  • branches/eam_branches/ipp-20110505/ippToPsps/jython/scratchdb.py

    r31399 r31587  
    4545        sql = "SELECT surveyID FROM Survey WHERE name = '" + name + "'"
    4646        try:
    47             rs = self.stmt.executeQuery(sql)
     47            rs = self.executeQuery(sql)
    4848            rs.first()
    4949            return rs.getInt(1)
     
    6161        sql = "SELECT flags FROM " + self.dvoMeta + " WHERE sourceID = %s AND externID = %s" % (sourceID, externID)
    6262        try:
    63             rs = self.stmt.executeQuery(sql) 
     63            rs = self.executeQuery(sql) 
    6464            rs.first()
    6565            flags = rs.getInt(1)
     
    7878        sql = "SELECT imageID FROM " + self.dvoMeta + " WHERE sourceID = %s AND externID = %s" % (sourceID, externID)
    7979        try:
    80             rs = self.stmt.executeQuery(sql) 
     80            rs = self.executeQuery(sql) 
    8181            rs.first()
    8282            imageID = rs.getInt(1)
     
    9595        sql = "SELECT photcode FROM " + self.dvoMeta + " WHERE sourceID = %s AND externID = %s" % (sourceID, externID)
    9696        try:
    97             rs = self.stmt.executeQuery(sql) 
     97            rs = self.executeQuery(sql) 
    9898            rs.first()
    9999            photcode = rs.getInt(1)
     
    109109
    110110        sql = "UPDATE "+table+" AS a, Filter AS b SET a.filterID=b.filterID WHERE b.filterType = '" + filter + "'"
    111         self.stmt.execute(sql)
     111        self.execute(sql)
    112112
    113113    '''
     
    123123               " + str(imageID) + "    \
    124124               )"
    125         self.stmt.execute(sql)
     125        self.execute(sql)
    126126
    127127    '''
     
    131131
    132132        sql = "INSERT INTO dvoDone (name) VALUES ('" + name + "')"
    133         self.stmt.execute(sql)
     133        self.execute(sql)
    134134       
    135135    '''
     
    141141
    142142        try:
    143             rs = self.stmt.executeQuery(sql)
     143            rs = self.executeQuery(sql)
    144144            rs.first()
    145145            if rs.getInt(1) > 0:
     
    160160
    161161        sql = "DROP TABLE dvoMeta"
    162         try: self.stmt.execute(sql)
     162        try: self.execute(sql)
    163163        except: pass
    164164       
    165165        sql = "DROP TABLE dvoDetection"
    166         try: self.stmt.execute(sql)
     166        try: self.execute(sql)
    167167        except: pass
    168168
     
    175175               )"
    176176
    177         try: self.stmt.execute(sql)
     177        try: self.execute(sql)
    178178        except:
    179179            self.logger.error("Unable to create DVO meta-data database table")
     
    193193               #INDEX (ippDetectID) \
    194194
    195         try: self.stmt.execute(sql)
     195        try: self.execute(sql)
    196196        except:
    197197            self.logger.error("Unable to create DVO detection database table")
  • branches/eam_branches/ipp-20110505/ippToPsps/jython/stackbatch.py

    r31402 r31587  
    88from java.sql import *
    99
     10from batch import Batch
    1011from gpc1db import Gpc1Db
    11 from batch import Batch
     12from ipptopspsdb import IppToPspsDb
     13from scratchdb import ScratchDb
     14
    1215import logging.config
    1316
     
    2023    Constructor
    2124    '''
    22     def __init__(self, logger, skyID, inputFile, stackType, useFullTables=False):
     25    def __init__(self,
     26                 logger,
     27                 gpc1Db,
     28                 ippToPspsDb,
     29                 scratchDb,
     30                 skyID,
     31                 inputFile,
     32                 stackType,
     33                 useFullTables=False):
     34
    2335       super(StackBatch, self).__init__(
    2436               logger,
     37               gpc1Db,
     38               ippToPspsDb,
     39               scratchDb,
     40               skyID,
    2541               "stack",
    2642               inputFile,
     
    2844               useFullTables) # TODO
    2945
    30        self.logger.info("StackBatch constructor. Creating batch from: '" + inputFile + "'")
    31 
    32        self.skyID = skyID
    33 
    34        # get filterID using init table
    35        self.filter = self.header['FPA.FILTER']
    36        self.filter = self.filter[0:1]
    37 
    38        self.stackType = stackType
    39        meta = self.gpc1Db.getStackStageMeta(self.skyID, self.header['FPA.FILTER'])
    40        if len(meta) < 1: return
    41        self.stackID = meta[0];
    42        self.skycell = meta[1];
    43 
    44        # determine skycell from header value
    45        #self.skycell = "skycell.34" #= self.header['SKYCELL']
    46        self.skycell = self.skycell[8:]
    47 
    48        self.logger.info("Processing stack with ID: %d, type: %s and skycell: %s filter: %s" % (self.stackID, self.stackType, self.skycell, self.filter))
    49 
     46       if not self.everythingOK: return
     47
     48       self.expTime = gpc1Db.getStackExpTime(self.stackID)
     49
     50       self.logger.info("got exp time of %d" % self.expTime)
     51
     52       # meta data to the log
     53       self.logger.info("New Stack Batch:")
     54       self.logger.info("Sky ID:     %d" % self.id)
     55       self.logger.info("File:       %s" % inputFile)
     56       self.logger.info("Stack ID:   %d" % self.stackID)
     57       self.logger.info("Stack type: %s" % self.stackType)
     58       self.logger.info("Skycell:    %s" % self.skycell)
     59       self.logger.info("Filter:     %s" % self.filter)
    5060
    5161       # delete PSPS tables
     
    5868       self.scratchDb.dropTable("ObjectCalColor")
    5969
    60        # delete IPP tables
    61        #self.scratchDb.dropTable("SkyChip_psf")
    62        #self.scratchDb.dropTable("SkyChip_xsrc")
    63        #self.scratchDb.dropTable("SkyChip_xfit")
    64        #self.scratchDb.dropTable("SkyChip_xrad")
    65 
    66        self.logger.info("Stack type: " + self.safeDictionaryAccess(self.header, self.stackType))
    67        # obs time makes no sense except for nightly stacks
    68        #if self.header['STK_TYPE'] != "NIGHTLY_STACK": self.header['MJD-OBS'] = "-999"
    69 
    7070       # create an output filename, which is {filterID}{skycellID}.FITS
    71        self.outputFitsFile = "%s%07d.FITS" % (self.filter, int(self.skycell))
     71       self.outputFitsFile = "%08d.FITS" % self.stackID
    7272       self.outputFitsPath = "%s/%s" % (self.localOutPath, self.outputFitsFile)
    7373
     
    7777
    7878       # insert what we know about this stack batch into the stack table
    79        self.ippToPspsDb.insertStackMeta(self.batchID, self.skyID, self.stackID, self.filter, self.stackType)
     79       self.ippToPspsDb.insertStackMeta(self.batchID, self.id, self.stackID, self.filter, self.stackType)
    8080
    8181       # insert sourceID/imageID combo so DVO can look it up
     
    8989
    9090        sql = "UPDATE " + table + "  SET stackMetaID=" + str(self.stackID)
    91         self.scratchDb.stmt.execute(sql)
     91        self.scratchDb.execute(sql)
    9292
    9393    '''
     
    9797
    9898        sql = "UPDATE "+table+" AS a, StackType AS b SET a.stackTypeID=b.stackTypeID WHERE b.name = '" + self.stackType + "'"
    99         self.scratchDb.stmt.execute(sql)
     99        self.scratchDb.execute(sql)
    100100
    101101
     
    148148        WHERE a.ippDetectID=b.IPP_IDET AND b.PSF_FWHM "+psfCondition
    149149
    150         self.scratchDb.stmt.execute(sql)
     150        self.scratchDb.execute(sql)
    151151
    152152    '''
     
    196196        WHERE a.ippDetectID=b.IPP_IDET AND b.MODEL_TYPE = '"+ippModelType+"'"
    197197
    198         self.scratchDb.stmt.execute(sql)
     198        self.scratchDb.execute(sql)
    199199
    200200        # sersic fit has an extra parameter
     
    213213            WHERE a.ippDetectID=b.IPP_IDET AND b.MODEL_TYPE = '"+ippModelType+"'"
    214214
    215             self.scratchDb.stmt.execute(sql)
     215            self.scratchDb.execute(sql)
    216216
    217217
     
    220220    '''
    221221    def populateStackMeta(self):
     222
    222223        self.logger.info("Procesing StackMeta table")
    223224
     
    246247        ," + str(self.scratchDb.getPhotoCalID(self.header['SOURCEID'], self.header['IMAGEID'])) + " \
    247248        ," + self.header['FPA.ZP'] + " \
    248         ," + self.header['EXPTIME'] + " \
     249        ," + str(self.expTime) + " \
    249250        ,'" + self.safeDictionaryAccess(self.header, 'PSFMODEL') + "' \
    250251        ,'" + self.header['CTYPE1'] + "' \
     
    261262        ," + self.header['PC002002'] + " \
    262263        )"
    263         self.scratchDb.stmt.execute(sql)
     264        self.scratchDb.execute(sql)
    264265
    265266        self.scratchDb.updateAllRows("StackMeta", "surveyID", str(self.surveyID))
     
    272273    '''
    273274    def populateStackDetection(self):
     275
    274276        self.logger.info("Procesing StackDetection table")
    275277
     
    321323               ,X_PSF_SIG \
    322324               ,Y_PSF_SIG \
    323                ,POW(10.0, (-0.4*PSF_INST_MAG)) / "+self.header['EXPTIME']+" \
    324                ,ABS((PSF_INST_MAG_SIG*(POW(10.0, (-0.4*PSF_INST_MAG)) / "+self.header['EXPTIME']+")) / 1.085736) \
    325                ,POW(10.0, (-0.4*PEAK_FLUX_AS_MAG)) / "+self.header['EXPTIME']+" \
     325               ,POW(10.0, (-0.4*PSF_INST_MAG)) / "+str(self.expTime)+" \
     326               ,ABS((PSF_INST_MAG_SIG*(POW(10.0, (-0.4*PSF_INST_MAG)) / "+str(self.expTime)+")) / 1.085736) \
     327               ,POW(10.0, (-0.4*PEAK_FLUX_AS_MAG)) / "+str(self.expTime)+" \
    326328               ,SKY \
    327329               ,SKY_SIGMA \
     
    352354               FROM SkyChip_psf"
    353355
    354         self.scratchDb.stmt.execute(sql)
     356        self.scratchDb.execute(sql)
    355357
    356358        self.scratchDb.updateAllRows("StackDetection", "surveyID", str(self.surveyID))
     
    362364        self.updateStackTypeID("StackDetection")
    363365        self.updateDvoIDs("StackDetection")
    364 
    365         # now delete bad flux
     366        sql = "ALTER TABLE StackDetection ADD PRIMARY KEY (objID, stackDetectID)"
     367        self.scratchDb.execute(sql)
     368
     369        if self.stackType == "DEEP_STACK":
     370
     371            #if deep stack and instFlux = null and err not null
     372            sql = "UPDATE StackDetection AS a, SkyChip_psf AS b \
     373                   SET instFlux = 2*b.PSF_INST_FLUX_SIG \
     374                   WHERE instFlux IS NULL \
     375                   AND b.PSF_INST_FLUX_SIG IS NOT NULL"
     376            self.scratchDb.execute(sql)
     377            #    instFlux = 2*PSF_INST_FLUX_SIG
     378           
    366379        self.scratchDb.reportAndDeleteRowsWithNULLS("StackDetection", "instFlux")
    367380        self.scratchDb.reportAndDeleteRowsWithNULLS("StackDetection", "objID")
     
    372385    '''
    373386    def populateStackApFlx(self):
     387
    374388        self.logger.info("Procesing StackApFlx table")
    375389 
     
    381395
    382396        try:
    383             self.scratchDb.stmt.execute(sql)
     397            self.scratchDb.execute(sql)
    384398        except: return
    385399
    386400        # TODO temporarily loading 1st convolved fluxes into unconvolved fields
    387         self.logger.info("    Adding un-convolved fluxes")
     401        self.logger.info("Adding un-convolved fluxes")
    388402        self.updateApFlxs("", "< 7.0")
    389         self.logger.info("    Adding 1st convolved fluxes")
     403        self.logger.info("Adding 1st convolved fluxes")
    390404        self.updateApFlxs("c1", "< 7.0")
    391         self.logger.info("    Adding 2nd convolved fluxes")
     405        self.logger.info("Adding 2nd convolved fluxes")
    392406        self.updateApFlxs("c2", "> 7.0")
    393407
    394         self.logger.info("    Adding petrosians for extended sources")
     408        self.logger.info("Adding petrosians for extended sources")
    395409        sql = "UPDATE StackApFlx AS a, SkyChip_xsrc AS b SET \
    396410        petRadius=b.PETRO_RADIUS \
     
    403417        ,petR90Err=b.PETRO_RADIUS_90_ERR \
    404418        WHERE a.ippDetectID=b.IPP_IDET"
    405         self.scratchDb.stmt.execute(sql)
     419        self.scratchDb.execute(sql)
    406420
    407421        self.scratchDb.updateAllRows("StackApFlx", "surveyID", str(self.surveyID))
     
    413427        self.updateStackTypeID("StackApFlx")
    414428        self.updateDvoIDs("StackApFlx")
     429        self.scratchDb.reportAndDeleteRowsWithNULLS("StackApFlx", "objID")
     430        self.deleteDetectionsNotInStackDetection("StackApFlx")
     431
    415432
    416433    '''
     
    418435    '''
    419436    def populateStackModelFit(self):
     437
    420438        self.logger.info("Procesing StackModelFit table")
    421439
     
    423441        sql = "INSERT INTO StackModelFit (ippDetectID) SELECT DISTINCT IPP_IDET from SkyChip_xfit"
    424442        try:
    425             self.scratchDb.stmt.execute(sql)
     443            self.scratchDb.execute(sql)
    426444        except:
    427445            return
    428446
    429 
    430447        # populate model parameters
    431         self.logger.info("    Adding deVaucouleurs fit")
     448        self.logger.info("Adding deVaucouleurs fit")
    432449        self.updateModelFit("deV", "PS_MODEL_DEV")
    433         self.logger.info("    Adding exponential fit")
     450        self.logger.info("Adding exponential fit")
    434451        self.updateModelFit("exp", "PS_MODEL_EXP")
    435         self.logger.info("    Adding sersic fit")
     452        self.logger.info("Adding sersic fit")
    436453        self.updateModelFit("ser", "PS_MODEL_SERSIC")
    437454
     
    444461        self.updateStackTypeID("StackModelFit")
    445462        self.updateDvoIDs("StackModelFit")
     463        self.scratchDb.reportAndDeleteRowsWithNULLS("StackModelFit", "objID")
     464        self.deleteDetectionsNotInStackDetection("StackModelFit")
     465
     466    '''
     467    Reports and deletes detections in this table that are not in StackDetection
     468    '''
     469    def deleteDetectionsNotInStackDetection(self, table):
     470
     471        sql = "SELECT COUNT(*) FROM " + table + " WHERE ippDetectID NOT IN (SELECT ippDetectID FROM StackDetection)"
     472        rs = self.scratchDb.executeQuery(sql)
     473        rs.first()
     474        nMissing = rs.getInt(1)
     475        self.logger.info("%5d detections in %s table that are not in StackDetection. Deleting" % (nMissing, table))
     476 
     477        if nMissing < 1: return
     478       
     479        sql = "DELETE FROM " + table + " WHERE ippDetectID NOT IN (SELECT ippDetectID FROM StackDetection)"
     480        self.scratchDb.execute(sql)
     481       
    446482
    447483    '''
     
    449485    '''
    450486    def populateStackToImage(self):
     487
    451488        self.logger.info("Procesing StackToImage table")
    452489
     
    457494                   VALUES (\
    458495                   " + str(self.stackID) + ", " + imageID + ")"
    459             self.scratchDb.stmt.execute(sql)
     496            self.scratchDb.execute(sql)
    460497
    461498        # now update StackMeta with correct number of inputs
    462499        sql = "UPDATE StackMeta SET nP2Images = (SELECT COUNT(*) FROM StackToImage)"
    463         self.scratchDb.stmt.execute(sql)
     500        self.scratchDb.execute(sql)
    464501
    465502    '''
     
    467504    '''
    468505    def populateSkinnyObject(self):
     506
    469507        self.logger.info("Procesing SkinnyObject table")
    470508
     
    474512               ) \
    475513               SELECT \
    476                objID \
     514               DISTINCT objID \
    477515               ,ippObjID \
    478516               FROM StackDetection"
    479         self.scratchDb.stmt.execute(sql)
     517        self.scratchDb.execute(sql)
    480518
    481519        self.scratchDb.updateAllRows("SkinnyObject", "surveyID", str(self.surveyID))
     
    486524    '''
    487525    def populateObjectCalColor(self):
     526
    488527        self.logger.info("Procesing ObjectCalColor table")
    489528
     
    493532               ) \
    494533               SELECT \
    495                objID \
     534               DISTINCT objID \
    496535               ,ippObjID \
    497536               FROM StackDetection"
    498         self.scratchDb.stmt.execute(sql)
     537        self.scratchDb.execute(sql)
    499538
    500539        self.scratchDb.updateFilterID("ObjectCalColor", self.filter)
     
    508547
    509548        self.logger.info("Altering PSPS tables")
    510         self.scratchDb.makeColumnUnique("StackDetection", "objID")
     549        #self.scratchDb.makeColumnUnique("StackDetection", "objID")
    511550        self.scratchDb.createIndex("StackDetection", "ippDetectID")
    512551        self.scratchDb.createIndex("StackApFlx", "ippDetectID")
     
    531570        imageID = self.scratchDb.getImageIDFromExternID(self.header['SOURCEID'], self.header['IMAGEID'])
    532571
    533         self.logger.info("Updating table '" + table + "' with DVO IDs...")
     572        self.logger.debug("Updating table '" + table + "' with DVO IDs...")
    534573        sql = "UPDATE IGNORE " + table + " AS a, dvoDetectionFull AS b SET \
    535574               a.ippObjID = b.ippObjID, \
     
    539578               AND b.sourceID = " + self.header['SOURCEID'] + "\
    540579               AND b.imageID = " + str(imageID)
    541         self.scratchDb.stmt.execute(sql)
    542 
     580        self.scratchDb.execute(sql)
    543581
    544582    '''
     
    553591        self.populateStackMeta()
    554592        self.populateStackDetection()
    555         self.populateStackModelFit()
    556         self.populateStackApFlx()
     593
     594        if self.stackType != "NIGHTLY_STACK":
     595            self.populateStackModelFit()
     596            self.populateStackApFlx()
     597   
    557598        self.populateStackToImage()
    558599        self.populateSkinnyObject()
     
    560601
    561602        self.setMinMaxObjID(["StackDetection"])
    562        
     603       
     604        if self.totalDetections < 1:
     605
     606            self.logger.error("No detections to publish")
     607            return False
     608
    563609        return True
    564610
     
    568614    def alreadyProcessed(self):
    569615
    570         return self.ippToPspsDb.alreadyProcessed("stack", "stack_id", self.stackID)
     616        # sadly, we have to read the FITS primary header first
     617        if not self.readPrimaryHeader(): return False
     618
     619        # get filterID using init table
     620        self.filter = self.header['FPA.FILTER']
     621        self.filter = self.filter[0:1]
     622
     623        self.stackType = stackType
     624        meta = self.gpc1Db.getStackStageMeta(self.id, self.header['FPA.FILTER'])
     625        if len(meta) < 1: return False
     626        self.stackID = meta[0];
     627        self.skycell = meta[1];
     628        self.skycell = self.skycell[8:]
     629
     630        #return self.ippToPspsDb.alreadyProcessed("stack", "stack_id", self.stackID)
     631        return False # TODOI
     632
     633
     634useFullTables=True
    571635
    572636logging.config.fileConfig("logging.conf")
    573637logger = logging.getLogger("stackbatch")
     638logger.setLevel(logging.INFO)
    574639logger.info("Starting")
     640
    575641gpc1Db = Gpc1Db(logger)
    576 stackType = "NIGHTLY_STACK"
    577 skyIDs = gpc1Db.getIDsInThisDVODbForThisStage("MD04.Staticsky", "staticsky")
    578 #skyIDs = gpc1Db.getIDsInThisDVODbForThisStage("MD04.GENE.PSPSDEEP", "staticsky")
    579 #stackType = "DEEP_STACK"
    580 #skyIDs = [689]
     642ippToPspsDb = IppToPspsDb(logger)
     643scratchDb = ScratchDb(logger, useFullTables)
     644
     645#stackType = "NIGHTLY_STACK"
     646#skyIDs = gpc1Db.getIDsInThisDVODbForThisStageFudge()
     647#skyIDs = gpc1Db.getIDsInThisDVODbForThisStage("MD04.Staticsky", "staticsky")
     648
     649stackType = "DEEP_STACK"
     650skyIDs = gpc1Db.getIDsInThisDVODbForThisStage("MD04.GENE.PSPSDEEP", "staticsky")
     651
     652#skyIDs = [942]
    581653#skyIDs = [299]
    582654#skyIDs = [302]
    583655#skyIDs = [8508]
    584 i = 0
     656#i = 0
    585657for skyID in skyIDs:
    586 
    587     logger.info("-------------------------------------------------- sky ID: %d" % skyID)
     658   
     659    #if skyID < 1340: continue # nightly
     660    #if skyID < 238: continue # deep
    588661
    589662    cmfFiles = gpc1Db.getStackStageCmfs(skyID)
     
    591664    for file in cmfFiles:
    592665
    593         if not os.path.isfile(file):
    594             logger.error("Cannot read file at '" + file)
    595             continue
    596 
    597         stackBatch = StackBatch(logger, skyID, file, stackType, True)
    598 
    599         if not stackBatch.alreadyProcessed():
    600 
    601             stackBatch.createEmptyPspsTables()
    602             stackBatch.importIppTables("")
    603             if stackBatch.populatePspsTables():
    604  
    605                 #stackBatch.reportNullsInAllPspsTables(False)
    606                 stackBatch.exportPspsTablesToFits()
    607                 stackBatch.writeBatchManifest()
    608                 #stackBatch.createTarball()
    609                 #stackBatch.publishToDatastore()
    610 
    611                 i = i + 1
    612                 #if i > 0: sys.exit()
    613 
    614 logger.info("Finished")
     666        stackBatch = StackBatch(logger,
     667                                gpc1Db,
     668                                ippToPspsDb,
     669                                scratchDb,
     670                                skyID,
     671                                file,
     672                                stackType,
     673                                useFullTables)
     674
     675        stackBatch.run()
     676
Note: See TracChangeset for help on using the changeset viewer.