IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Ignore:
Timestamp:
Nov 3, 2014, 2:41:20 PM (12 years ago)
Author:
heather
Message:

added diff / ff stages to addstar, partially to ipptopsps

File:
1 edited

Legend:

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

    r36697 r37551  
     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
     26'''
     27ForcedWarpBatch class
     28
     29This class, a sub-class of Batch, processes single exposures in the form of IPP smf files
     30
     31'''
     32class ForcedWarpBatch(Batch):
     33
     34    '''
     35    Constructor
     36    '''
     37    def __init__(self,
     38                 logger,
     39                 config,
     40                 skychunk,
     41                 gpc1Db,
     42                 ippToPspsDb,
     43                 scratchDb,
     44                 forcedWarpID,
     45                 batchID):
     46
     47       super(ForcedWarpBatch, self).__init__(
     48               logger,
     49               config,
     50               skychunk,
     51               gpc1Db,
     52               ippToPspsDb,
     53               scratchDb,
     54               forcedWarpID,
     55               batchID,
     56               "P2",
     57               gpc1Db.getForcedWarpStageSmf(forcedWarpID)
     58
     59       # get camera meta data
     60       meta = self.gpc1Db.getForcedWarpStageMeta(self.id)
     61       if not meta:
     62           self.logger.errorPair("Could not get", "forced warp metadata")
     63           raise
     64
     65       self.expID = meta[0];
     66       self.expName = meta[1];
     67       self.distGroup = meta[2];
     68       self.analysisVer = meta[3];
     69       self.bias = meta[4];
     70       self.biasScat = meta[5];
     71
     72       if not self.analysisVer: self.analysisVer = -999
     73
     74       # create an output filename, which is {expID}.FITS
     75       self.outputFitsFile = "%08d.FITS" % self.expID
     76       self.outputFitsPath = "%s/%s" % (self.localOutPath, self.outputFitsFile)
     77       self.dropTableVerbose("ForcedWarpMeasurement")
     78       self.dropTableVerbose("ForcedWarpExtended")
     79       self.dropTableVerbose("ForcedWarpMeta")
     80       self.dropTableVerbose("ForcedWarpToImage")
     81       if not self.config.retry:
     82       self.scratchDb.dropTable("ForcedWarpMeasurement")
     83       self.scratchDb.dropTable("ForcedWarpExtended")
     84       self.scratchDb.dropTable("ForcedWarpMeta")
     85       self.scratchDb.dropTable("ForcedWarpToImage")
     86       self.historyModNum = "0"
     87
     88       # get a few primary header values. if in test mode, then use defaults
     89       if self.safeDictionaryAccessWithDefault(self.header, 'MJD-OBS', "1") == "NULL":
     90           self.logger.errorPair("Could not get", "MJD-OBS")
     91           raise
     92
     93
     94       if self.safeDictionaryAccessWithDefault(self.header, 'EXPTIME', "1") == "NULL":
     95           self.logger.errorPair("Could not get", "EXPTIME")
     96           raise
     97
     98       if self.safeDictionaryAccessWithDefault(self.header, 'FILTERID', "g.0000") == "NULL":
     99           self.logger.errorPair("Could not get", "FILTERID")
     100           raise
     101       
     102       # MJD-OBS is the exposure start, EXTIME / 172800 = (EXPTIME sec / 84600 sec/day) / 2
     103       self.obsTime = float(self.header['MJD-OBS']) + (float(self.header['EXPTIME']) / 172800.0)
     104     
     105       # set up some defauts
     106       self.calibModNum = 0
     107       self.totalNumPhotoRef = 0
     108
     109
     110       self.filter = self.header['FILTERID'][0:1]
     111       self.filterID = self.scratchDb.getFilterID(self.filter)
     112
     113       # insert what we know about this stack batch into the stack table
     114       self.ippToPspsDb.insertDetectionMeta(self.batchID, self.expID, self.filter)
     115
     116       # dump stuff to log
     117       self.logger.infoPair("Cam ID", "%d" % self.id)
     118       self.logger.infoPair("Exp ID", "%d" % self.expID)
     119       self.logger.infoPair("Exp name", "%s" % self.expName)
     120       self.logger.infoPair("Distribution group", "%s" % self.distGroup)
     121
     122
     123
     124
     125    '''
     126    Populates the FrameMeta table, mainly from dictionary values found in IPP FITS header
     127    '''
     128    def populateForcedWarpMeta(self):
     129        self.logger.infoPair("Processing table", "ForcedWarpMeta")
     130
     131        photoCalID = str(self.scratchDb.getPhotoCalID(forcedWarpID))       
     132
     133
     134        sqlLine = sqlUtility("INSERT INTO ForcedWarpMeta (")
     135        #batchID (below)
     136        #surveyID (below)
     137        #filterdID (below)
     138        sqlLine.group("skyCellID",     str(self.skycellID))
     139        sqlLine.group("photoCalID",    photoCalID)
     140        sqlLine.group("magSat",           self.getKeyFloat(header, "%.8f", 'FSATUR'))
     141        sqlLine.group("analVer",           self.analysisVer);
     142        sqlLine.group("expTime",               self.getKeyFloat(self.header, "%.8f", 'EXPREQ'));
     143        sqlLine.group("completMag",       self.getKeyFloat(header, "%.8f", 'FLIMIT'))
     144        sqlLine.group("astroScat",        self.getKeyFloat(header, "%.8f", 'CERROR'))
     145        sqlLine.group("photoScat",             self.getKeyFloat(self.header, "%.8f", 'ZPT_ERR'));
     146        sqlLine.group("nAstroRef",      self.getKeyValue(header, 'NASTRO'))
     147        sqlLine.group("nPhotoRef",      self.getKeyValue(header, 'NASTRO'))
     148        sqlLine.group("psfModelID",     self.getKeyValue(header, 'PSFMODEL'))
     149        sqlLine.group("psfFwhm_mean",   self.getKeyFloat(header, "%.8f", 'FWHM_MAJ'))
     150        sqlLine.group("psfFwhm_max",    self.getKeyFloat(header, "%.8f", 'FW_MJ_UQ'))
     151        sqlLine.group("photoZero",        self.getKeyFloat(self.header, "%.8f", 'ZPT_OBS'))
     152        #photoColor -- how do I set this? it's also not set in stack meta
     153        sqlLine.group("ctype1",                self.getKeyValue(self.header, 'CTYPE1'));
     154        sqlLine.group("ctype2",                self.getKeyValue(self.header, 'CTYPE2'));
     155        sqlLine.group("crval1",                self.getKeyFloat(self.header, "%.8f", 'CRVAL1'));
     156        sqlLine.group("crval2",                self.getKeyFloat(self.header, "%.8f", 'CRVAL2'));
     157        sqlLine.group("crpix1",                self.getKeyFloat(self.header, "%.8f", 'CRPIX1'));
     158        sqlLine.group("crpix2",                self.getKeyFloat(self.header, "%.8f", 'CRPIX2'));
     159        sqlLine.group("cdelt1",                self.getKeyFloat(self.header, "%.8e", 'CDELT1'));
     160        sqlLine.group("cdelt2",                self.getKeyFloat(self.header, "%.8e", 'CDELT2'));
     161        sqlLine.group("pc001001",              self.getKeyFloat(self.header, "%.8e", 'PC001001'));
     162        sqlLine.group("pc001002",              self.getKeyFloat(self.header, "%.8e", 'PC001002'));
     163        sqlLine.group("pc002001",              self.getKeyFloat(self.header, "%.8e", 'PC002001'));
     164        sqlLine.group("pc002002",              self.getKeyFloat(self.header, "%.8e", 'PC002002'));
     165
     166
     167        sql = sqlLine.make(") VALUES ( ", ")")
     168
     169        try: self.scratchDb.execute(sql)
     170        except:
     171            self.logger.errorPair('failed sql: ', sql)
     172            raise
     173
     174        self.scratchDb.updateAllRows("ForcedWarpMeta", "batchID", str(self.batchID))
     175        self.scratchDb.updateAllRows("ForcedWarpMeta", "surveyID", str(self.surveyID))
     176        self.scratchDb.updateFilterID("ForcedWarpMeta", self.filter)
     177        self.scratchDb.updateAllRows("ForcedWarpMeta", "calibModNum", str(self.calibModNum))
     178        self.scratchDb.updateAllRows("ForcedWarpMeta", "dataRelease", str(self.skychunk.dataRelease))
     179        self.tablesToExport.append("ForcedWarpMeta")
     180       
     181    '''
     182    Populates the ForcedWarpToImage table
     183    '''
     184    def populateForcedWarpToImage(self):
     185
     186        self.logger.infoPair("Procesing table", "ForcedWarpToImage")
     187
     188        for filter in self.filters:
     189           
     190            forcedwarpID = self.forcedwarpID
     191            if forcedwarpID > 0:
     192   
     193                imageIDs = self.gpc1Db.getImageIDsForThisForcedWarpID(forcedwarpID)
     194
     195                for imageID in imageIDs:
     196
     197                    sql = "INSERT INTO ForcedWarpToImage (forcedwarpID, imageID) \
     198                   VALUES (\
     199                   " + str(forcedwarpID) + ", " + imageID + ")"
     200                    self.scratchDb.execute(sql)
     201
     202                    # now update StackMeta with correct number of inputs
     203
     204        self.tablesToExport.append("ForcedWarpToImage")
     205
     206
     207
     208
     209
     210    '''
     211    Populates the ForcedWarpMeasurement table
     212    '''
     213    def populateForcedWarpMeasurementTable(self, results):
     214
     215        pspsTableName = "ForcedWarpMeasurement"
     216        ippTableName = "ForcedWarpMeasurement_psf"
     217
     218
     219        self.logger.infoPair("Procesing table", "ForcedWarpMeasurement")
     220
     221        # insert the per-object data (IDs, random stack ID, dataRelease, etc)
     222        self.selectDvoObjIDs()
     223
     224        self.generateRandomIDs()
     225
     226        # add indexes ForcedWarpMeasurement
     227        self.scratchDb.createIndex("ForcedWarpMeasurement", "objID")
     228
     229               
     230
     231
     232
     233
     234
     235
     236
     237        self.tablesToExport.append("ForcedWarpMeasurement")
     238
     239
     240    '''
     241    Populates the ForcedWarpExtended table
     242    '''
     243    def populateForcedWarpExtendedTable(self, results):
     244
     245        pspsTableName = "ForcedWarpExtended"
     246        ippTableName = "ForcedWarpExtended_psf"
     247
     248   
     249        self.tablesToExport.append("ForcedWarpExtended")
     250
     251
     252    '''
     253    Does the processing, i.e. pulling stuff from IPP tables into PSPS tables
     254    '''
     255    def populatePspsTables(self):
     256        self.logger.infoPair("starting","populatePspsTables");
     257        self.skipBatch = False
     258        # each of the "populate*" methods below add their tables to the list:
     259        self.tablesToExport=[]
     260   
     261        #this should be done
     262        self.populateForcedWarpMeta()         
     263
     264        self.populateForcedWarpMeasurement()           
     265        self.populateForcedWarpExtended()
     266        self.populateForcedWarpToImage()
     267             
     268        self.setMinMaxObjID(["ForcedWarpMeasurement"])
     269
     270        self.logger.infoPair("finishing","populatePspsTables");
     271        return True
     272         
     273
     274
     275    '''
     276    This function reads the cmf/smf file and loads it into the database as its own table
     277    '''
     278    def importIppTables(self, columns="*", tableRE=""):
     279       
     280        if self.config.retry: return True
     281        self.logger.infoPair("Importing FW tables with table match expression: ", tableRE)
     282        fileName = self.fits.getPath()
     283
     284        self.logger.infoPair("using filename:",fileName)
     285           
     286        try:
     287           tables = stilts.treads(fileName)
     288        except:
     289           self.logger.errorPair("STILTS could not import from", fileName)
     290           return False
     291        for table in tables:
     292             
     293           match = re.match(tableRE, table.name)
     294           if not match: continue
     295           self.logger.infoPair("Reading IPP table", table.name)
     296           table = stilts.tpipe(table, cmd='addcol table_index $0')
     297           table = stilts.tpipe(table, cmd='explodeall')
     298           
     299           # drop any previous tables before import
     300           self.scratchDb.dropTable(table.name)
     301                 
     302           # IPP FITS files are littered with infinities, so remove these
     303           self.logger.info("Removing Infinity values from all columns")
     304           table = stilts.tpipe(table, cmd='keepcols "' + columns + '"')
     305           table = stilts.tpipe(table, cmd='replaceval -Infinity null *')
     306           table = stilts.tpipe(table, cmd='replaceval Infinity null *')
     307                 
     308           try:
     309               table.write(self.scratchDb.url + '#' + table.name)
     310               count = count + 1
     311           except:
     312               self.logger.exception("Problem writing table '" + table.name + "' to the database")
     313                     
     314        self.logger.infoPair("Done. Imported", "%d tables" % count)
     315        self.indexIppTables()
     316                     
     317        return True
     318
     319
     320               
     321
     322
     323
     324
     325
     326
     327    def generateRandomIDs(self):
     328        sql = "UPDATE ForcedWarpMeasurement set randomWarpID = FLOOR(RAND()*9223372036854775807)";
     329        try: self.scratchDb.execute(sql)
     330        except:
     331            self.logger.errorPair('failed sql',sql)
     332            return
     333
     334
     335
     336
     337
     338
     339
     340
     341
     342    def exportPspsTablesToFits(self, regex="(.*)"):
     343       return super(DetectionBatch, self).exportPspsTablesToFits("(ForcedWarp.*)")
Note: See TracChangeset for help on using the changeset viewer.