IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Ignore:
Timestamp:
Feb 6, 2013, 3:16:35 PM (13 years ago)
Author:
eugene
Message:

upgrade to ippToPsps (see doc/upgrade.txt): adds native dvo to mysql ingest operations, adds autogen configuration & installation, splits out global config information from new "skychunk" information (current region on the sky being processed), adds test suites

Location:
trunk/ippToPsps
Files:
28 edited
3 copied

Legend:

Unmodified
Added
Removed
  • trunk/ippToPsps

  • trunk/ippToPsps/jython

    • Property svn:ignore
      •  

        old new  
        11*.class
         2Makefile
         3Makefile.in
  • trunk/ippToPsps/jython/batch.py

    r33787 r35097  
    3030                 logger,
    3131                 config,
     32                 skychunk,
    3233                 gpc1Db,
    3334                 ippToPspsDb,
     
    3940                 useFullTables):
    4041
     42        # print "starting the batch"
     43
     44        # self.printline = 0
     45        # self.testprint()
     46
    4147        self.readHeader = False
    4248        self.config = config
     49        self.skychunk = skychunk
    4350        self.fits = fits
    4451        self.useFullTables = useFullTables
     
    4855        self.logger.infoSeparator()
    4956        self.logger.debug("Batch class constructor")
     57
     58        # self.testprint()
    5059
    5160        # set up class variables
     
    5665        self.scratchDb = scratchDb
    5766        self.batchType = batchType;
    58         self.pspsVoTableFilePath = "../config/" + batchType + "/tables.vot"
     67        self.pspsVoTableFilePath = self.config.configDir + "tables." + batchType + ".vot"
     68
     69        # self.testprint()
    5970
    6071        # check FITS file is ok
     
    6475            # now check that the fits header is readable
    6576            if not self.header:
    66                 logger.errorPair("Could not read FITS for id", "%d" % id)
     77                logger.errorPair("Could not read FITS PHU for id", "%d" % id)
    6778                raise
    6879
     
    7283        self.tablesToExport = []
    7384
    74         if self.config.survey != "":
    75             self.surveyID = self.scratchDb.getSurveyID(self.config.survey)
     85        if self.skychunk.survey != "":
     86            self.surveyID = self.scratchDb.getSurveyID(self.skychunk.survey)
    7687        else:
    7788            self.surveyID = -1;
    7889       
    7990        # create datastore object
    80         self.datastore = Datastore(self.logger, self.config, self.ippToPspsDb)
    81 
    82         # get local storage location from config
     91        self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb)
     92
     93        # get local storage location from skychunk
    8394        self.batchName = Batch.getNameFromID(self.batchID)
    8495        self.subDir = Batch.getSubDir(
    85                 self.config.basePath,
     96                self.skychunk.basePath,
    8697                self.batchType,
    87                 self.config.dvoLabel)
     98                self.skychunk.dvoLabel)
    8899
    89100        self.localOutPath = Batch.getOutputPath(
    90                 self.config.basePath,
     101                self.skychunk.basePath,
    91102                self.batchType,
    92                 self.config.dvoLabel,
     103                self.skychunk.dvoLabel,
    93104                self.batchID)
    94105
    95106        if not os.path.exists(self.localOutPath): os.makedirs(self.localOutPath)
     107
     108        # self.testprint()
    96109
    97110        # store today's date
     
    112125            self.logger.infoPair("Input FITS primary header", "%s cards found" % self.fits.getPrimaryHeaderCardCount())
    113126
     127        # self.testprint()
     128
    114129        self.logger.infoPair("Output path", self.localOutPath)
    115130
    116131   
     132    def testprint(self):
     133      print "here ", self.printline
     134      self.printline += 1
     135
    117136    '''
    118137    Static method to generated batch name from batch ID
     
    232251        root.attrib['type'] = self.batchType
    233252        root.attrib['timestamp'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    234         root.attrib['survey'] = self.config.pspsSurvey
     253        root.attrib['survey'] = self.skychunk.pspsSurvey
    235254
    236255        # min/max object IDs
     
    273292        # set up filenams and paths
    274293        tarFile = Batch.getTarFile(self.batchID)
    275         tarPath = Batch.getTarPath(self.config.basePath, self.batchType, self.config.dvoLabel, self.batchID)
     294        tarPath = Batch.getTarPath(self.skychunk.basePath, self.batchType, self.skychunk.dvoLabel, self.batchID)
    276295        tarballFile = Batch.getTarballFile(self.batchID)
    277         tarballPath = Batch.getTarballPath(self.config.basePath, self.batchType, self.config.dvoLabel, self.batchID)
     296        tarballPath = Batch.getTarballPath(self.skychunk.basePath, self.batchType, self.skychunk.dvoLabel, self.batchID)
    278297
    279298        # tar directory
     
    376395      self.logger.infoPair("Importing tables with filter", filter)
    377396
     397      # print "trying to read ", self.fits.getPath()
     398
    378399      try:
    379400          tables = stilts.treads(self.fits.getPath())
     
    385406      for table in tables:
    386407
     408          # print "import smf table ", table
    387409          match = re.match(filter, table.name)
    388410          if not match: continue
    389411          self.logger.debugPair("Reading IPP table", table.name)
    390412          table = stilts.tpipe(table, cmd='explodeall')
     413
     414          # print "read smf table ", table
    391415
    392416          # drop any previous tables before import
     
    398422          table = stilts.tpipe(table, cmd='replaceval -Infinity null *')
    399423          table = stilts.tpipe(table, cmd='replaceval Infinity null *')
     424          # print "cleaned up values ", table
    400425
    401426          try:
    402427              table.write(self.scratchDb.url + '#' + table.name)
     428              # print "wrote to mysql ", table
    403429              self.scratchDb.killLastConnectionID()
    404430              count = count + 1
     
    488514
    489515        # TODO path to DVO prog hardcoded temporarily
    490         cmd = "../src/dvograbber " + self.config.settingsPath + " " + self.scratchDb.dbName + " " + self.config.dvoLocation
     516        cmd = "../src/dvograbber " + self.config.settingsPath + " " + self.scratchDb.dbName + " " + self.skychunk.dvoLocation
    491517        self.logger.infoPair("Running DVO", cmd)
    492518        p = Popen(cmd, shell=True, stdout=PIPE)
     
    504530    '''
    505531    Creates and publishes a batch
    506     TODO all methods call below should throw exceptions on failure
     532    TODO all method calls below should throw exceptions on failure
    507533    '''
    508534    def run(self):
    509535
     536        # this is badly named : it creates the tables and then fills in
     537        # the ImageMeta tables for each ota (alterPspsTables)
    510538        if not self.createEmptyPspsTables():
    511539            self.logger.errorPair("Aborting this batch", "could not create empty PSPS tables")
     
    513541            raise
    514542
     543        # for P2/ST, this reads the detection tables from the CMF/SMF file(s)
     544        # for OB, this imports object data from DVO
    515545        if not self.importIppTables():
    516546            self.logger.errorPair("Aborting this batch", "could not import IPP tables")
     
    529559   
    530560        if self.writeBatchManifest():
    531             if self.config.datastorePublishing:
     561            if self.skychunk.datastorePublishing:
    532562
    533563                # tar and zip ready for publication to datastore
  • trunk/ippToPsps/jython/batchRepublisher.py

    r33866 r35097  
    3030            self.exitProgram("incorrect args")
    3131
    32         self.datastore = Datastore(self.logger, self.config, self.ippToPspsDb)
     32        self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb)
    3333        self.BATCHID = int(sys.argv[2])
    3434
     
    4040        batchName = Batch.getNameFromID(self.BATCHID)
    4141        batchType = self.ippToPspsDb.getBatchType(self.BATCHID)
    42         subDir = Batch.getSubDir(self.config.basePath, batchType, self.config.dvoLabel)
     42        subDir = Batch.getSubDir(self.skychunk.basePath, batchType, self.skychunk.dvoLabel)
    4343        tarballFile = Batch.getTarballFile(self.BATCHID)
    4444
     
    5050        self.logger.infoPair("Reseting batch in database", "%d" % self.BATCHID)
    5151        self.ippToPspsDb.resetBatch(self.BATCHID)
    52         self.logger.infoPair("publishing to", self.config.datastoreProduct)
     52        self.logger.infoPair("publishing to", self.skychunk.datastoreProduct)
    5353        Batch.publishToDatastore(self.datastore, self.BATCHID, batchName, subDir, tarballFile)
    5454
  • trunk/ippToPsps/jython/cleanup.py

    r33818 r35097  
    2626        super(Cleanup, self).__init__(argv)
    2727
    28         self.datastore = Datastore(self.logger, self.config, self.ippToPspsDb)
     28        self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb)
    2929        self.dxlayer = DXLayer(self.logger)
    3030        if len(argv) > 2: self.parsePollTimeArg(sys.argv[2])
     
    4040
    4141            self.logger.infoSeparator()
    42             self.logger.infoPair("Config", self.config.name)
    43             self.config.printDeletionPolicy()
     42            self.logger.infoPair("Skychunk", self.skychunk.name)
     43            self.skychunk.printDeletionPolicy()
    4444            self.clean("IN")
    4545            self.clean("P2")
     
    8989   
    9090        # delete stuff from local disk
    91         if self.config.deleteLocal:
     91        if self.skychunk.deleteLocal:
    9292            count = 0
    9393            for id in deleteFromLocalIDs:
    9494       
    95                 if Batch.deleteFromDisk(self.logger, self.config.basePath, batchType, self.config.dvoLabel, id):
     95                if Batch.deleteFromDisk(self.logger, self.skychunk.basePath, batchType, self.skychunk.dvoLabel, id):
    9696                    self.ippToPspsDb.updateDeletedLocal(id, 1)
    9797                    count = count + 1
     
    100100   
    101101        # remove stuff from datastore
    102         if self.config.deleteDatastore:
     102        if self.skychunk.deleteDatastore:
    103103            count = 0
    104104            for id in deleteFromDatastoreIDs:
     
    112112       
    113113        # remove stuff from DXLayer
    114         if self.config.deleteDxLayer:
     114        if self.skychunk.deleteDxLayer:
    115115            count = 0
    116116            for id in deleteFromDxLayerIDs:
  • trunk/ippToPsps/jython/config.py

    r33728 r35097  
    11#!/usr/bin/env jython
    22
     3import sys
     4import os
    35import logging
    46from xml.etree.ElementTree import ElementTree, Element, tostring
     
    68from pslogger import PSLogger
    79
    8 
    910'''
    10 A class encapsulating a ippToPsps configuration. This information is stored in the 'config' table
    11 of the ipptopsps database, but there are some higher level config details in the 'settings.xml' file
     11A class encapsulating the globald ippToPsps configuration information.
     12This is stored in the 'settings.xml' file in the config directory
    1213'''
    1314class Config(object):
    14 
    1515
    1616    '''
     
    1919    Basically reads the entire config and stores values to class variables
    2020    '''
    21     def __init__(self, programName, name):
     21    def __init__(self):
    2222
    23         self.programName = programName
    24         self.name = name
    25         self.settingsPath = "../config/settings.xml" # TODO
     23        self.test = False
     24        for arg in sys.argv:
     25            if arg == "-test":
     26                self.test = True
     27                sys.argv.remove(arg)
     28            if arg == "-t":
     29                self.test = True
     30                sys.argv.remove(arg)
     31
     32        ## name of the top-level jython script
     33        self.programName = os.path.basename(sys.argv[0])
     34
     35        ## this is somewhat crude: ipptopsps programs are called like this:
     36        ## ippjython foo.py [chunk] [other options]
     37        ## the logging code (called below by getLogger) wants to include 'name' in the
     38        ## output file.  we blindly set name == argv[1]
     39        ## programs which are called without argv[1] will use 'none' in the log file
     40        if len(sys.argv) >= 2:
     41            self.name = sys.argv[1]
     42
     43        # XXX this probably goes in 'config.py'
     44        self.configDir = os.getenv("IPPTOPSPS_DATA")
     45        if self.configDir is None:
     46            self.configDir = "../config/"
     47        else:
     48            self.configDir = self.configDir + "/"
     49
     50        # self.configdir is set in ipptopsps.jy on init based on env(IPPTOPSPS_DATA)
     51        # for test purposes, an uninstalled system may use the config information from
     52        # a relative path
     53        self.settingsPath = self.configDir + "settings.xml"
     54
    2655        self.logger = None
    2756
    2857        self.settingsDoc = ElementTree(file=self.settingsPath)
    2958        self.logPath = self.settingsDoc.find("logPath").text
    30         self.czarPlotsPath = self.settingsDoc.find("czarPlotsPath").text
    3159
    32         # this is the border (in degrees) that we place around any loading box of
    33         # PS1 pointings to ensure we pull a large enough area out of DVO
    34         self.BORDER = 1.65
    35         self.isLoaded = False
    36 
    37     '''
    38     Prints everything for this config
    39     '''
    40     def printAll(self):
    41 
    42         self.logger.infoTitle("Config")
    43 
    44         try:
    45             self.logger.infoSeparator()
    46             self.logger.infoPair("Config name", self.name)
    47             self.logger.infoPair("Survey", self.survey)
    48             self.logger.infoPair("Publishing to PSPS as survey", self.pspsSurvey)
    49             self.logger.infoPair("Loading epoch", self.epoch)
    50             self.logger.infoPair("Data release", "%d" % self.dataRelease)
    51             for batchType in self.batchTypes: self.logger.infoPair("Queuing batch type", batchType)
    52         except:
    53             pass
    54 
    55         self.printDvoInfo()
    56         self.printDatastoreInfo()
    57         self.printBoxCoords()
    58         self.printDeletionPolicy()
    59         try: self.logger.infoSeparator()
    60         except: pass
    61 
    62     '''
    63     Queuing this batch type?
    64     '''
    65     def queuingThisBatchType(self, batchType):
    66        if batchType in self.batchTypes: return 1
    67        return 0
     60        print "config.programName: ", self.programName
     61        print "config.configDir: ", self.configDir
     62        print "config.settingsPath: ", self.settingsPath
     63        print "config.logPath: ", self.logPath
     64        print "config.test: ", self.test
    6865
    6966    '''
     
    7269    def getLogger(self, host, pid, stdout=1, sendToFile=0):
    7370       
     71        print "get Logger: ", host, pid
    7472        logging.setLoggerClass(PSLogger)
     73        print "done Logger 1"
    7574        self.logger = logging.getLogger(self.programName)
    76         self.logger.setup(self.programName, self.logPath, self.name, host, pid, stdout, sendToFile)
     75        print "done Logger 2"
     76        if (self.name is None):
     77            self.logger.setup(self.programName, self.logPath, "none", host, pid, stdout, sendToFile)
     78        else:
     79            self.logger.setup(self.programName, self.logPath, self.name, host, pid, stdout, sendToFile)
     80        print "done Logger 3"
    7781
    7882        return self.logger
    79 
    80     '''
    81     Prints the currently set DVO info
    82     '''
    83     def printDvoInfo(self):
    84 
    85         try:
    86             self.logger.infoPair("DVO label", self.dvoLabel)
    87             self.logger.infoPair("DVO location", self.dvoLocation)
    88         except:
    89             pass
    90    
    91     '''
    92     Prints datastore info
    93     '''
    94     def printDatastoreInfo(self):
    95 
    96         try:
    97             self.logger.infoBool("Datastore publishing?", self.datastorePublishing)
    98             if self.datastorePublishing:
    99                 self.logger.infoPair("Datastore type", self.datastoreProduct)
    100                 self.logger.infoPair("Datastore product", self.datastoreType)
    101         except:
    102             pass
    103    
    104     '''
    105     Prints the current deletion policy
    106     '''
    107     def printDeletionPolicy(self):
    108 
    109         try:
    110             self.logger.infoBool("Deleting local?", self.deleteLocal)
    111             self.logger.infoBool("Deleting datastore?", self.deleteDatastore)
    112             self.logger.infoBool("Deleting DXLayer?", self.deleteDxLayer)
    113         except:
    114             pass
    115    
    116     '''
    117     Prints the currently set RA/Dec bounding box
    118     '''
    119     def printBoxCoords(self):
    120 
    121         try:
    122             self.logger.infoPair("RA limits", "%.1f -> %.1f" % (self.minRa, self.maxRa))
    123             self.logger.infoPair("Dec limits", "%.1f -> %.1f" % (self.minDec, self.maxDec))
    124             self.logger.infoPair("Loading box size", "%.1f degrees" % self.boxSize)
    125         except:
    126             pass
    127    
    12883
    12984    '''
     
    13489    def getDbUser(self, dbType): return self.settingsDoc.find(dbType +"/user").text
    13590    def getDbPassword(self, dbType): return self.settingsDoc.find(dbType +"/password").text
    136 
  • trunk/ippToPsps/jython/console.py

    r33729 r35097  
    3737   
    3838        self.frame = JFrame(
    39                 "ippToPsps console for config '" + self.config.name + "'",
     39                "ippToPsps console for skychunk '" + self.skychunk.name + "'",
    4040                layout=BorderLayout(),
    4141                size=(1000, 500),
     
    7474        button = JButton('Purge dead', actionPerformed=self.purgeDead)
    7575        buttonPanel.add(button)
    76         button = JButton('Change config', actionPerformed=self.changeConfig)
     76        button = JButton('Change skychunk', actionPerformed=self.changeSkychunk)
    7777        buttonPanel.add(button)
    7878
     
    136136        self.ippToPspsDb.purgeDeadClients()
    137137        self.refreshClientTable(None)
    138     def changeConfig(self, event):
     138    def changeSkychunk(self, event):
    139139        ids = self.getSelectedIds()
    140140        if len(ids) < 1:
    141141            JOptionPane.showMessageDialog(None, "No clients selected", "Error", JOptionPane.ERROR_MESSAGE)
    142142            return
    143         comboBox = JComboBox(self.ippToPspsDb.getActiveConfigList())
     143        comboBox = JComboBox(self.ippToPspsDb.getActiveSkychunkList())
    144144        if JOptionPane.showConfirmDialog(None,
    145145                comboBox,
    146                 "Choose a config",
     146                "Choose a skychunk",
    147147                JOptionPane.OK_CANCEL_OPTION,
    148148                JOptionPane.PLAIN_MESSAGE) == JOptionPane.CANCEL_OPTION: return
    149149
    150         self.ippToPspsDb.setConfigForLoaders(comboBox.getSelectedItem(), ids)
     150        self.ippToPspsDb.setSkychunkForLoaders(comboBox.getSelectedItem(), ids)
    151151        self.refreshClientTable(None)
    152152
  • trunk/ippToPsps/jython/datastore.py

    r33774 r35097  
    11#!/usr/bin/env jython
     2# EAM : config -> skychunk DONE
    23
    34from subprocess import call, PIPE, Popen
     
    1920
    2021    '''
    21     def __init__(self, logger, config, ippToPspsDb):
     22    def __init__(self, logger, skychunk, ippToPspsDb):
    2223   
    2324        # setup logger
    2425        self.logger = logger
    25         self.config = config
     26        self.skychunk = skychunk
    2627        self.ippToPspsDb = ippToPspsDb
    2728
     
    4243        command  = "dsreg --add " + name + "\
    4344                    --link --datapath " + path + "\
    44                     --type " + self.config.datastoreType + "\
    45                     --product " + self.config.datastoreProduct + "\
     45                    --type " + self.skychunk.datastoreType + "\
     46                    --product " + self.skychunk.datastoreProduct + "\
    4647                    --list " + tempFile.name
    4748
     
    7576                   --del " + name + " \
    7677                   --rm \
    77                    --product " + self.config.datastoreProduct
     78                   --product " + self.skychunk.datastoreProduct
    7879
    7980        p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
  • trunk/ippToPsps/jython/datastoreRemover.py

    r33787 r35097  
    2424            self.exitProgram("incorrect args")
    2525
    26         self.datastore = Datastore(self.logger, self.config, self.ippToPspsDb)
     26        self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb)
    2727
    2828    '''
  • trunk/ippToPsps/jython/detectionbatch.py

    r34879 r35097  
    33import os.path
    44import sys
     5import glob
    56import time
    67import stilts
     8
    79from java.lang import *
    810from java.sql import *
     
    3436                 logger,
    3537                 config,
     38                 skychunk,
    3639                 gpc1Db,
    3740                 ippToPspsDb,
     
    4447               logger,
    4548               config,
     49               skychunk,
    4650               gpc1Db,
    4751               ippToPspsDb,
     
    7276       self.outputFitsPath = "%s/%s" % (self.localOutPath, self.outputFitsFile)
    7377
    74        # if test mode
    75        if self.config.test:
    76            self.startX = 3
    77            self.endX = 4
    78            self.startY = 3
    79            self.endY = 4
    80        else:
    81            self.startX = 0
    82            self.endX = 8
    83            self.startY = 0
    84            self.endY = 8
     78       self.startX = 0
     79       self.endX = 8
     80       self.startY = 0
     81       self.endY = 8
    8582
    8683       #self.startX = 1
     
    8986       #self.endY = 8
    9087
    91        # get a fre primary header values. if in test mode, then use defaults
     88       # get a few primary header values. if in test mode, then use defaults
    9289       if self.safeDictionaryAccessWithDefault(self.header, 'MJD-OBS', "1") == "NULL":
    9390           self.logger.errorPair("Could not get", "MJD-OBS")
     
    214211        ," + self.safeDictionaryAccess(self.header, 'PCA2X0Y2') + " \
    215212        )"
     213
     214        print "frame meta sql: ", sql
     215
    216216        self.scratchDb.execute(sql)
    217217
     
    219219        self.scratchDb.updateFilterID("FrameMeta", self.filter)
    220220        self.scratchDb.updateAllRows("FrameMeta", "calibModNum", str(self.calibModNum))
    221         self.scratchDb.updateAllRows("FrameMeta", "dataRelease", str(self.config.dataRelease))
     221        self.scratchDb.updateAllRows("FrameMeta", "dataRelease", str(self.skychunk.dataRelease))
    222222
    223223    '''
     
    228228        tableName = "ImageMeta_" + ota
    229229       
     230        # XXX we drop the table above so it is not left behind on failure
    230231        # drop then re-create table
    231         self.scratchDb.dropTable(tableName)
     232        # self.scratchDb.dropTable(tableName)
    232233        sql = "CREATE TABLE " + tableName + " LIKE ImageMeta"
    233234        try: self.scratchDb.execute(sql)
    234235        except: pass
    235 
    236         # insert all detections into table
     236        if (ota[0:2] == "XY"): ccdID = ota[2:4]
     237        else: ccdID = 0
     238
     239        # insert image metadata into table
    237240        sql = "INSERT INTO " + tableName + " ( \
    238241               frameID \
     
    299302               ) VALUES ( \
    300303               " + str(self.expID) + " \
    301                ," + ota[2:4] + " \
     304               ," + str(ccdID) + " \
    302305               ," + str(self.bias) + " \
    303306               ," + str(self.biasScat) + " \
     
    366369        self.scratchDb.updateFilterID(tableName, self.filter)
    367370        self.scratchDb.updateAllRows(tableName, "calibModNum", str(self.calibModNum))
    368         self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.config.dataRelease))
     371        self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.skychunk.dataRelease))
    369372        if 'NASTRO' in header: self.totalNumPhotoRef = self.totalNumPhotoRef + int(header['NASTRO'])
    370373        self.scratchDb.replaceNullsInThisColumn(tableName, "polyOrder", "0")
     
    386389        except: pass
    387390       
    388         # delete all detections with PSF_INST_MAG < 17.5, as decreed by Gene
     391        # delete all detections with PSF_INST_MAG < -17.5, as decreed by Gene
    389392        BEFORE = self.scratchDb.getRowCount(ippTableName)
    390393        #don't do this anymore
     
    464467               , '" + self.dateStr + "' \
    465468               , 0 \
    466                , " + str(self.config.dataRelease) + "\
     469               , " + str(self.skychunk.dataRelease) + "\
    467470               FROM " + ippTableName
    468471        # self.logger.info(sql)
     472
    469473        self.scratchDb.execute(sql)
    470474
     
    517521        self.scratchDb.execute(sql)
    518522
    519         self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.config.dataRelease))
     523        self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.skychunk.dataRelease))
    520524
    521525    '''
    522526    Populates the DetectionCalib table for this OTA
    523527    '''
    524     def populateDetectionCalibTable(self, ota):
     528    def populateDetectionCalibTableUpdateInsert(self, ota):
    525529
    526530        tableName = "DetectionCalib_" + ota
     
    562566            WHERE a.objID = b.objID AND a.detectID = b.detectID"
    563567        self.scratchDb.execute(sql)
    564         self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.config.dataRelease))
     568        self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.skychunk.dataRelease))
     569       
     570    '''
     571    Populates the DetectionCalib table for this OTA
     572    '''
     573    def populateDetectionCalibTable(self, ota):
     574
     575        # target table name:
     576        tableName = "DetectionCalib_" + ota
     577        # drop then re-create table
     578        self.scratchDb.dropTable(tableName)
     579        sql = "CREATE TABLE " + tableName + " LIKE DetectionCalib"
     580        try: self.scratchDb.execute(sql)
     581        except: pass
     582
     583        externID = self.imageIDs[ota]
     584
     585        imageID = self.scratchDb.getImageIDFromExternID(externID)
     586        self.logger.infoPair("obtained","imageID")
     587
     588        # check for & create output directory first
     589        datadumpDir = "/tmp/datadump"
     590        try:
     591            statinfo = os.stat(datadumpDir)
     592            # check on the stat results?
     593        except:
     594            print "making the data dump directory ", datadumpDir
     595            os.mkdir(datadumpDir)
     596            os.chmod(datadumpDir, 0777)
     597            statinfo = os.stat(datadumpDir)
     598
     599        dumpFile = datadumpDir + "/genetest.xx.dat"
     600        files = glob.glob(dumpFile)
     601        if len(files) > 0:
     602            os.unlink(dumpFile)
     603
     604        # insert all detections into table
     605        sql = "SELECT \
     606          a.objID,    \
     607          a.detectID, \
     608          a.ippObjID,      \
     609          a.ippDetectID,   \
     610          a.filterID,      \
     611          a.surveyID,      \
     612          b.ra,            \
     613          b.dec_,          \
     614          b.raErr,         \
     615          b.decErr,        \
     616          b.zp,            \
     617          b.zpErr,         \
     618          b.expTime,       \
     619          b.airMass,       \
     620          " + str(self.skychunk.dataRelease) + " \
     621         FROM              \
     622           Detection_" + ota + " as a \
     623         JOIN " + self.scratchDb.dvoDetectionTable + " as b \
     624         ON (a.objID = b.objID AND a.detectID = b.detectID) \
     625         WHERE b.imageID = " + str(imageID) + \
     626         " INTO OUTFILE '" + dumpFile + "'"
     627        print "sql: ", sql
     628        self.scratchDb.execute(sql)
     629
     630        sql = "LOAD DATA INFILE '" + dumpFile + "' INTO TABLE " + tableName
     631        print "sql: ", sql
     632        self.scratchDb.execute(sql)
    565633       
    566634    '''
     
    591659
    592660        self.scratchDb.updateAllRows(tableName, "calibModNum", str(self.calibModNum))
    593         self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.config.dataRelease))
    594 
     661        self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.skychunk.dataRelease))
     662
     663    '''
     664    Applies indexes and other constraints to the PSPS tables
     665    '''
     666    def alterPspsTablesChip(self, chipname, extname, x, y):
     667
     668        # drop the ImageMeta_ table first, or we can leave an invalid table behind
     669        tableName = "ImageMeta_" + chipname
     670       
     671        # drop then re-create table
     672        self.scratchDb.dropTable(tableName)
     673
     674        # load corresponding header into memory
     675        header = self.fits.findAndReadHeader(extname)
     676        if not header:
     677            self.logger.errorPair("No header found for chip", chipname)
     678            return False
     679       
     680        # check we have valid sourceID/imageID pair from the header
     681        if self.safeDictionaryAccess(header, 'SOURCEID') == "NULL": return False
     682        if self.safeDictionaryAccess(header, 'IMAGEID') == "NULL": return False
     683       
     684        # store sourceID/imageID combo in Db so DVO can look up later
     685        if not self.useFullTables:
     686            self.scratchDb.insertNewDvoExternID(header['SOURCEID'], header['IMAGEID'])
     687           
     688        # store these for later
     689        self.imageIDs[chipname] = header['IMAGEID']
     690           
     691        # populate ImageMeta
     692        self.populateImageMetaTable(chipname, header)
     693        self.updateImageID("ImageMeta_" + chipname, x, y)
     694           
     695        return True
    595696
    596697    '''
     
    623724                ota = "XY%d%d" % (x, y)
    624725               
    625                 # load corresponding header into memory
    626                 header = self.fits.findAndReadHeader(ota + ".hdr")
    627                 if not header:
    628                     self.logger.errorPair("No header found for OTA", ota)
    629                     continue
    630 
    631                 # check we have valid sourceID/imageID pair from the header
    632                 if self.safeDictionaryAccess(header, 'SOURCEID') == "NULL": continue
    633                 if self.safeDictionaryAccess(header, 'IMAGEID') == "NULL": continue
    634 
    635                 # store sourceID/imageID combo in Db so DVO can look up later
    636                 if not self.useFullTables:
    637                     self.scratchDb.insertNewDvoExternID(header['SOURCEID'], header['IMAGEID'])
    638 
    639                 # store these for later
    640                 self.imageIDs[ota] = header['IMAGEID']
    641 
    642                 # populate ImageMeta
    643                 self.populateImageMetaTable(ota, header)
    644                 self.updateImageID("ImageMeta_" + ota, x, y)
    645              
     726                self.alterPspsTablesChip(ota, ota + ".hdr", x, y)
     727
     728        # try the test Chip
     729        self.alterPspsTablesChip("Chip", "Chip.hdr", 0, 0)
     730
    646731        # now run DVO code to get all IDs
    647732        if not self.useFullTables:
     
    651736        # the column in PSPS
    652737        self.scratchDb.execute("ALTER TABLE DetectionCalib CHANGE dec_ `dec` double")
    653 
    654 
    655738
    656739        return True
     
    675758                extension = "XY%d%d_psf" % (x, y)
    676759                self.scratchDb.createIndex(extension, "IPP_IDET")
     760        # try the test Chip
     761        self.scratchDb.createIndex("Chip_psf", "IPP_IDET")
     762
    677763        self.logger.infoPair("created indexes on", "IPP tables")     
     764
    678765    '''
    679766    Updates provided table with DVO IDs from DVO table
     
    693780        self.scratchDb.execute(sql)
    694781
     782    '''
     783    Does the processing, i.e. pulling stuff from IPP tables into PSPS tables
     784    '''
     785    def populatePspsTablesChip(self, chipname, x, y, results, tables):
     786        # XXX EAM NOTE: drop tables (Detection_, SkinnyObject_, DetectionCalib_, Detection_) here so
     787        # they do not polute the db?
     788        # XXX or put an explicit drop at the end of the loop?
     789
     790        #self.logger.infoTitle("Processing " + chipname)
     791        # this is a bit crude: if the chip is not present, this test will fail and the chip
     792        # will be (correctly) skipped.  would be better to carry that information explicitly ("chip is missing")
     793        if not self.scratchDb.astrometricSolutionOK(chipname):
     794            self.logger.info("| %5s |            ------------- Bad astrometric solution : rejecting ------------                    |" % chipname)
     795            return False
     796        self.logger.info("populate stuff ");
     797        # populate remainder of tables
     798        self.populateDetectionTable(chipname, results)
     799        self.logger.info("successful populate ");
     800        # now add DVO IDs
     801        self.updateDvoIDs("Detection_" + chipname, self.imageIDs[chipname])
     802        self.logger.info("updated dvoids")
     803        results['NULLOBJID'] = self.scratchDb.reportAndDeleteRowsWithNULLS("Detection_" + chipname, "objID")
     804        #self.logger.info("deleted nulls")
     805        self.updateImageID("Detection_" + chipname, x, y)
     806        self.logger.info("updateImageId")
     807        rowCount = self.scratchDb.getRowCount("Detection_" + chipname)
     808        self.logger.info("got row count")
     809        self.logger.info("| %5s | %13d | %13d | %13d | %13d | %13d | %13d |",
     810                chipname,
     811                results['ORIGINALTOTAL'],
     812                results['SATDET'],
     813                results['NULLINSTFLUX'],
     814                results['NULLPEAKADU'],
     815                results['NULLOBJID'],
     816                rowCount)
     817        self.totalOriginal     = self.totalOriginal + results['ORIGINALTOTAL']
     818        self.totalSatDet       = self.totalSatDet + results['SATDET']
     819        self.totalNulIInstFlux = self.totalNulIInstFlux + results['NULLINSTFLUX']
     820        self.totalNullPeakFlux = self.totalNullPeakFlux + results['NULLPEAKADU']
     821        self.totalNullObjID    = self.totalNullObjID + results['NULLOBJID']
     822        self.totalDetections   = self.totalDetections + rowCount
     823        #self.logger.info("updated totals")
     824        # check we have something in this Detection table TODO add this to table above
     825        if rowCount < 1:
     826            self.logger.infoPair("Skipping empty table for chipname", chipname)
     827            return False;
     828
     829        # update ImageMeta with count of detections for this CHIPNAME and photoCodeID
     830        sql = "UPDATE ImageMeta_" + chipname + " \
     831               SET nDetect = %d, photoCalID = %d" % (self.scratchDb.getRowCount("Detection_" + chipname), self.scratchDb.getPhotoCalID(self.imageIDs[chipname]))
     832        self.scratchDb.execute(sql)
     833       
     834        self.logger.info("updated imagedata")
     835        self.populateSkinnyObjectTable(chipname)
     836        self.logger.info("updated skinnyobject")
     837        #self.populateObjectCalColorTable(chipname)
     838        #self.logger.info("updated objectcalcolor")
     839        self.populateDetectionCalibTable(chipname)
     840        self.logger.info("updated detectioncalibtable")
     841       
     842        # add these to list of tables to export later
     843        self.tablesToExport.append("ImageMeta_" + chipname)
     844        self.logger.info("export ImageMeta")
     845
     846        self.tablesToExport.append("Detection_" + chipname)
     847        self.logger.info("export Detection")
     848
     849        self.tablesToExport.append("SkinnyObject_" + chipname)
     850        self.logger.info("export Skinny")
     851
     852        #self.tablesToExport.append("ObjectCalColor_" + chipname)
     853        self.tablesToExport.append("DetectionCalib_" + chipname)
     854        self.logger.info("export DetectionCalib")
     855
     856        tables.append("Detection_" + chipname)
     857        self.logger.info("updated detectioncalibtable")
     858
     859        return True
    695860
    696861    '''
     
    705870        otaCount = 0
    706871        results = {}
    707         totalOriginal = totalSatDet = totalNulIInstFlux = totalNullPeakFlux = totalNullObjID = totalDetections = 0
     872        self.totalOriginal = self.totalSatDet = self.totalNulIInstFlux = self.totalNullPeakFlux = self.totalNullObjID = self.totalDetections = 0
    708873        self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+---------------+")
    709874        self.logger.info("|  OTA  | Initial total |   Sat Det     | NULL instFlux | NULL peak ADU | NULL obj ID   |  Remainder    |")
     
    721886                if ota not in self.imageIDs: continue
    722887
    723                 #self.logger.infoTitle("Processing " + ota)
    724                 if not self.scratchDb.astrometricSolutionOK(ota):
    725                     self.logger.info("| %5s |            ------------- Bad astrometric solution : rejecting ------------                    |" % ota)
    726                     continue
    727                # self.logger.info("populate stuff ");
    728                 # populate remainder of tables
    729                 self.populateDetectionTable(ota, results)
    730                # self.logger.info("successful populate ");
    731                 # now add DVO IDs
    732                 self.updateDvoIDs("Detection_" + ota, self.imageIDs[ota])
    733                # self.logger.info("updated dvoids")
    734                 results['NULLOBJID'] = self.scratchDb.reportAndDeleteRowsWithNULLS("Detection_" + ota, "objID")
    735                 #self.logger.info("deleted nulls")
    736                 self.updateImageID("Detection_" + ota, x, y)
    737                # self.logger.info("updateImageId")
    738                 rowCount = self.scratchDb.getRowCount("Detection_" + ota)
    739               #  self.logger.info("got row count")
    740                 self.logger.info("| %5s | %13d | %13d | %13d | %13d | %13d | %13d |",
    741                         ota,
    742                         results['ORIGINALTOTAL'],
    743                         results['SATDET'],
    744                         results['NULLINSTFLUX'],
    745                         results['NULLPEAKADU'],
    746                         results['NULLOBJID'],
    747                         rowCount)
    748                 totalOriginal = totalOriginal + results['ORIGINALTOTAL']
    749                 totalSatDet = totalSatDet + results['SATDET']
    750                 totalNulIInstFlux = totalNulIInstFlux + results['NULLINSTFLUX']
    751                 totalNullPeakFlux = totalNullPeakFlux + results['NULLPEAKADU']
    752                 totalNullObjID = totalNullObjID + results['NULLOBJID']
    753                 totalDetections = totalDetections + rowCount
    754                 #self.logger.info("updated totals")
    755                 # check we have something in this Detection table TODO add this to table above
    756                 if rowCount < 1:
    757                     self.logger.debugPair("Skipping empty table for ota", ota)
    758                     continue;
    759 
    760                 # update ImageMeta with count of detections for this OTA and photoCodeID
    761                 sql = "UPDATE ImageMeta_" + ota + " \
    762                        SET nDetect = %d, photoCalID = %d" % (self.scratchDb.getRowCount("Detection_" + ota), self.scratchDb.getPhotoCalID(self.imageIDs[ota]))
    763                 self.scratchDb.execute(sql)
    764                
    765                 #self.logger.info("updated imagedata")
    766                 self.populateSkinnyObjectTable(ota)
    767                 #self.logger.info("updated skinnyobject")
    768                 #self.populateObjectCalColorTable(ota)
    769                 #self.logger.info("updated objectcalcolor")
    770                 self.populateDetectionCalibTable(ota)
    771                 #self.logger.info("updated detectioncalibtable")
    772                
    773                 # add these to list of tables to export later
    774                 self.tablesToExport.append("ImageMeta_" + ota)
    775                 self.tablesToExport.append("Detection_" + ota)
    776                 self.tablesToExport.append("SkinnyObject_" + ota)
    777                 #self.tablesToExport.append("ObjectCalColor_" + ota)
    778                 self.tablesToExport.append("DetectionCalib_" + ota)
    779                 tables.append("Detection_" + ota)
    780            
    781                 otaCount = otaCount + 1
    782                 #self.logger.info("end of ota")
     888                if self.populatePspsTablesChip(ota, x, y, results, tables): otaCount = otaCount + 1
     889
     890        if self.populatePspsTablesChip("Chip", 0, 0, results, tables): otaCount = otaCount + 1
     891
    783892        # print totals
    784893        self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+---------------+")
    785894        self.logger.info("| Total | %13d | %13d | %13d | %13d | %13d | %13d |",
    786                 totalOriginal,
    787                 totalSatDet,
    788                 totalNulIInstFlux,
    789                 totalNullPeakFlux,
    790                 totalNullObjID,
    791                 totalDetections)
     895                self.totalOriginal,
     896                self.totalSatDet,
     897                self.totalNulIInstFlux,
     898                self.totalNullPeakFlux,
     899                self.totalNullObjID,
     900                self.totalDetections)
    792901        self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+---------------+")
    793902
     
    830939    def importIppTables(self, filter=""):
    831940
    832        if self.config.test: regex = "XY33.psf"
    833        else : regex = ".*.psf"
     941       ## if self.config.test: regex = "XY33.psf"
     942       ## else : regex = ".*.psf"
     943       regex = ".*.psf"
    834944 
     945       # XXX EAM NOTE : this is fragile : requires PS1_V4
    835946       columns = "IPP_IDET X_PSF Y_PSF X_PSF_SIG Y_PSF_SIG PSF_INST_MAG PSF_INST_MAG_SIG PEAK_FLUX_AS_MAG PSF_MAJOR PSF_MINOR PSF_THETA EXT_NSIGMA PSF_QF MOMENTS_XX MOMENTS_XY MOMENTS_YY AP_MAG KRON_FLUX KRON_FLUX_ERR FLAGS FLAGS2 SKY SKY_SIGMA EXT_NSIGMA PSF_QF_PERFECT PSF_CHISQ"
    836947
  • trunk/ippToPsps/jython/dvo.py

    r34107 r35097  
    3333
    3434    '''
    35     def __init__(self, logger, config, scratchDbName="ipptopsps_scratch"):
     35    def __init__(self, logger, config, skychunk, ippToPspsDb, scratchDbName=None):
    3636
    3737        # set up logging
    3838        self.logger = logger
    3939        self.config = config
     40        self.skychunk = skychunk
     41        self.ippToPspsDb = ippToPspsDb
    4042
    4143        # set up empty lists
     
    4648        self.regionsIngestedButOutOfDate = []
    4749       
    48         # connect to the specified scratch database
     50        # connect to the specified scratch database, if a name is given, otherwise use the first version
    4951        try:
    50             self.scratchDb = ScratchDb(self.logger, self.config, scratchDbName)
     52            self.scratchDb = ScratchDb(self.logger, self.config, '1', scratchDbName)
    5153        except: raise
    5254
     55        # we have (still) 3 modes of ingest from dvo cpt/cps/cpm files
     56        # 1) dvograbber (useFullTables == FALSE),
     57        # 2) jython/stilts (useStilts == TRUE, useFullTables == TRUE)
     58        # 3) dvopsps (useStilts == FALSE, useFullTables == TRUE)
     59        # my goal (EAM, 2013/01/31) is to migrate to only dvopsps
     60
     61        self.useStilts = 0
    5362        self.scratchDb.setUseFullTables(True)
    5463
    5564        # decide if we are using the right DVO for this scratchDb
    56         self.correctDvo = self.scratchDb.isCorrectDvo(self.config.dvoLocation)
     65        self.correctDvo = self.scratchDb.isCorrectDvo(self.skychunk.dvoLocation)
    5766
    5867        # this scratch Db either has no DVO info ingested, or a different DVO ingested. Prompt user
    5968        if not self.correctDvo:
    6069            print "*******************************************************************************"
    61             self.logger.warning("Wrong or no DVO in use. Do you want to reset and use '" + self.config.dvoLocation + "'?")
     70            self.logger.warning("Wrong or no DVO in use. Do you want to reset and use '" + self.skychunk.dvoLocation + "'?")
    6271            response = raw_input("(y/n) ")
    6372            if response == "y":
     
    101110
    102111        # check if we have up-to-date version
    103         path = self.config.dvoLocation + "/Photcodes.dat"
     112        path = self.skychunk.dvoLocation + "/Photcodes.dat"
    104113        if self.scratchDb.alreadyImportedThisDvoTable(path):
    105114            self.logger.debugPair("DVO Photcodes.dat file", "up-to-date")
     
    126135
    127136        # check if we have up-to-date version
    128         path = self.config.dvoLocation + "/Images.dat"
     137        path = self.skychunk.dvoLocation + "/Images.dat"
    129138        if self.scratchDb.alreadyImportedThisDvoTable(path):
    130139            self.logger.debugPair("DVO Images.dat file", "up-to-date")
     
    151160        if not self.correctDvo: return False
    152161
    153         path =  self.config.dvoLocation + "/SkyTable.fits"
     162        path =  self.skychunk.dvoLocation + "/SkyTable.fits"
    154163        if self.scratchDb.alreadyImportedThisDvoTable(path):
    155164            self.logger.debugPair("DVO SkyTable.fits file", "up-to-date")       
     
    158167        self.logger.infoSeparator()
    159168        self.logger.infoPair("DVO SkyTable.fits file", "NOT up-to-date")       
    160         self.importFits(
     169
     170        if self.useStilts:
     171            self.importFits(
    161172                path,
    162173                "R_MIN R_MAX D_MIN D_MAX INDEX NAME",
    163174                self.scratchDb.dvoSkyTable)
     175        else:
     176           
     177            # create dvoSkyTable
     178            sql = "drop TABLE dvoSkyTable"
     179            try:
     180                self.scratchDb.execute(sql)
     181            except: pass
     182
     183            # create dvoSkyTable
     184            sql = "CREATE TABLE dvoSkyTable (R_MIN REAL, R_MAX REAL, D_MIN REAL, D_MAX REAL, INDEX_ INT, NAME CHAR(18))"
     185            self.scratchDb.execute(sql)
     186
     187            # TODO path to DVO prog hardcoded temporarily
     188            cmd = "dvopsps skytable"
     189            cmd += " -dbhost " + self.scratchDb.dbHost
     190            cmd += " -dbname " + self.scratchDb.dbName
     191            cmd += " -dbuser " + self.scratchDb.dbUser
     192            cmd += " -dbpass " + self.scratchDb.dbPass
     193            cmd += " -D CATDIR " + self.skychunk.dvoLocation
     194
     195            self.logger.infoPair("Running dvopsps", cmd)
     196            p = Popen(cmd, shell=True, stdout=PIPE)
     197            p.wait()
    164198
    165199        self.logger.infoPair("Adding index to", self.scratchDb.dvoSkyTable)
     
    168202       
    169203        self.scratchDb.setImportedThisDvoTable(path)
    170         self.logger.infoPair("Finished importing SkyTable at", self.config.dvoLocation)
     204        self.logger.infoPair("Finished importing SkyTable at", self.skychunk.dvoLocation)
    171205
    172206        return True
     
    231265           paths = []
    232266           for fileType in self.ingestFileTypes:
    233                paths.append(self.config.dvoLocation + "/" + regionPath + "." + fileType)
     267               paths.append(self.skychunk.dvoLocation + "/" + regionPath + "." + fileType)
    234268
    235269           # check for the existence of all interested file types
     
    304338        # go no further if we've already partly ingested a different DVO
    305339        if not self.correctDvo:
    306             self.logger.infoPair("Wrong DVO in use", self.config.dvoLocation)
     340            self.logger.infoPair("Wrong DVO in use", self.skychunk.dvoLocation)
    307341            return
    308342
     
    387421        size = 0.0
    388422        for region in regions:
    389 
     423             self.logger.infoPair("sizes for region", region)
    390424             # get combined size of all interested files
    391425             for fileType in self.ingestFileTypes:
    392                  size = size + self.getDiskSize(self.config.dvoLocation + "/" + region + "." + fileType)
     426                 size = size + self.getDiskSize(self.skychunk.dvoLocation + "/" + region + "." + fileType)
     427                 # EAM TEST I/O
     428                 self.logger.infoPair(fileType, size)
    393429
    394430        return size
     
    519555          try:
    520556              if attempts > 0: self.logger.infoPair("Attempt %d to write" % attempts, table.name)
    521               table.cmd_keepcols("CODE NAME TYPE_AS_INT").write(self.scratchDb.url + '#' + tableName)
     557              table.cmd_keepcols("CODE NAME TYPE_AS_INT C_LAM K").write(self.scratchDb.url + '#' + tableName)
    522558              break
    523559          except:
     
    532568      return tableName
    533569
     570
     571    '''
     572    ingest skyregion into MySQL database using the native DVO program dvopsps
     573    Populates dvoDetections and dvoDone with FITS tables from DVO for the defined sky area, this
     574    includes purging detections outside sky area
     575    '''
     576    def nativeIngestDetections(self, boxId, raCenter, decCenter, boxSize):
     577
     578        # XXX put the chunk below in a separate method
     579        # blow away existing dvoDetection table
     580
     581        # clear the 'ingested' field for all boxes
     582        self.ippToPspsDb.clearIngestedBoxes()
     583       
     584        # drop detections table
     585        self.logger.infoPair("Dropping table", self.scratchDb.dvoDetectionTable)
     586        self.scratchDb.dropTable(self.scratchDb.dvoDetectionTable)
     587       
     588        # create detections table
     589        self.logger.infoPair("Creating table", self.scratchDb.dvoDetectionTable)
     590        sql = "CREATE TABLE " + self.scratchDb.dvoDetectionTable + " LIKE dvoDetection"
     591        try: self.scratchDb.execute(sql)
     592        except:
     593            self.logger.errorPair("Unable to create table", self.scratchDb.dvoDetectionTable)
     594            return False
     595        self.scratchDb.changeEngineToInnoDB(self.scratchDb.dvoDetectionTable)
     596       
     597        # add fileID column
     598        sql = "ALTER TABLE " + self.scratchDb.dvoDetectionTable + " ADD fileID INT NOT NULL"
     599        try: self.scratchDb.execute(sql)
     600        except:
     601            self.logger.errorPair("Unable to add fileID column to ", self.scratchDb.dvoDetectionTable)
     602            return False
     603
     604        # add an index to the fileID column
     605        self.scratchDb.createIndex(self.scratchDb.dvoDetectionTable, "fileID")
     606
     607        # make sure we have an up-to-date Images table
     608        self.loadImages()
     609
     610        # dvopsps -D catdir CATDIR -region .... -dbhost xx -dbname xx -dbuser xx -dbpass xx
     611        halfSize = boxSize / 2.0
     612        # -region raCenter-halfSize raCenter+halfSize decCenter-halfSize decCenter+halfSize
     613
     614        # TODO path to DVO prog hardcoded temporarily
     615        cmd = "dvopsps detections"
     616        cmd += " -dbhost " + self.scratchDb.dbHost
     617        cmd += " -dbname " + self.scratchDb.dbName
     618        cmd += " -dbuser " + self.scratchDb.dbUser
     619        cmd += " -dbpass " + self.scratchDb.dbPass
     620        cmd += " -D CATDIR " + self.skychunk.dvoLocation
     621        cmd += " -region "
     622        cmd += " " + str(raCenter-halfSize)
     623        cmd += " " + str(raCenter+halfSize)
     624        cmd += " " + str(decCenter-halfSize)
     625        cmd += " " + str(decCenter+halfSize)
     626
     627        if self.skychunk.parallel:
     628            cmd += " -parallel"
     629
     630        self.logger.infoPair("Running dvopsps", cmd)
     631        p = Popen(cmd, shell=True, stdout=PIPE)
     632        p.wait()
     633
     634        self.ippToPspsDb.setIngestedBox(boxId)
     635
     636        # add fileID column
     637        sql = "ANALYZE TABLE " + self.scratchDb.dvoDetectionTable
     638        try: self.scratchDb.execute(sql)
     639        except:
     640            self.logger.errorPair("Unable to analyze mysql table", self.scratchDb.dvoDetectionTable)
     641            return False
     642
     643        # update lists after attempted sync
     644        # self.printSummary()
     645
     646        return True
  • trunk/ippToPsps/jython/dvodetections.py

    r34630 r35097  
    2020    Constructor
    2121    '''
    22     def __init__(self, logger, config, scratchDbName):
     22    def __init__(self, logger, config, skychunk, ippToPspsDb, scratchDbName):
    2323
    24         super(DvoDetections, self).__init__(logger, config, scratchDbName)
     24        super(DvoDetections, self).__init__(logger, config, skychunk, ippToPspsDb, scratchDbName)
    2525
    2626        # declare DVO file types of interest
     
    3232    def ingestRegion(self, region):
    3333
    34        cpmPath = self.config.dvoLocation + "/" + region + ".cpm"
    35        cptPath = self.config.dvoLocation + "/" + region + ".cpt"
     34       cpmPath = self.skychunk.dvoLocation + "/" + region + ".cpm"
     35       cptPath = self.skychunk.dvoLocation + "/" + region + ".cpt"
    3636
    3737       cpmTableName = self.scratchDb.getDbFriendlyTableName(region + ".cpm")
     
    8383       # first try to add the new columns. catch failure and continue
    8484       try:
    85            sql = "ALTER TABLE " + cpmTableName + " ADD COLUMN (PSPS_OBJ_ID BIGINT), (ZP REAL), (RA FLOAT), (DEC FLOAT)"
     85           sql = "ALTER TABLE " + cpmTableName + " ADD COLUMN (PSPS_OBJ_ID BIGINT), ADD COLUMN (ZP REAL), ADD COLUMN (RA FLOAT), ADD COLUMN (DEC_ FLOAT)"
    8686           self.scratchDb.execute(sql)
    8787       except:
    88            self.logger.infoPair("Already added PSPS_OBJ_ID column to", cpmTableName)
     88           # failed, but may be due to mysql error
     89           self.logger.infoPair("mysql error or already added PSPS_OBJ_ID column to", cpmTableName)
     90           # self.logger.infoPair("sql command", sql)
    8991               
    9092       # shove PSPS objIDs from cpt table and the calibrated zero point and coordinates which are formed
    9193       # by combining values from multiple tables into cpt table
    92        sql = "UPDATE " + cpmTableName + " AS a, " + cptTableName + " AS b, " \
    93               + self.scratchDb.dvoPhotcodesTable + " AS c \
    94               SET a.PSPS_OBJ_ID = b.EXT_ID, \
    95               b.ZP  = c.C_LAM * 0.001 + c.K * (b.AIRMASS - 1) - b.M_CAL, \
    96               b.RA  = a.RA  - (b.D_RA  / 3600.0), \
    97               b.DEC = a.DEC - (b.D_DEC / 3600.0) \
    98               WHERE a.CAT_ID = b.CAT_ID \
    99               AND a.OBJ_ID = b.OBJ_ID   \
    100               AND b.PHOTCODE = c.CODE"
     94       sql = "UPDATE " \
     95              + cpmTableName + " AS meas, " \
     96              + cptTableName + " AS ave, " \
     97              + self.scratchDb.dvoPhotcodesTable + " AS phot \
     98              SET \
     99              meas.PSPS_OBJ_ID = ave.EXT_ID, \
     100              meas.ZP  = phot.C_LAM * 0.001 + phot.K * (meas.AIRMASS - 1) - meas.M_CAL, \
     101              meas.RA  = ave.RA  - (meas.D_RA  / 3600.0), \
     102              meas.DEC_ = ave.DEC_ - (meas.D_DEC / 3600.0) \
     103              WHERE meas.CAT_ID = ave.CAT_ID \
     104              AND meas.OBJ_ID = ave.OBJ_ID   \
     105              AND meas.PHOTCODE = phot.CODE"
    101106
     107       # EAM : add some debug I/O
     108       # self.logger.infoPair("sql command", sql)
    102109       self.scratchDb.execute(sql)
    103110
     
    136143              ,POW(10.0, 0.4 * M_TIME)  \
    137144              ,RA   \
    138               ,DEC  \
     145              ,DEC_  \
    139146              ,X_CCD_ERR*PLTSCALE   \
    140147              ,Y_CCD_ERR*PLTSCALE   \
    141148              , " + str(fileId) + " \
    142149              FROM " + cpmTableName
     150
     151       # print "sql :", sql
     152       # response = raw_input("prepare to insert dvoDetectionTable ")
    143153
    144154       try:
     
    148158           return False
    149159       finally:
     160           # response = raw_input("insert dvoDetectionTable ")
    150161           self.logger.infoPair("Dropping tables", "%s and %s" % (cpmTableName, cptTableName))
    151162           self.scratchDb.dropTable(cpmTableName)
     
    155166
    156167       return True
    157 
    158 
  • trunk/ippToPsps/jython/dvoobjects.py

    r33675 r35097  
    88import logging
    99import glob
     10from subprocess import call, PIPE, Popen
    1011
    1112from dvo import Dvo
    12 
    1313
    1414'''
     
    2020    Constructor
    2121    '''
    22     def __init__(self, logger, config, scratchDbName=None):
     22    def __init__(self, logger, config, skychunk, ippToPspsDb, scratchDbName=None):
    2323
    24         super(DvoObjects, self).__init__(logger, config, scratchDbName)
     24        super(DvoObjects, self).__init__(logger, config, skychunk, ippToPspsDb, scratchDbName)
    2525
    2626        # declare DVO file types of interest
     
    3737       for fileType in self.ingestFileTypes:
    3838
    39            path = self.config.dvoLocation + "/" + region + "." + fileType
     39           path = self.skychunk.dvoLocation + "/" + region + "." + fileType
    4040           tableName = self.scratchDb.getDbFriendlyTableName(region + "." + fileType)
    4141
     
    4747
    4848
     49    '''
     50    ingest object data into MySQL database using the native DVO program dvopsps
     51    Populates dvoDetections and dvoDone with FITS tables from DVO for the defined sky area, this
     52    includes purging detections outside sky area
     53    '''
     54    def nativeIngestRegion(self, region):
     55
     56        # drop cpt/cps/object table?
     57        # create detections table?
     58
     59        # TODO path to DVO prog hardcoded temporarily
     60        cmd = "dvopsps objects"
     61        cmd += " -dbhost " + self.scratchDb.dbHost
     62        cmd += " -dbname " + self.scratchDb.dbName
     63        cmd += " -dbuser " + self.scratchDb.dbUser
     64        cmd += " -dbpass " + self.scratchDb.dbPass
     65        cmd += " -D CATDIR " + self.skychunk.dvoLocation
     66        cmd += " -cpt " + region
     67
     68        if self.skychunk.parallel:
     69            cmd += " -parallel"
     70
     71        self.logger.infoPair("Running dvopsps", cmd)
     72        p = Popen(cmd, shell=True, stdout=PIPE)
     73        p.wait()
     74
     75        # update lists after attempted sync
     76        # self.printSummary()
     77
     78        return True
  • trunk/ippToPsps/jython/fits.py

    r33259 r35097  
    137137
    138138            # this regex will get param/value pairs for all header cards, ignoring comments and parsing out 'HIERACH' prefixes
    139             match = re.match('^(HIERARCH )*([a-zA-Z0-9-_\.]+)\s*=\s+\'*([a-zA-Z0-9-_\.:\s@#]+)\'*\\/*', record)
     139            match = re.match('^(HIERARCH )*([a-zA-Z0-9-_\.]+)\s*=\s+\'*([a-zA-Z0-9-+_\.:\s@#]+)\'*\\/*', record)
    140140            if match:
    141141
  • trunk/ippToPsps/jython/gpc1db.py

    r34884 r35097  
    2121    '''
    2222    def __init__(self, logger, config):
    23         super(Gpc1Db, self).__init__(logger, config, "gpc1database")
     23        # define database type
     24        if (config.test):
     25            dbType = "gpc1database_test"
     26        else:
     27            dbType = "gpc1database"
     28
     29        super(Gpc1Db, self).__init__(logger, config, dbType)
    2430
    2531    '''
     
    9399           
    94100        try:
     101            # XXX EAM : test output
     102            self.logger.infoPair("sql for dvo items:", sql)
    95103            rs = self.executeQuery(sql)
    96104            while (rs.next()):
     
    112120        self.logger.debug("Querying GPC1 for image IDs for stack ID: " + str(stackID))
    113121
     122        # JOIN stackInputSkyfile shoule use stack_id as well as warp_id, right? (maybe not -- the join to warp is first)
    114123        sql = "SELECT DISTINCT CONCAT(exp_id, SUBSTR(class_id, 3, 4)) FROM ( \
    115124               SELECT DISTINCT exp_id,class_id \
     
    226235        if path.startswith("neb"):
    227236
     237            # XXX EAM : this should just use the name (path.smf) instead of a wildcard, right?
    228238            f=os.popen("neb-ls -p "+path+"%smf")
    229239            for i in f.readlines():
     
    234244            files = glob.glob(path + ".smf")
    235245
     246        # XXX EAM : test output
     247        self.logger.infoPair("smf files:", files)
    236248        if len(files) < 1: return None
    237249
     
    290302
    291303
     304        # print "staring stack stage cmf"
     305
    292306        # get single path base for the directory containing all cmf files, one of which is hopefully for our stack_id
    293307        try:
    294308            rs = self.executeQuery(sql)
    295309            rs.first()
     310        except:
     311            self.logger.errorPair("Can't query for stack cmfs", "stack_id = %d" % stackID)
     312            return None
     313
     314        try:
    296315            pathBase = rs.getString(1)
     316        except:
     317            self.logger.errorPair("No stack cmf files found for stack_id = %d" % stackID)
     318            return None
     319
     320        # find the files (are they in nebulous or in the filesystem?)
     321        files = []
     322        if pathBase.startswith("neb"):
     323            # XXX EAM : this should just use the name (path.smf) instead of a wildcard, right?
     324            f=os.popen("neb-ls -p " + pathBase + "%cmf")
     325            for i in f.readlines():
     326                files.append(i.rstrip())
     327
     328        # or not a neb path
     329        else:
     330            files = glob.glob(pathBase + ".cmf")
     331
     332        # print "stack cmf files:", files
     333        if len(files) < 1: return None
     334
     335        # if we get here, then the cmf is readable, now check the stack_id
     336        fits = Fits(self.logger, self.config, files[0])
     337        return fits
     338
     339        # XXX validate the file?
     340        # if fits.getPrimaryHeaderValue("STK_ID") == str(stackID):
    297341
    298342            # now find and loop through all cmf files at this path_base
    299             files=os.popen("neb-ls " + pathBase + "%cmf")
    300             for i in files.readlines():
    301 
    302                 nebPath = i.rstrip()
    303 
    304                 # now attempt to run 'neb-ls -p' to actually read this cmf file
    305                 try:
    306                     self.logger.debug("Trying to neb-ls -p on '" + nebPath + "'")
    307                     paths=os.popen("neb-ls -p " + nebPath)
    308                     path = paths.readline().rstrip()
    309                     if len(path) < 1:
    310                        self.logger.debug("zero length path - skipping")
    311                        raise
    312 
    313                     # if we get here, then the cmf is readable, now check the stack_id
    314                     fits = Fits(self.logger, self.config, path)
    315                     if fits.getPrimaryHeaderValue("STK_ID") == str(stackID):
    316                         # we have the right file!
    317                         self.logger.debug("SUCCESS!: %s == %s"% (fits.getPrimaryHeaderValue("STK_ID"), str(stackID)))
    318                         return fits
    319                     else:
    320                         # this is not the correct file
    321                         self.logger.debug("STACK ID: %s != %s"% (fits.getPrimaryHeaderValue("STK_ID"), str(stackID)))
    322 
    323                 # an exception here means that nebulous could not read this file, so we just skip it
    324                 except:
    325                     self.logger.debug("NEB FAILED SKIPPING")
    326                     pass
    327 
    328         except:
    329             self.logger.errorPair("Can't query for stack cmfs", "stack_id = %d" % stackID)
    330 
    331         self.logger.errorPair("Couldn't find stack cmf for", "stack_id = %d" % stackID)
    332         return None
     343
     344            ## XXX the code below was needed when we ingested from staticsky (N files per run)
     345            ## XXX ingesting from skycal solves this problem (1 file per run)
     346            ## files=os.popen("neb-ls " + pathBase + "%cmf")
     347            ## for i in files.readlines():
     348            ##     nebPath = i.rstrip()
     349            ##
     350            ##     # now attempt to run 'neb-ls -p' to actually read this cmf file
     351            ##     try:
     352            ##         self.logger.debug("Trying to neb-ls -p on '" + nebPath + "'")
     353            ##         paths=os.popen("neb-ls -p " + nebPath)
     354            ##         path = paths.readline().rstrip()
     355            ##         if len(path) < 1:
     356            ##            self.logger.debug("zero length path - skipping")
     357            ##            raise
     358            ##
     359            ##         print "starint stack stage cmf 3"
     360            ##
     361            ##         # if we get here, then the cmf is readable, now check the stack_id
     362            ##         fits = Fits(self.logger, self.config, path)
     363            ##         if fits.getPrimaryHeaderValue("STK_ID") == str(stackID):
     364            ##             # we have the right file!
     365            ##             self.logger.debug("SUCCESS!: %s == %s"% (fits.getPrimaryHeaderValue("STK_ID"), str(stackID)))
     366            ##             return fits
     367            ##         else:
     368            ##             # this is not the correct file
     369            ##             self.logger.debug("STACK ID: %s != %s"% (fits.getPrimaryHeaderValue("STK_ID"), str(stackID)))
     370            ##
     371            ##     # an exception here means that nebulous could not read this file, so we just skip it
     372            ##     except:
     373            ##         self.logger.debug("NEB FAILED SKIPPING")
     374            ##         pass
    333375
    334376    '''
  • trunk/ippToPsps/jython/initbatch.py

    r33727 r35097  
    2828            logger,
    2929            config,
     30            skychunk,
    3031            gpc1Db,
    3132            ippToPspsDb,
     
    3435       super(InitBatch, self).__init__(logger,
    3536               config,
     37               skychunk,
    3638               gpc1Db,
    3739               ippToPspsDb,
  • trunk/ippToPsps/jython/ipptopsps.py

    r33790 r35097  
    11#!/usr/bin/env jython
     2# EAM : config -> skychunk DONE
    23
    34import signal
     
    910
    1011from config import Config
     12from skychunk import Skychunk
    1113from pslogger import PSLogger
    1214from ipptopspsdb import IppToPspsDb
     
    2325    def __init__(self, argv, logToStdout=1, logToFile=0):
    2426
    25         # are the arsg ok? all programs require a config name
     27        # set up config object (global config information, also parse command-line options, eg -test / -t)
     28        self.config = Config()
     29
     30        # are the args ok? all programs require a config name
    2631        if len(sys.argv) < 2:
    2732            self.printUsage()
    2833            self.exitProgram("Wrong args")
    29            
     34
    3035        # some class constants
    31         self.PROGNAME = sys.argv[0]
    32         CONFIGNAME = sys.argv[1]
    3336        self.HOST = socket.gethostname()
    3437        self.PID = os.getpid()
     
    3841        self.SECONDS = None
    3942
    40         self.createNewConfig = False
    41         self.rotateConfigs = False
    42         # a new config?
    43         if CONFIGNAME == "edit": self.createNewConfig = True
    44         # should we rotate configs for this program?
    45         elif CONFIGNAME == "all": self.rotateConfigs = True
     43        self.logger = self.config.getLogger(self.HOST, self.PID, logToStdout, logToFile)
    4644
    47         # set up config object
    48         self.config = Config(self.PROGNAME, CONFIGNAME)
    49         self.logger = self.config.getLogger(self.HOST, self.PID, logToStdout, logToFile)
     45        # argv[1] -> self.skychunk.name
     46        self.skychunk = Skychunk(self.logger)
    5047
    5148        # create connection to databases database
    5249        try:
    53             self.ippToPspsDb = IppToPspsDb(self.logger, self.config)
     50            self.ippToPspsDb = IppToPspsDb(self.logger, self.config, self.skychunk)
    5451        except:
    5552            self.exitProgram("Could not connect to ipptopsps Db")
     
    6360        # title for log
    6461        self.logger.infoSeparator()
    65         self.logger.infoTitle("ippToPsps '" + self.PROGNAME + "' started")
     62        self.logger.infoTitle("ippToPsps '" + self.config.programName + "' started")
    6663        self.logger.infoPair("Host", self.HOST)
    6764        self.logger.infoPair("PID", "%d" % self.PID)
    68         self.logger.infoPair("Config", self.config.name)
     65        self.logger.infoPair("Skychunk", self.skychunk.name)
    6966
    7067    '''
     
    104101
    105102        # write message to log or stdout if no logger set up
    106         msg = sys.argv[0] + " <configName|all|edit> " + extra
     103        msg = sys.argv[0] + " <skychunkName|all|edit> " + extra
    107104        try:
    108105            self.logger.errorPair("Usage:", msg)
     
    111108
    112109    '''
    113     Refreshes the config then recreates objects with new settings
     110    Refreshes the skychunk then recreates objects with new settings
    114111    '''
    115     def refreshConfig(self):
     112    def refreshSkychunk(self):
    116113
    117         # new config?
    118         if self.createNewConfig:
    119             self.ippToPspsDb.editConfig()
    120             self.ippToPspsDb.setConfigForThisClient(self.config.name, self.HOST, self.PID)
    121             self.createNewConfig = False
     114        # new skychunk?
     115        if self.skychunk.createNewSkychunk:
     116            self.ippToPspsDb.editSkychunk()
     117            self.ippToPspsDb.setSkychunkForThisClient(self.skychunk.name, self.HOST, self.PID)
     118            self.skychunk.createNewSkychunk = False
    122119
    123         # if we are rotating configs, then look for next active one in list
    124         if self.rotateConfigs:
    125             self.ippToPspsDb.getConfigForThisClient(self.HOST, self.PID)
    126             configs = self.ippToPspsDb.getActiveConfigList()
     120        # if we are rotating skychunks, then look for next active one in list
     121        if self.skychunk.rotateSkychunks:
     122            self.ippToPspsDb.getSkychunkForThisClient(self.HOST, self.PID)
     123            skychunks = self.ippToPspsDb.getActiveSkychunkList()
    127124             
    128125            i = 1
    129             for config in configs:
    130                if config == self.config.name: break
     126            for skychunk in skychunks:
     127               if skychunk == self.skychunk.name: break
    131128               i += 1
    132129
    133             if i >= len(configs): newConfig = configs[0]
    134             else: newConfig = configs[i]
     130            if i >= len(skychunks): newSkychunk = skychunks[0]
     131            else: newSkychunk = skychunks[i]
    135132
    136             self.ippToPspsDb.setConfigForThisClient(newConfig, self.HOST, self.PID)
     133            self.ippToPspsDb.setSkychunkForThisClient(newSkychunk, self.HOST, self.PID)
    137134
    138         return self.ippToPspsDb.readConfig(self.HOST, self.PID)
     135        return self.ippToPspsDb.readSkychunk(self.HOST, self.PID)
    139136
    140137    '''
    141     All implementing subclasses (programs) should call this method once in a while to see if it should be paused or killed, otherwise this updates the clients table with current time and reloads the config data
     138    All implementing subclasses (programs) should call this method once in a while to see if it should be paused or killed, otherwise this updates the clients table with current time and reloads the skychunk data
    142139    '''
    143140    def checkClientStatus(self):
    144141
    145         self.ippToPspsDb.updateClient(self.PROGNAME, self.HOST, self.PID)
     142        self.ippToPspsDb.updateClient(self.config.programName, self.HOST, self.PID)
    146143
    147144        if self.ippToPspsDb.isKilled(self.HOST, self.PID):
    148145            self.exitProgram("killed via Db")
    149146       
    150         # this loop pauses the process if we have no config or we have set it to pause
     147        # this loop pauses the process if we have no skychunk or we have set it to pause
    151148        firstTimeIn = True
    152         while not self.refreshConfig() or self.ippToPspsDb.isPaused(self.HOST, self.PID):
     149        while not self.refreshSkychunk() or self.ippToPspsDb.isPaused(self.HOST, self.PID):
    153150
    154             self.ippToPspsDb.updateClient(self.PROGNAME, self.HOST, self.PID)
     151            self.ippToPspsDb.updateClient(self.config.programName, self.HOST, self.PID)
    155152            if self.ippToPspsDb.isKilled(self.HOST, self.PID):
    156153                self.exitProgram("killed while paused")
     
    175172        # write message to log or stdout if no logger set up
    176173        try:
    177             self.logger.infoPair(self.PROGNAME + " exited", exitReason)
     174            self.logger.infoPair(self.config.programName + " exited", exitReason)
    178175        except:
    179176            print "*** Program exited: " + exitReason
     
    186183
    187184        sys.exit(0)
    188    
    189 
  • trunk/ippToPsps/jython/ipptopspsdb.py

    r34661 r35097  
    1717    Constructor
    1818    '''
    19     def __init__(self, logger, config):
    20         super(IppToPspsDb, self).__init__(logger, config, "ipptopspsdatabase")
     19    def __init__(self, logger, config, skychunk):
     20        if (config.test):
     21            dbType = "ipptopspsdatabase_test"
     22        else:
     23            dbType = "ipptopspsdatabase"
     24        super(IppToPspsDb, self).__init__(logger, config, dbType)
     25
     26        self.skychunk = skychunk
    2127
    2228        self.MAX_FAILS = 5
     
    2935        sql = "SELECT DISTINCT batch_id \
    3036               FROM batch \
    31                WHERE timestamp > '" + self.config.epoch + "' \
     37               WHERE timestamp > '" + self.skychunk.epoch + "' \
    3238               AND batch_type = '" + batchType + "' \
    33                AND dvo_db = '" + self.config.dvoLabel + "' \
     39               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    3440               AND merged = 1 \
    3541               AND " + column + " = 0"
     
    5460        sql = "SELECT DISTINCT batch_id \
    5561               FROM batch \
    56                WHERE timestamp > '" + self.config.epoch + "' \
     62               WHERE timestamp > '" + self.skychunk.epoch + "' \
    5763               AND batch_type = '" + batchType + "' \
    58                AND dvo_db = '" + self.config.dvoLabel + "' \
     64               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    5965               AND purged = 1 \
    6066               AND " + column + " = 0"
     
    8086        sql = "SELECT DISTINCT batch_id \
    8187               FROM batch \
    82                WHERE timestamp > '" + self.config.epoch + "' \
     88               WHERE timestamp > '" + self.skychunk.epoch + "' \
    8389               AND batch_type = '" + batchType + "' \
    84                AND dvo_db = '" + self.config.dvoLabel + "' \
     90               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    8591               AND (loaded_to_ODM = -1 OR merge_worthy = 1) \
    8692               AND " + column + " = 0"
     
    148154        sql = "SELECT DISTINCT batch_id \
    149155               FROM batch \
    150                WHERE timestamp > '" + self.config.epoch + "' \
     156               WHERE timestamp > '" + self.skychunk.epoch + "' \
    151157               AND batch_type = '" + batchType + "' \
    152                AND dvo_db = '" + self.config.dvoLabel + "' \
     158               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    153159               AND processed = 1\
    154160               AND loaded_to_datastore != 1 \
     
    177183        sql = "SELECT batch_id \
    178184               FROM batch \
    179                WHERE timestamp > '" + self.config.epoch + "' \
    180                AND dvo_db = '" + self.config.dvoLabel + "' \
     185               WHERE timestamp > '" + self.skychunk.epoch + "' \
     186               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    181187               AND loaded_to_datastore = 1 \
    182188               AND batch_type = '" + batchType + "' \
     
    206212        sql = "SELECT batch_id \
    207213               FROM batch \
    208                WHERE timestamp > '" + self.config.epoch + "' \
    209                AND dvo_db = '" + self.config.dvoLabel + "' \
     214               WHERE timestamp > '" + self.skychunk.epoch + "' \
     215               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    210216               AND loaded_to_datastore = 1 \
    211217               AND batch_type = '" + batchType + "' \
     
    235241        sql = "SELECT batch_id \
    236242               FROM batch \
    237                WHERE timestamp > '" + self.config.epoch + "' \
    238                AND dvo_db = '" + self.config.dvoLabel + "' \
     243               WHERE timestamp > '" + self.skychunk.epoch + "' \
     244               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    239245               AND merge_worthy = 1 \
    240246               AND batch_type = '" + batchType + "' \
     
    262268        sql = "SELECT DISTINCT batch_id \
    263269               FROM batch \
    264                WHERE timestamp > '" + self.config.epoch + "' \
    265                AND dvo_db = '" + self.config.dvoLabel + "' \
     270               WHERE timestamp > '" + self.skychunk.epoch + "' \
     271               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    266272               AND " + column + " = " + str(value)
    267273
     
    288294               FROM batch \
    289295               WHERE batch_type = '" + batchType + "' \
    290                AND timestamp > '" + self.config.epoch + "' \
    291                AND dvo_db = '" + self.config.dvoLabel + "' \
     296               AND timestamp > '" + self.skychunk.epoch + "' \
     297               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    292298               AND processed = 1 \
    293299               AND loaded_to_datastore = 1 \
     
    315321               FROM batch \
    316322               WHERE batch_type = '" + batchType + "' \
    317                AND timestamp > '" + self.config.epoch + "' \
    318                AND dvo_db = '" + self.config.dvoLabel + "' \
     323               AND timestamp > '" + self.skychunk.epoch + "' \
     324               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    319325               AND " + column + " = " + str(value)
    320326
     
    387393               WHERE batch_type = '" + batchType + "' \
    388394               AND processed = 1 \
    389                AND timestamp > '" + self.config.epoch + "' \
    390                AND dvo_db = '" + self.config.dvoLabel + "' \
     395               AND timestamp > '" + self.skychunk.epoch + "' \
     396               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    391397               AND timestamp BETWEEN now() - INTERVAL " + interval + " AND now()"
    392398
     
    412418               WHERE batch_type = '" + batchType + "' \
    413419               AND loaded_to_datastore = 1 \
    414                AND timestamp > '" + self.config.epoch + "' \
    415                AND dvo_db = '" + self.config.dvoLabel + "' \
     420               AND timestamp > '" + self.skychunk.epoch + "' \
     421               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    416422               ORDER BY timestamp DESC LIMIT 1"
    417423
     
    511517               WHERE stage_id = " + str(stage_id) + " \
    512518               AND batch_type = '" + batchType + "' \
    513                AND dvo_db = '" + self.config.dvoLabel + "' \
     519               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    514520               AND batch_type != 'IN' \
    515521               AND timestamp BETWEEN now() - INTERVAL 12 HOUR AND now()"
     
    554560               WHERE stage_id = " + str(stage_id) + " \
    555561               AND batch_type = '" + batchType + "' \
    556                AND timestamp > '" + self.config.epoch + "' \
    557                AND dvo_db = '" + self.config.dvoLabel + "' \
     562               AND timestamp > '" + self.skychunk.epoch + "' \
     563               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    558564               AND batch_type != 'IN' \
    559565               AND processed = 1"
     
    579585               WHERE stage_id = " + str(stage_id) + " \
    580586               AND batch_type = '" + batchType + "' \
    581                AND timestamp > '" + self.config.epoch + "' \
    582                AND dvo_db = '" + self.config.dvoLabel + "' \
     587               AND timestamp > '" + self.skychunk.epoch + "' \
     588               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    583589               AND processed = -1"
    584590
     
    602608               FROM batch \
    603609               WHERE batch_type = '" + batchType + "' \
    604                AND timestamp > '" + self.config.epoch + "' \
    605                AND dvo_db = '" + self.config.dvoLabel + "' \
     610               AND timestamp > '" + self.skychunk.epoch + "' \
     611               AND dvo_db = '" + self.skychunk.dvoLabel + "' \
    606612               AND processed = -1 \
    607613               GROUP BY stage_id HAVING numoccur >= " + str(self.MAX_FAILS)
     
    634640        batchID = -1;
    635641
    636         if self.config.force or \
     642        if self.skychunk.force or \
    637643            (not self.alreadyProcessed(batchType, stageID) \
    638644            and not self.processingNow(batchType, stageID) \
     
    650656                       '" + batchType + "', \
    651657                       " + str(stageID) + ", \
    652                        '" + self.config.survey + "', \
    653                        '" + self.config.dvoLabel + "', \
    654                        '" + self.config.datastoreProduct + "' \
     658                       '" + self.skychunk.survey + "', \
     659                       '" + self.skychunk.dvoLabel + "', \
     660                       '" + self.skychunk.datastoreProduct + "' \
    655661                       )"
    656662            self.logger.infoPair("heather:","sql")
     
    749755
    750756    '''
    751     Sets the config field for this client
    752     '''
    753     def setConfigForThisClient(self, config, host, pid):
    754 
    755         self.execute("UPDATE clients SET config = '" + config + "' \
     757    Sets the skychunk field for this client
     758    '''
     759    def setSkychunkForThisClient(self, skychunk, host, pid):
     760
     761        self.execute("UPDATE clients SET skychunk = '" + skychunk + "' \
    756762                WHERE host = '" + host + "' \
    757763                AND pid = " + str(pid))
    758     '''
    759     Sets the config field for a set of loader clients
    760     '''
    761     def setConfigForLoaders(self, config, ids):
     764
     765    '''
     766    Sets the skychunk field for a set of loader clients
     767    '''
     768    def setSkychunkForLoaders(self, skychunk, ids):
    762769
    763770        for id in ids:
    764             self.execute("UPDATE clients SET config = '" + config + "' \
     771            self.execute("UPDATE clients SET skychunk = '" + skychunk + "' \
    765772                    WHERE type = 'loader.py' \
    766773                    AND id = " + str(id))
     
    796803    '''
    797804    def insertClient(self, type, host, pid):
    798         self.execute("INSERT INTO clients (timestamp, type, host, pid, config) VALUES (now(), '" + type + "', '" + host + "', " + str(pid) + ", '" + self.config.name + "')")
     805        self.execute("INSERT INTO clients (timestamp, type, host, pid, skychunk) VALUES (now(), '" + type + "', '" + host + "', " + str(pid) + ", '" + self.skychunk.name + "')")
    799806
    800807    '''
     
    831838        try:
    832839            rs = self.executeQuery(sql)
    833             rs.first()
     840            if rs.first() is False:  return False
    834841            if rs.getInt(1) == 1: return True
    835842            else: return False
     
    840847
    841848    '''
    842     Returns a list of available configs
    843     '''
    844     def getActiveConfigList(self):
     849    Returns a list of available skychunks
     850    '''
     851    def getActiveSkychunkList(self):
    845852       
    846         sql = "SELECT DISTINCT name FROM config WHERE active = 1 ORDER BY name"
    847 
    848         configs = []
    849         try:
    850             rs = self.executeQuery(sql)
    851             while (rs.next()): configs.append(rs.getString(1))
    852         except:
    853             self.logger.errorPair("Can't get config names", sql)
     853        sql = "SELECT DISTINCT name FROM skychunk WHERE active = 1 ORDER BY name"
     854
     855        skychunks = []
     856        try:
     857            rs = self.executeQuery(sql)
     858            while (rs.next()): skychunks.append(rs.getString(1))
     859        except:
     860            self.logger.errorPair("Can't get skychunk names", sql)
    854861        finally:
    855862            rs.close()
    856863
    857         return configs
    858 
    859     '''
    860     Prompts user for info about a new or existing config and lets them neter the various details
    861     '''
    862     def editConfig(self):
     864        return skychunks
     865
     866    '''
     867    Prompts user for info about a new or existing skychunk and lets them neter the various details
     868    '''
     869    def editSkychunk(self):
    863870
    864871       print " ********************************************************************"
    865        print " *              Config editor"
     872       print " *              Skychunk editor"
    866873       print " *"
    867        response = raw_input(" * Name for new config, or existing config to edit? ")
     874       response = raw_input(" * Name for new skychunk, or existing skychunk to edit? ")
    868875       if response == "": return
    869        self.config.name = response
    870 
    871        # attempt to insert new config, if it already exists then carry on with update
    872        sql = "INSERT INTO config (name) VALUES ('" + self.config.name + "')"
     876       self.skychunk.name = response
     877
     878       # attempt to insert new skychunk, if it already exists then carry on with update
     879       sql = "INSERT INTO skychunk (name) VALUES ('" + self.skychunk.name + "')"
    873880       try:       
    874881           self.execute(sql)
    875882       except: pass
    876883
    877        # for each column in the config table
    878        sql = "SHOW COLUMNS FROM config"
     884       # for each column in the skychunk table
     885       sql = "SHOW COLUMNS FROM skychunk"
    879886       rs = self.executeQuery(sql)
    880887       while (rs.next()):
     
    887894           if field == 'timestamp': continue
    888895           if field == 'name': continue
     896           if field == 'ingested_det': continue
     897           if field == 'ingested_obj': continue
    889898
    890899           # get current value for this field, if any
    891900           try:
    892                rs2 = self.executeQuery("SELECT " + field + " FROM config WHERE name = '" + self.config.name + "'")
     901               rs2 = self.executeQuery("SELECT " + field + " FROM skychunk WHERE name = '" + self.skychunk.name + "'")
    893902               rs2.first()
    894903               default = rs2.getString(1)
     
    907916               if type.find("varchar") != -1 or type.find("timestamp") != -1: quotes = "'"
    908917               else: quotes = ""
    909                self.execute("UPDATE config SET " + field + " = " + quotes + response + quotes + " WHERE name = '" + self.config.name + "'")
     918               self.execute("UPDATE skychunk SET " + field + " = " + quotes + response + quotes + " WHERE name = '" + self.skychunk.name + "'")
    910919       
    911920       print " *"
     
    913922
    914923    '''
    915     Returns config for this client
    916     '''
    917     def getConfigForThisClient(self, host, pid):
    918 
    919         sql = "SELECT config \
     924    Returns skychunk for this client
     925    '''
     926    def getSkychunkForThisClient(self, host, pid):
     927
     928        sql = "SELECT skychunk \
    920929               FROM clients \
    921930               WHERE host = '" + host + "' \
     
    925934            rs = self.executeQuery(sql)
    926935            rs.first()
    927             self.config.name = rs.getString(1)
    928         except:
    929             self.logger.errorPair("No config set for", "%s (pid=%d)" % (host, pid))
    930             self.config.isLoaded = False
     936            self.skychunk.name = rs.getString(1)
     937        except:
     938            self.logger.errorPair("No skychunk set for", "%s (pid=%d)" % (host, pid))
     939            self.skychunk.isLoaded = False
    931940            return False
    932941
     
    934943
    935944    '''
    936     Reads config from the database and populates Config object
    937     '''
    938     def readConfig(self, host, pid):
    939 
    940         # first get config defined for this client
    941         if not self.getConfigForThisClient(host, pid): return False
    942 
    943         # now load that config
     945    Reads skychunk from the database and populates Skychunk object
     946    '''
     947    def readSkychunk(self, host, pid):
     948
     949        # first get skychunk defined for this client
     950        if not self.getSkychunkForThisClient(host, pid): return False
     951
     952        # now load that skychunk
    944953        sql = "SELECT \
    945954        datastore_product \
     
    964973        ,queue_ST \
    965974        ,queue_OB \
    966         FROM config \
    967         WHERE name = '" + self.config.name + "'"
    968 
    969         self.config.batchTypes = []
    970         try:
    971             rs = self.executeQuery(sql)
     975        ,parallel \
     976        FROM skychunk \
     977        WHERE name = '" + self.skychunk.name + "'"
     978
     979        self.skychunk.batchTypes = []
     980        try:
     981            rs = self.executeQuery(sql)
     982
    972983            rs.first()
    973             self.config.datastoreProduct = rs.getString(1)
    974             self.config.datastoreType = rs.getString(2)
    975             if rs.getInt(3) == 1: self.config.datastorePublishing = True
    976             else: self.config.datastorePublishing = False
    977             self.config.dvoLabel = rs.getString(4)
     984            self.skychunk.datastoreProduct = rs.getString(1)
     985            self.skychunk.datastoreType = rs.getString(2)
     986            if rs.getInt(3) == 1: self.skychunk.datastorePublishing = True
     987            else: self.skychunk.datastorePublishing = False
     988            self.skychunk.dvoLabel = rs.getString(4)
    978989
    979990            # if dvoLabel is null is can break queries, so set to something
    980             if not self.config.dvoLabel: self.config.dvoLabel = "none"
    981             self.config.dvoLocation = rs.getString(5)
    982             self.config.minRa = rs.getDouble(6)
    983             self.config.maxRa = rs.getDouble(7)
    984             self.config.minDec = rs.getDouble(8)
    985             self.config.maxDec = rs.getDouble(9)
    986 
    987             self.config.boxSize = rs.getDouble(10)
    988             self.config.halfBox = self.config.boxSize/2.0
    989             self.config.boxSizeWithBorder = self.config.boxSize + (self.config.BORDER * 2)
    990 
    991             self.config.basePath = rs.getString(11)
    992             self.config.dataRelease = rs.getInt(12)
    993             self.config.deleteLocal = rs.getInt(13)
    994             self.config.deleteDatastore = rs.getInt(14)
    995             self.config.deleteDxLayer = rs.getInt(15)
    996             self.config.epoch = rs.getString(16)
    997             self.config.survey = rs.getString(17)
    998             self.config.pspsSurvey = rs.getString(18)
    999             if rs.getInt(19) == 1: self.config.batchTypes.append("P2")
    1000             if rs.getInt(20) == 1: self.config.batchTypes.append("ST")
    1001             if rs.getInt(21) == 1: self.config.batchTypes.append("OB")
    1002             self.config.force = False # TODO
    1003             self.config.test = False # TODO
    1004             self.config.isLoaded = True
    1005         except:
    1006             self.logger.errorPair("Could not read config with name", self.config.name)
    1007             self.config.isLoaded = False
    1008 
    1009         return self.config.isLoaded
     991            if not self.skychunk.dvoLabel: self.skychunk.dvoLabel = "none"
     992            self.skychunk.dvoLocation = rs.getString(5)
     993            self.skychunk.minRa = rs.getDouble(6)
     994            self.skychunk.maxRa = rs.getDouble(7)
     995            self.skychunk.minDec = rs.getDouble(8)
     996            self.skychunk.maxDec = rs.getDouble(9)
     997
     998            self.skychunk.boxSize = rs.getDouble(10)
     999            self.skychunk.halfBox = self.skychunk.boxSize/2.0
     1000            self.skychunk.boxSizeWithBorder = self.skychunk.boxSize + (self.skychunk.BORDER * 2)
     1001
     1002            self.skychunk.basePath = rs.getString(11)
     1003            self.skychunk.dataRelease = rs.getInt(12)
     1004
     1005            self.skychunk.deleteLocal = rs.getInt(13)
     1006            self.skychunk.deleteDatastore = rs.getInt(14)
     1007            self.skychunk.deleteDxLayer = rs.getInt(15)
     1008
     1009            self.skychunk.epoch = rs.getString(16)
     1010
     1011            self.skychunk.survey = rs.getString(17)
     1012            self.skychunk.pspsSurvey = rs.getString(18)
     1013
     1014            if rs.getInt(19) == 1: self.skychunk.batchTypes.append("P2")
     1015            if rs.getInt(20) == 1: self.skychunk.batchTypes.append("ST")
     1016            if rs.getInt(21) == 1: self.skychunk.batchTypes.append("OB")
     1017
     1018            self.skychunk.force = True # TODO
     1019            self.skychunk.parallel = False # TODO
     1020
     1021            if rs.getInt(22) == 1: self.skychunk.parallel = True
     1022
     1023            if self.skychunk.parallel: print "USING parallel"
     1024            self.skychunk.isLoaded = True
     1025        except:
     1026            self.logger.errorPair("Could not read skychunk with name", self.skychunk.name)
     1027            self.skychunk.isLoaded = False
     1028
     1029        return self.skychunk.isLoaded
    10101030
    10111031    '''
     
    10151035
    10161036        sql = "SELECT id FROM box \
    1017                WHERE config  = '" + self.config.name + "' \
     1037               WHERE skychunk  = '" + self.skychunk.name + "' \
    10181038               AND ra_center = " + str(ra) + " \
    10191039               AND dec_center = " + str(dec) + " \
    1020                AND box_side = " + str(self.config.boxSize)
     1040               AND box_side = " + str(self.skychunk.boxSize)
    10211041
    10221042        id = -1
     
    10341054    '''
    10351055    def removeAllBoxes(self):
    1036         self.execute("DELETE FROM box WHERE config = '" + self.config.name + "'")
     1056        self.execute("DELETE FROM box WHERE skychunk = '" + self.skychunk.name + "'")
    10371057
    10381058    '''
     
    10471067
    10481068            sql = "INSERT INTO box \
    1049                    (config, ra_center, dec_center, box_side) \
     1069                   (skychunk, ra_center, dec_center, box_side) \
    10501070                   VALUES \
    1051                    ('" + self.config.name + "', " + str(ra) + ", " + str(dec) + ", " + str(self.config.boxSize) + ")"
     1071                   ('" + self.skychunk.name + "', " + str(ra) + ", " + str(dec) + ", " + str(self.skychunk.boxSize) + ")"
    10521072
    10531073            self.execute(sql)
     
    10551075
    10561076        return id
     1077
     1078    '''
     1079    Inserts new box into box table. If it already exisits, it returns existing box id
     1080    '''
     1081    def isBoxIngested(self, id):
     1082
     1083        # set the field 'ingested' to 1 for this box
     1084        sql = "select ingested from box where id = " + str(id)
     1085        try:
     1086            rs = self.executeQuery(sql)
     1087            if not rs.next():
     1088                print "no matching boxes for ", str(id)
     1089                raise
     1090            status = rs.getInt(1)
     1091        except:
     1092            print "failed to set box ", str(id), "as ingested"
     1093            raise
     1094
     1095        return status
     1096    '''
     1097    Inserts new box into box table. If it already exisits, it returns existing box id
     1098    '''
     1099    def setIngestedBox(self, id):
     1100
     1101        # set the field 'ingested' to 1 for this box
     1102        sql = "update box set ingested = 1 where id = " + str(id)
     1103        try:
     1104            self.execute(sql)
     1105        except:
     1106            print "failed to set box ", str(id), "as ingested"
     1107            raise
     1108
     1109    '''
     1110    Inserts new box into box table. If it already exisits, it returns existing box id
     1111    '''
     1112    def clearIngestedBoxes(self):
     1113
     1114        # set the field 'ingested' to 1 for this box
     1115        sql = "update box set ingested = 0"
     1116        try:
     1117            self.execute(sql)
     1118        except:
     1119            print "failed to clear boxes as ingested"
     1120            raise
    10571121
    10581122    '''
     
    10881152               FROM box \
    10891153               JOIN pending ON (id = box_id) \
    1090                WHERE config = '" + self.config.name + "' \
     1154               WHERE skychunk = '" + self.skychunk.name + "' \
    10911155               AND batch_type = '" + batchType + "' \
    10921156               AND ra_center NOT IN \
    10931157               (SELECT ra_center \
    10941158                FROM stripe \
    1095                 WHERE config = '" + self.config.name + "') \
     1159                WHERE skychunk = '" + self.skychunk.name + "') \
    10961160               GROUP BY ra_center LIMIT 1"
     1161
     1162        # XXX print "sql: ", sql               
    10971163
    10981164        try:
     
    11061172                   FROM box \
    11071173                   JOIN pending ON (id = box_id) \
    1108                    WHERE config = '" + self.config.name + "' \
     1174                   WHERE skychunk = '" + self.skychunk.name + "' \
    11091175                   AND batch_type = '" + batchType + "' \
    11101176                   GROUP BY ra_center \
     
    11261192               WHERE ra_center = " + str(raCenter) + " \
    11271193               AND batch_type = '" + batchType + "' \
    1128                AND config = '" + self.config.name + "' \
     1194               AND skychunk = '" + self.skychunk.name + "' \
    11291195               ORDER BY dec_center DESC"
    11301196
     
    11591225        # now insert new stripe entry
    11601226        sql = "INSERT INTO stripe \
    1161                (client_id, config, ra_center) \
    1162                SELECT clients.id, clients.config, " + str(raCenter) + " \
     1227               (client_id, skychunk, ra_center) \
     1228               SELECT clients.id, clients.skychunk, " + str(raCenter) + " \
    11631229               FROM clients \
    11641230               WHERE host = '" + host + "' \
     
    11881254
    11891255    '''
    1190     Returns ids for pending items for this config
     1256    Returns ids for pending items for this skychunk
    11911257    '''
    11921258    def getPendingIds(self, batchType):
     
    11951261               FROM pending \
    11961262               JOIN box ON (box_id = id) \
    1197                WHERE config = '" + self.config.name + "' \
     1263               WHERE skychunk = '" + self.skychunk.name + "' \
    11981264               AND batch_type = '" + batchType + "'"
    11991265
     
    12041270            rs.close()
    12051271        except:
    1206             self.logger.errorPair("Can't get pending ids for this config", sql)
     1272            self.logger.errorPair("Can't get pending ids for this skychunk", sql)
    12071273
    12081274        return ids
     
    12351301               WHERE stage_id = " + str(stageID) + " \
    12361302               AND batch_type = '" + batchType + "' \
    1237                AND config = '" + self.config.name + "'"
     1303               AND skychunk = '" + self.skychunk.name + "'"
    12381304
    12391305        self.execute(sql)
    12401306
    12411307    '''
    1242     Writes density-plot data to file for pending stuff over sky for given config
     1308    Writes density-plot data to file for pending stuff over sky for given skychunk
    12431309    '''
    12441310    def createPendingDensityPlotData(self, batchType, DATFILE):
     
    12461312        sql = "SELECT id, ra_center, dec_center \
    12471313               FROM box \
    1248                WHERE config = '" + self.config.name + "' \
     1314               WHERE skychunk = '" + self.skychunk.name + "' \
    12491315               ORDER BY ra_center, dec_center"
    12501316
     
    12991365    def getItemsInThisThisBox(self, ra, dec):
    13001366
    1301         halfSide = self.config.boxSize/2.0
     1367        halfSide = self.skychunk.boxSize/2.0
    13021368        minRa =  ra-halfSide
    13031369        maxRa = ra+halfSide
     
    13281394               FROM stripe \
    13291395               JOIN clients ON (client_id = id) \
    1330                WHERE clients.config = '" + self.config.name + "' \
     1396               WHERE clients.skychunk = '" + self.skychunk.name + "' \
    13311397               ORDER BY host, started"
    13321398
  • trunk/ippToPsps/jython/loader.py

    r34661 r35097  
    3434        super(Loader, self).__init__(argv, 1, 1)
    3535
    36         # create gpc1 database objects
     36        if self.skychunk.parallel:
     37            print "PARALLEL dvo"
     38        else:
     39            print "SERIAL dvo"
     40
     41        # connect to the gpc1 database
    3742        self.gpc1Db = Gpc1Db(self.logger, self.config)
    3843
    3944        # connect to scratch database
    40         scratchDbs = ['ipptopsps_scratch', 'ipptopsps_scratch2', 'ipptopsps_scratch3']
    41         for dbName in scratchDbs:
    42             self.scratchDb = ScratchDb(self.logger, self.config, dbName)
    43             if self.scratchDb.anyOtherConnections():
    44                 self.logger.errorPair("This scratch Db is already in use", dbName)
     45        scratchDbs = ['1', '2', '3']
     46        for dbVersion in scratchDbs:
     47            self.scratchDb = ScratchDb(self.logger, self.config, dbVersion)
     48            if not self.config.test and self.scratchDb.anyOtherConnections():
     49                self.logger.errorPair("This scratch Db is already in use", self.scratchDb.dbName)
    4550                self.scratchDb.disconnect()
    4651                continue
     
    5257       
    5358        # create Datastore objects
    54         self.datastore = Datastore(self.logger, self.config, self.ippToPspsDb)
     59        self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb)
    5560
    5661        # if an IN batch is requested, create and quit
     
    6065               batch = InitBatch(self.logger,
    6166                       self.config,
     67                       self.skychunk,
    6268                       self.gpc1Db,
    6369                       self.ippToPspsDb,
     
    7278   
    7379
     80        # if the 'once' option is passed, we do not loop multiple times in 'run'
     81        self.onePassOnly = 0
     82        if len(sys.argv) > 2 and sys.argv[2] == "once":
     83           self.onePassOnly = 1
     84
    7485        # set a poll time of about 1 minute
    7586        self.parsePollTimeArg("0.0166")
    7687
    77         self.config.printAll()
     88        self.skychunk.printAll()
    7889
    7990    '''
    8091    Overrides base-class version so we can ensure our scratch Db is using the right DVO Db
    8192    '''
    82     def refreshConfig(self):
    83 
    84         ret = super(Loader, self).refreshConfig()
     93    def refreshSkychunk(self):
     94
     95        ret = super(Loader, self).refreshSkychunk()
    8596        try: self.scratchDb
    8697        except: return ret
    8798           
    88         self.dvoDetections = DvoDetections(self.logger, self.config, self.scratchDb.dbName)
     99        self.dvoDetections = DvoDetections(self.logger, self.config, self.skychunk, self.ippToPspsDb, self.scratchDb.dbName)
    89100
    90101        return ret
    91102
    92103    '''
    93     Overrides base_class version so we can break out of processing loops if the config changes
     104    Overrides base_class version so we can break out of processing loops if the skychunk changes
    94105    '''
    95106    def checkClientStatus(self):
    96107
    97         oldConfigName = self.config.name
     108        oldSkychunkName = self.skychunk.name
    98109        super(Loader, self).checkClientStatus()
    99         if oldConfigName != self.config.name:
    100             self.logger.infoPair("Config changed",  "from '" + oldConfigName + "' to '" + self.config.name + "'")
    101             self.config.printAll()
     110        if oldSkychunkName != self.skychunk.name:
     111            self.logger.infoPair("Skychunk changed",  "from '" + oldSkychunkName + "' to '" + self.skychunk.name + "'")
     112            self.skychunk.printAll()
    102113            return False
    103114
     
    115126
    116127            abort = False
    117             for batchType in self.config.batchTypes:
     128            for batchType in self.skychunk.batchTypes:
    118129
    119130                # get a stripe's worth of box IDs
     
    141152                    ids = self.ippToPspsDb.getPendingIdsForThisBox(boxId, batchType)
    142153               
     154                    # ids are the stage_ids for items to be processed (eg, stack_id for a stack CMF, cam_id for P2 smf)
     155
    143156                    if len(ids) < 1:
    144157                        self.logger.debugPair("No " + batchType + " items found in this box", "skipping")
     
    149162                    self.logger.infoPair("Box dimensions", "%.1f / %.1f / %.1f" % (boxDim['RA'], boxDim['DEC'], boxDim['SIDE']))
    150163                    self.logger.infoPair(batchType + " items found in this box", "%d" % len(ids))
    151                     boxSizeWithBorder = boxDim['SIDE'] + (self.config.BORDER * 2)
     164                    boxSizeWithBorder = boxDim['SIDE'] + (self.skychunk.BORDER * 2)
     165                    boxSizeSansBorder = boxDim['SIDE']
    152166                    self.logger.infoPair("got here", "ok")
    153167                    useFullTables = 0
    154168                    if batchType != "OB":
    155                         # look in DVO for this box (with extra border)
    156                         self.logger.infoPair("Querying DVO for this sky area", "")
    157                         self.dvoDetections.setSkyAreaAsBox(boxDim['RA'], boxDim['DEC'], boxSizeWithBorder)
    158                         #self.dvoDetections.setSkyArea()
    159                         sizeToBeIngested = self.dvoDetections.getDiskSizeOfRegionsToBeIngested()
    160                         if sizeToBeIngested == 0.0: smfsPerGB = 999999999
    161                         else: smfsPerGB = len(ids)/sizeToBeIngested
    162                         self.logger.infoPair("DVO to be ingested", "%.1f GB" % sizeToBeIngested)
    163                         self.logger.infoPair("smfs-per-GB", "%.1f" % smfsPerGB)
    164                         # should do we pre-ingest stuff from DVO?
    165                         if batchType == 'P2' and smfsPerGB > 30:
    166                             if not self.dvoDetections.sync():
    167                                 self.logger.errorPair("Could not sync DVO with MySQL", "skipping")
    168                                 continue
    169      
     169
     170                        if (self.dvoDetections.useStilts):
     171                            # look in DVO for this box (with extra border)
     172                            self.logger.infoPair("Querying DVO for this sky area", "")
     173                            self.dvoDetections.setSkyAreaAsBox(boxDim['RA'], boxDim['DEC'], boxSizeWithBorder)
     174                            #self.dvoDetections.setSkyArea()
     175                            sizeToBeIngested = self.dvoDetections.getDiskSizeOfRegionsToBeIngested()
     176                            if sizeToBeIngested == 0.0: smfsPerGB = 999999999
     177                            else: smfsPerGB = len(ids)/sizeToBeIngested
     178                            self.logger.infoPair("DVO to be ingested", "%7.1e GB" % sizeToBeIngested)
     179                            self.logger.infoPair("smfs-per-GB", "%.1f" % smfsPerGB)
     180
     181                            # should do we pre-ingest stuff from DVO?
     182                            # NOTE EAM : this skychunk loads the dvo detections into the mysql db
     183                            # XXXX EAM : this should happen for both P2 and Stack detection
     184                            # XXXX EAM : in parallel model, this should happen for all P2 & Stack batches
     185                            #
     186                            if (batchType == 'P2' or batchType == 'ST') and smfsPerGB > 30:
     187                                if not self.dvoDetections.sync():
     188                                    self.logger.errorPair("Could not sync DVO with MySQL", "skipping")
     189                                    continue
     190                               
     191                                useFullTables = 1
     192                        else:
     193                            # XXX EAM : this is not currently an
     194                            # option. either remove the non-native
     195                            # ingest code or make it an option
     196                            # if we are using the native loader, always use it
     197                            # need to work out a good boundary / region strategy in coordination with
     198                            # impact of mysql insertion
     199                            if not self.ippToPspsDb.isBoxIngested(boxId):
     200                                self.dvoDetections.nativeIngestDetections(boxId, boxDim['RA'], boxDim['DEC'], boxSizeSansBorder)
     201
    170202                            useFullTables = 1
    171203               
     204                    ## else:
     205                    ##     # if we are using the native loader, always use it
     206                    ##     # need to work out a good boundary / region strategy in coordination with
     207                    ##     # impact of mysql insertion
     208                    ##     self.dvoObjects.nativeIngestObjects(boxDim['RA'], boxDim['DEC'], boxSizeSansBorder)
     209                    ##     useFullTables = 1
     210
     211                    '''
     212                    NOTE EAM : "TheseItems" refers to each of the stack CMFs, camera SMFs, or object batches
     213                    '''
    172214                    self.logger.infoBool("Using pre-ingested DVO data?", useFullTables)
    173215                    if not self.processTheseItems(batchType, ids, useFullTables):
     
    175217                        break
    176218                    self.logger.infoPair("processed","ok")
     219
    177220            if abort or not self.checkClientStatus(): abort = True
    178221            elif numAttempts > 1 and not self.waitForPollTime():  break
    179222
     223            if self.onePassOnly: self.exitProgram("one pass completed")
    180224       
    181225    '''
     
    210254                    batch = DetectionBatch(self.logger,
    211255                            self.config,
     256                            self.skychunk,
    212257                            self.gpc1Db,
    213258                            self.ippToPspsDb,
     
    219264                    batch = StackBatch(self.logger,
    220265                            self.config,
     266                            self.skychunk,
    221267                            self.gpc1Db,
    222268                            self.ippToPspsDb,
     
    229275                    batch = ObjectBatch(self.logger,
    230276                            self.config,
     277                            self.skychunk,
    231278                            self.gpc1Db,
    232279                            self.ippToPspsDb,
     
    260307    '''
    261308    def printUsage(self):
    262         super(Cleanup, self).printUsage("<[init]>")
     309        super(Loader, self).printUsage("<[init]>")
    263310
    264311   
  • trunk/ippToPsps/jython/objectbatch.py

    r34834 r35097  
    3232                 logger,
    3333                 config,
     34                 skychunk,
    3435                 gpc1Db,
    3536                 ippToPspsDb,
     
    4243               logger,
    4344               config,
     45               skychunk,
    4446               gpc1Db,
    4547               ippToPspsDb,
     
    5254
    5355       try:
    54            self.dvoObjects = DvoObjects(self.logger, self.config, self.scratchDb.dbName)
     56           self.dvoObjects = DvoObjects(self.logger, self.config, self.skychunk, self.ippToPspsDb, self.scratchDb.dbName)
    5557       except:
    5658           self.logger.errorPair("Unable to create instance of", "DvoObjects")
     
    7173        self.region = self.scratchDb.getRegionNameFromThisDvoIndex(self.id)
    7274        self.ippToPspsDb.insertObjectMeta(self.batchID, self.region)
    73         self.dvoObjects.ingestRegion(self.region)
     75        if True:
     76            self.dvoObjects.nativeIngestRegion(self.region)
     77        else:
     78            self.dvoObjects.ingestRegion(self.region)
    7479
    7580        return True
     
    261266               ,PSF_QF_PERF \
    262267               ,STARGAL_SEP \
    263                , " + str(self.config.dataRelease) + "\
     268               , " + str(self.skychunk.dataRelease) + "\
    264269               , RAND() \
    265270               FROM " + cptTableName
  • trunk/ippToPsps/jython/plot.py

    r34165 r35097  
    1515    Constructor
    1616    '''
    17     def __init__(self, logger, config, ippToPspsDb):
     17    def __init__(self, logger, skychunk, ippToPspsDb):
    1818
    1919        self.logger = logger
    20         self.config = config
     20        self.skychunk = skychunk
    2121        self.ippToPspsDb = ippToPspsDb
    2222
    2323    '''
    24     Creates a density plot of pending exposures for this config
     24    Creates a density plot of pending exposures for this skychunk
    2525    '''
    2626    def createDensityPlot(self, batchType, forCzartool=False):
    2727
    28         tempFilename = "./" + self.config.name + "_" + batchType + "_plotData.dat"
     28        tempFilename = "./" + self.skychunk.name + "_" + batchType + "_plotData.dat"
    2929        DATFILE = open(tempFilename,'w')
    3030        max = self.ippToPspsDb.createPendingDensityPlotData(batchType, DATFILE)
     
    3636
    3737        if forCzartool:
    38             OUTPUTFILE = self.config.czarPlotsPath + "/ippToPsps_density_" + self.config.name + "_" + batchType + ".png"
     38            ## XXX from config??
     39            OUTPUTFILE = self.skychunk.czarPlotsPath + "/ippToPsps_density_" + self.skychunk.name + "_" + batchType + ".png"
    3940        else:
    40             OUTPUTFILE = self.config.name + "_" + batchType + "_" + timestamp + ".png"
     41            OUTPUTFILE = self.skychunk.name + "_" + batchType + "_" + timestamp + ".png"
    4142
    4243        f = os.popen('/home/panstarrs/ipp/local/bin/gnuplot', 'w')
     
    4950        print >> f, "set term " + TERM + "; \
    5051            set output \"" + OUTPUTFILE + "\"; \
    51             set title \"Unprocessed " + batchType + " items for '" + self.config.name + "' as of " + timestamp + "\"; \
     52            set title \"Unprocessed " + batchType + " items for '" + self.skychunk.name + "' as of " + timestamp + "\"; \
    5253            set grid; \
    53             set xrange [" + str(self.config.minRa) + ":" + str(self.config.maxRa) + "] reverse; \
    54             set yrange [" + str(self.config.minDec) + ":" + str(self.config.maxDec) + "]; \
     54            set xrange [" + str(self.skychunk.minRa) + ":" + str(self.skychunk.maxRa) + "] reverse; \
     55            set yrange [" + str(self.skychunk.minDec) + ":" + str(self.skychunk.maxDec) + "]; \
    5556            unset key; \
    5657            set palette rgb 22,13,10; \
  • trunk/ippToPsps/jython/plotter.py

    r33787 r35097  
    1818        super(Plotter, self).__init__(argv)
    1919
    20         self.plot = Plot(self.logger, self.config, self.ippToPspsDb)
     20        self.plot = Plot(self.logger, self.skychunk, self.ippToPspsDb)
    2121 
    2222        if len(argv) < 3:
  • trunk/ippToPsps/jython/pollOdm.py

    r33787 r35097  
    99
    1010from ipptopsps import IppToPsps
    11 from config import Config
     11from skychunk import Skychunk
    1212from odm import Odm
    1313from batch import Batch
     
    5656
    5757            self.logger.infoSeparator()
    58             self.logger.infoPair("Config", self.config.name)
     58            self.logger.infoPair("Skychunk", self.skychunk.name)
    5959
    6060            for stage in self.stages:
  • trunk/ippToPsps/jython/pslogger.py

    r33349 r35097  
    1111   This will default to stout and no file output
    1212   '''
    13    def setup(self, programName, basePath, configName, host, pid, stdout=1, sendToFile=0):
     13   def setup(self, programName, basePath, skychunkName, host, pid, stdout=1, sendToFile=0):
    1414
    1515       formatter = logging.Formatter('%(asctime)s | %(levelname)7s | %(message)s', '%Y-%m-%d %H:%M:%S')
     
    2121           PATH = basePath + "/log"
    2222           if not os.path.exists(PATH): os.makedirs(PATH)
    23            FULLPATH = PATH + "/" + programName + "_" + configName + "_" + host + "_" + str(pid) + ".log"
     23           FULLPATH = PATH + "/" + programName + "_" + skychunkName + "_" + host + "_" + str(pid) + ".log"
    2424           # opens file to be appended
    2525           hdlr = logging.FileHandler(FULLPATH, "a")
  • trunk/ippToPsps/jython/queue.py

    r33787 r35097  
    2929        # create various objects
    3030        self.gpc1Db = Gpc1Db(self.logger, self.config)
    31         self.datastore = Datastore(self.logger, self.config, self.ippToPspsDb)
     31        self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb)
     32
    3233        try:
    33             self.dvoObjects = DvoObjects(self.logger, self.config)
     34            self.dvoObjects = DvoObjects(self.logger, self.config, self.skychunk, self.ippToPspsDb)
    3435        except:
    3536            self.exitProgram("Unable to create instance of DvoObject")
    3637            raise
    3738
    38         self.config.printAll()
     39        self.skychunk.printAll()
    3940
    4041        if len(argv) > 2: self.parsePollTimeArg(sys.argv[2])
    41    
    4242
    4343    '''
    4444    Main processing loop.
    45     Tiled area is defined in config and looks for available stage_ids for each tile and writes them to ippToPsps database ready for processing
     45    Tiled area is defined in 'skychunk' and looks for available stage_ids for each tile and writes them to ippToPsps database ready for processing
    4646    by one or more loading clients that may be running on any host
    4747    '''
     
    5454       
    5555            # queue up batches that are processed but not loaded to datastore
    56             for batchType in self.config.batchTypes:
     56            for batchType in self.skychunk.batchTypes:
    5757
    5858                self.logger.infoTitle("Previous failed datastore loads")
     
    6464
    6565                # for object batches, get full list of stuff from Dvo
     66                # XXX : need to fix 'dvo.setSkyArea' or this may not return the full list for a parallel dvo
    6667                if batchType == "OB":
    6768                    self.dvoObjects.setSkyArea(
    68                             self.config.minRa,
    69                             self.config.maxRa,
    70                             self.config.minDec,
    71                             self.config.maxDec)
     69                            self.skychunk.minRa,
     70                            self.skychunk.maxRa,
     71                            self.skychunk.minDec,
     72                            self.skychunk.maxDec)
    7273                    rows = self.dvoObjects.allPopulatedRegionInfo
    7374                    self.dvoObjects.printSummary()
     
    7677                else:
    7778                    rows = self.gpc1Db.getItemsInThisDVODbForThisStage(
    78                             self.config.dvoLabel,
     79                            self.skychunk.dvoLabel,
    7980                            batchType,
    80                             self.config.minRa,
    81                             self.config.maxRa,
    82                             self.config.minDec,
    83                             self.config.maxDec)
     81                            self.skychunk.minRa,
     82                            self.skychunk.maxRa,
     83                            self.skychunk.minDec,
     84                            self.skychunk.maxDec)
     85
     86                # EAM TEST I/O
     87                self.logger.infoPair("received rows from db:", len(rows))
    8488
    8589                # first report total stuff
     
    104108                self.ippToPspsDb.storeAllItems(pending)
    105109
    106                 # loop through full range of RA/Dec queueing stuff in boxes of size self.config.boxSize
     110                # loop through full range of RA/Dec queueing stuff in boxes of size self.skychunk.boxSize
    107111                if len(ids) > 0:
    108112
     
    112116   
    113117                    # starting positions
    114                     ra = self.config.minRa + self.config.halfBox
    115                     dec = self.config.minDec + self.config.halfBox
     118                    ra = self.skychunk.minRa + self.skychunk.halfBox
     119                    dec = self.skychunk.minDec + self.skychunk.halfBox
    116120   
    117                     while ra <= self.config.maxRa:
    118                        while dec <= self.config.maxDec:
     121                    while ra <= self.skychunk.maxRa:
     122                       while dec <= self.skychunk.maxDec:
    119123           
    120124                           box_id = self.ippToPspsDb.insertBox(ra, dec)
     
    125129                                       ra,
    126130                                       dec,
    127                                        self.config.boxSize,
     131                                       self.skychunk.boxSize,
    128132                                       len(ids)))
    129133               
    130134                           if len(ids) > 0: self.ippToPspsDb.insertPending(box_id, batchType, ids)
    131135
    132                            dec = dec + self.config.boxSize
    133                        dec = self.config.minDec + self.config.halfBox
    134                        ra = ra + self.config.boxSize
     136                           dec = dec + self.skychunk.boxSize
     137                       dec = self.skychunk.minDec + self.skychunk.halfBox
     138                       ra = ra + self.skychunk.boxSize
    135139           
    136140                self.logger.info("+-------------+-------------+-------------+-------------+")
     
    150154   
    151155            batchName = Batch.getNameFromID(batchID)
    152             subDir = Batch.getSubDir(self.config.basePath, batchType, self.config.dvoLabel)
     156            subDir = Batch.getSubDir(self.skychunk.basePath, batchType, self.skychunk.dvoLabel)
    153157            tarballFile = Batch.getTarballFile(batchID)
    154158            self.logger.infoPair("Batch name", batchName)
  • trunk/ippToPsps/jython/scratchdb.py

    r34638 r35097  
    1919    Constructor
    2020    '''
    21     def __init__(self, logger, config, dbName=None):
    22         super(ScratchDb, self).__init__(logger, config, "localdatabase", dbName)
     21    def __init__(self, logger, config, dbVersion, dbName=None):
     22
     23        # create gpc1 database objects
     24        if (config.test):
     25            dbType = "localdatabase_test"
     26        else:
     27            dbType = "localdatabase"
     28
     29        if not dbName:
     30            dbName = config.getDbName(dbType)
     31            dbName += dbVersion
     32
     33        super(ScratchDb, self).__init__(logger, config, dbType, dbName)
    2334
    2435        self.dvoDoneTable = "dvoDone"
     
    340351            rs.first()
    341352            if rs.getInt(1) < 50:
     353                # print "bad astromety"
    342354                self.logger.debug("Bad astrometric solution for",  ota)
    343355                return False
    344356            else:
     357                # print "good astromety"
    345358                return True
    346359        except:
     360            # print "query failed"
    347361            self.logger.debug("Unable to check astrometric solution")
     362            return False
    348363
    349364        return True
     
    355370    def createDvoTables(self):
    356371   
     372        dvoImagesTable = "dvoImages"
     373        dvoDetectionTable = "dvoDetections"
     374
    357375        # drop and create Images table
    358         self.logger.debugPair("Creating DVO table", self.dvoImagesTable)
    359         sql = "DROP TABLE " + self.dvoImagesTable
     376        self.logger.debugPair("Creating DVO table", dvoImagesTable)
     377        sql = "DROP TABLE " + dvoImagesTable
     378
    360379        try: self.execute(sql)
    361380        except: pass
    362381       
    363         sql = "CREATE TABLE " + self.dvoImagesTable + " ( \
     382        sql = "CREATE TABLE " + dvoImagesTable + " ( \
    364383               SOURCE_ID SMALLINT, \
    365384               IMAGE_ID INT, \
     
    375394
    376395        # now detection table
    377         self.logger.debugPair("Creating DVO table", self.dvoDetectionTable)
    378         sql = "DROP TABLE " + self.dvoDetectionTable
     396        self.logger.debugPair("Creating DVO table", dvoDetectionTable)
     397        sql = "DROP TABLE " + dvoDetectionTable
    379398        try: self.execute(sql)
    380399        except: pass
     
    396415               raErr REAL, \
    397416               decErr REAL, \
    398                PRIMARY KEY (imageID, ippDetectID) \
    399                )"
     417               PRIMARY KEY (imageID, ippDetectID), \
     418               KEY (objID, detectID) \
     419             )"
    400420
    401421        try: self.execute(sql)
    402422        except:
    403423            self.logger.error("Unable to create DVO detection database table")
    404         self.makeColumnUnique("dvoDetection", "objID")
     424
     425        # XXX EAM : for the parallel mode, dvoDetection requires duplicate objID values!
     426        # self.makeColumnUnique("dvoDetection", "objID")
    405427
    406428    '''
     
    479501       self.createIndex(self.dvoDetectionTable, "fileID")
    480502
    481        # now add a delete cascading foreign key constraint on fileID
    482        sql = "ALTER TABLE dvoDetectionFull \
     503       # XXX : this should be based on choice of useStilts (which is set in dvo.py and must be moved)
     504       if (False):
     505           # now add a delete cascading foreign key constraint on fileID
     506           sql = "ALTER TABLE dvoDetectionFull \
    483507              ADD CONSTRAINT fk_fileID \
    484508              FOREIGN KEY (fileID) \
    485509              REFERENCES dvoDone(id) \
    486510              ON DELETE CASCADE"
    487        try: self.execute(sql)
    488        except:
    489            self.logger.errorPair("Unable to create foreign key on", self.dvoDoneTable)
    490            return False
     511           try: self.execute(sql)
     512           except:
     513               self.logger.errorPair("Unable to create foreign key on", self.dvoDoneTable)
     514               return False
    491515
    492516       return True
  • trunk/ippToPsps/jython/setupScratchDb.py

    r33787 r35097  
    22
    33import sys
     4import os
     5import socket
    46import stilts
    57from java.lang import *
    68from java.sql import *
    79
    8 
    9 from ipptopsps import IppToPsps
     10from config import Config
    1011from scratchdb import ScratchDb
     12from ipptopspsdb import IppToPspsDb
    1113
    1214'''
    1315SetupScratchDb class
    1416'''
    15 class SetupScratchDb(IppToPsps):
     17class SetupScratchDb(object):
     18
     19    ## XXX EAM : 2013.01.31 - i have changed the 'config.py' concept
     20    ## to only include the global static information (from
     21    ## settings.xml), and stripped out the dynamic information to a
     22    ## new entity called 'skychunk'
     23
     24    ## XXX note that setupScratchDb.py fails if there are no valid
     25    ## entries in the config table (or if it is passed a non-existent
     26    ## config) This is because ipptopsps.__init__ calls
     27    ## checkClientStatus, which calls refreshConfig, which calls
     28    ## readConfig, which attempts to select the matching entry from
     29    ## the config table.  if the select returns 0 rows, the code
     30    ## crashes.  even if it were not to crash (eg, if it returned
     31    ## False), checkClientStatus would enter a waiting loop until the
     32    ## config existed.
     33   
     34    ## since a scratchDb is needed to do basically anything, it seems
     35    ## like 'setupScratchDb' should not be dependent on the details of
     36    ## the configs, etc.
     37
     38    ## what are the options?  I think this is a problem of poor
     39    ## factoring / dependencies, esp for 'config.py'.  there are two
     40    ## (or more) aspects to 'config.py' : management of the dynamic
     41    ## 'config' information (basically, the regions / dvodbs of
     42    ## interest) and manipulation of the static / system configuration
     43    ## information.
     44
     45    ## these concepts should probably be split and the more general
     46    ## part (settings & logger) placed in one module and the rest elsewhere.
     47
     48    ## as for setupScratchDb.py, it looks like it only uses the static
     49    ## settings info and the logger functions, so it should not be a
     50    ## child of the ipptopsps class
    1651
    1752    '''
     
    1954    '''
    2055    def __init__(self, argv):
    21         super(SetupScratchDb, self).__init__(argv)
     56        # set up config object
     57        self.config = Config()
    2258
    23         if len(argv) < 3:
     59        if len(argv) < 2:
    2460            self.printUsage()
    2561            self.exitProgram("incorrect args")
    2662
     63        # some class constants
     64        self.HOST = socket.gethostname()
     65        self.PID = os.getpid()
     66
     67        # XXX Shouldn't config set up logger?
     68        # (not yet, since we set HOST & PID with program...)
     69        self.logger = self.config.getLogger(self.HOST, self.PID, 1, 0)
     70
    2771        try:
    28             self.scratchDb = ScratchDb(self.logger, self.config, argv[2])
     72            self.scratchDb = ScratchDb(self.logger, self.config, argv[1])
    2973        except:
    3074            self.exitProgram("Could not connect to a scratch Db")
    3175            raise
    32 
    3376
    3477    def run(self):
     
    4285        # install IN tables
    4386        self.logger.infoPair("Installing", "initialization tables")
    44         tables = stilts.treads("../config/IN/tables.vot")
     87        tablepath = self.config.configDir + "tables.IN.vot"
     88        tables = stilts.treads(tablepath)
     89
    4590        for table in tables:
     91            # EAM TEST I/O
     92            self.logger.infoPair("Creating IN table: ", table.name)
    4693            self.logger.debug("Creating IN table: " + table.name)
    4794            table.write(self.scratchDb.url + '#' + table.name)
    4895
    49     '''
    50     Overrides base-class version
    51     '''
     96        # create basic DVO tables
     97        self.logger.infoPair("Installing", "initialization tables")
     98        self.scratchDb.createDvoTables()
     99
    52100    def printUsage(self):
    53         super(SetupScratchDb, self).printUsage("<scratchdb_name>")
     101        # write message to log or stdout if no logger set up
     102        msg = os.path.basename(sys.argv[0]) + " <scratchdb_version> "
     103        try:
     104            self.logger.errorPair("Usage:", msg)
     105        except:
     106            print "*** Usage: " + msg
    54107
    55108'''
     
    61114    setupScratchDb.exitProgram("completed")
    62115except: pass
    63 
    64 
  • trunk/ippToPsps/jython/stackbatch.py

    r34879 r35097  
    22
    33import os.path
     4import glob
    45import sys
    56
     
    3233                 logger,
    3334                 config,
     35                 skychunk,
    3436                 gpc1Db,
    3537                 ippToPspsDb,
     
    4244               logger,
    4345               config,
     46               skychunk,
    4447               gpc1Db,
    4548               ippToPspsDb,
     
    4851               batchID,
    4952               "ST",
    50                gpc1Db.getStackStageCmf(config.dvoLabel, stackID),
     53               gpc1Db.getStackStageCmf(skychunk.dvoLabel, stackID),
    5154               useFullTables)
     55
     56       # self.printline = 0
     57       # # self.testprint()
    5258
    5359       self.stackType = "DEEP_STACK" # TODO
     
    6369       self.filterID = self.scratchDb.getFilterID(self.filter)
    6470       self.skycell = meta[1];
     71
     72       # self.testprint()
    6573
    6674       # skycell is, eg "skycell.1133.081"
     
    7684       self.skycell = self.skycell[8:12]
    7785       self.projectioncell = self.skycell
     86
     87       # self.testprint()
    7888
    7989       # proposed new values. Need to coordinate with the SkyCell table
     
    96106       self.scratchDb.dropTable("StackDetectionCalib")
    97107
     108       # self.testprint()
     109
    98110       # delete IPP tables
    99111       self.scratchDb.dropTable("SkyChip_psf")
     
    115127       if not self.useFullTables:
    116128           self.scratchDb.insertNewDvoExternID(self.header['SOURCEID'], self.header['IMAGEID'])
     129
     130       # self.testprint()
    117131
    118132       # dump stuff to log
     
    139153        self.scratchDb.execute(sql)
    140154
     155
     156    def testprint(self):
     157      print "here ", self.printline
     158      self.printline += 1
    141159
    142160    '''
     
    348366        self.logger.infoPair("Procesing table", "StackMeta")
    349367
     368        self.fwhm_maj    = self.safeDictionaryAccess(self.header, 'FWHM_MAJ')
     369        self.fwhm_maj_uq = self.safeDictionaryAccess(self.header, 'FW_MJ_UQ')
     370        self.psfmodel    = self.safeDictionaryAccess(self.header, 'PSFMODEL')
     371        if (self.fwhm_maj    == "NULL"): self.fwhm_maj    = -999
     372        if (self.fwhm_maj_uq == "NULL"): self.fwhm_maj_uq = -999
     373
     374        # print "fwhm_maj    = ", self.fwhm_maj
     375        # print "fwhm_maj_uq = ", self.fwhm_maj_uq
     376        # print "psfmodel    = ", self.psfmodel
     377
    350378        sql = "INSERT INTO StackMeta (\
    351379        stackMetaID \
     
    375403        ," + self.header['FPA.ZP'] + " \
    376404        ," + self.expTime + " \
    377         ,'" + self.safeDictionaryAccess(self.header, 'PSFMODEL') + "' \
    378         ,'" + self.safeDictionaryAccess(self.header, 'FWHM_MAJ') + "' \
    379         ,'" + self.safeDictionaryAccess(self.header, 'FW_MJ_UQ') + "' \
     405        ,'" + self.psfmodel  + "' \
     406        ," + str(self.fwhm_maj)    + " \
     407        ," + str(self.fwhm_maj_uq) + " \
    380408        ,'" + self.header['CTYPE1'] + "' \
    381409        ,'" + self.header['CTYPE2'] + "' \
     
    395423        self.scratchDb.updateAllRows("StackMeta", "surveyID", str(self.surveyID))
    396424        self.scratchDb.updateFilterID("StackMeta", self.filter)
    397         self.scratchDb.updateAllRows("StackMeta", "dataRelease", str(self.config.dataRelease))
     425        self.scratchDb.updateAllRows("StackMeta", "dataRelease", str(self.skychunk.dataRelease))
    398426        self.updateStackTypeID("StackMeta")
    399427
     
    486514               ," + self.historyModNum + " \
    487515               FROM SkyChip_psf"
    488         self.scratchDb.execute(sql)
    489        
     516
     517        # print "sql: ", sql
     518        # response = raw_input("ready to insert stack det ")
     519
     520        self.scratchDb.execute(sql)
     521
    490522        #it is possible to drop some detections from dvo (that are present in the cmf). when that happens we get a 0 for objid
    491523        #we drop those...
     
    498530        self.scratchDb.updateFilterID("StackDetection", self.filter)
    499531       
    500         self.scratchDb.updateAllRows("StackDetection", "dataRelease", str(self.config.dataRelease))
     532        self.scratchDb.updateAllRows("StackDetection", "dataRelease", str(self.skychunk.dataRelease))
    501533       
    502534        self.scratchDb.updateAllRows("StackDetection", "primaryF", "0")
     
    509541       
    510542        self.updateDvoIDsAndFlags("StackDetection")
     543        # response = raw_input("updated dvo ")
    511544       
    512545        sql = "ALTER IGNORE TABLE StackDetection ADD PRIMARY KEY (objID)"
    513546       
    514547        self.scratchDb.execute(sql)
     548        # response = raw_input("add primary key? ")
    515549 
    516550        if self.stackType == "DEEP_STACK":
     
    524558           
    525559            self.scratchDb.execute(sql)
     560            # response = raw_input("add psf flux ")
    526561           
    527562        #leave null instflux in
     
    529564       
    530565        self.scratchDb.reportAndDeleteRowsWithNULLS("StackDetection", "objID")
     566        # response = raw_input("delete nulls ")
    531567       
    532568        sql="DELETE FROM StackDetection where objID = 0"
    533569       
    534570        self.scratchDb.execute(sql)
    535         self.logger.infoPair("Delleting", "entries with StackDetection.objID = 0")
     571        self.logger.infoPair("Deleting", "entries with StackDetection.objID = 0")
     572        # response = raw_input("deleted objID is 0 ")
    536573       
    537574
     
    577614        self.scratchDb.updateAllRows("StackApFlx", "surveyID", str(self.surveyID))
    578615        self.scratchDb.updateFilterID("StackApFlx", self.filter)
    579         self.scratchDb.updateAllRows("StackApFlx", "dataRelease", str(self.config.dataRelease))
     616        self.scratchDb.updateAllRows("StackApFlx", "dataRelease", str(self.skychunk.dataRelease))
    580617        self.scratchDb.updateAllRows("StackApFlx", "primaryF", "0")
    581618        self.scratchDb.updateAllRows("StackApFlx", "activeFlag", "0")
     
    611648        self.scratchDb.updateAllRows("StackModelFit", "surveyID", str(self.surveyID))
    612649        self.scratchDb.updateFilterID("StackModelFit", self.filter)
    613         self.scratchDb.updateAllRows("StackModelFit", "dataRelease", str(self.config.dataRelease))
     650        self.scratchDb.updateAllRows("StackModelFit", "dataRelease", str(self.skychunk.dataRelease))
    614651        self.scratchDb.updateAllRows("StackModelFit", "primaryF", "0")
    615652        self.scratchDb.updateAllRows("StackModelFit", "activeFlag", "0")
     
    676713
    677714        self.scratchDb.updateAllRows("SkinnyObject", "surveyID", str(self.surveyID))
    678         self.scratchDb.updateAllRows("SkinnyObject", "dataRelease", str(self.config.dataRelease))
     715        self.scratchDb.updateAllRows("SkinnyObject", "dataRelease", str(self.skychunk.dataRelease))
    679716
    680717    '''   
    681718    Populates the StackDetectionCalib table
    682     '''
    683     def populateStackDetectionCalib(self):
     719    XXX this can probably get a big speed increase by using 'SELECT () INTO OUTFILE '/tmp/name' and then
     720    calling the load data infile '/tmp/name' into table;
     721    '''
     722    def populateStackDetectionCalibInsertUpdate(self):
    684723        self.logger.infoPair("Processing table", "StackDetectionCalib")
    685724        tableName = "StackDetectionCalib"
     
    702741               FROM StackDetection"
    703742        self.scratchDb.execute(sql)
     743
     744        imageID = self.scratchDb.getImageIDFromExternID(self.header['IMAGEID'])
     745        self.logger.infoPair("obtained","imageID")
     746
    704747        # insert calibration information from dvoDetections into the Table
    705748        sql = "UPDATE " + tableName + " AS a, "  + self.scratchDb.dvoDetectionTable + " AS b \
     
    712755            a.expTime = b.expTime, \
    713756            a.airMass = b.airMass   \
    714             WHERE a.stackDetectID = b.detectID"
    715         self.scratchDb.execute(sql)
    716         self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.config.dataRelease))
    717        
    718    
    719 
     757            WHERE a.stackDetectID = b.detectID \
     758            AND b.imageID = " + str(imageID)
     759        self.scratchDb.execute(sql)
     760        self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.skychunk.dataRelease))
     761       
     762    def populateStackDetectionCalib(self):
     763
     764        tableName = "StackDetectionCalib"
     765        self.logger.infoPair("Processing table", tableName)
     766
     767        imageID = self.scratchDb.getImageIDFromExternID(self.header['IMAGEID'])
     768        self.logger.infoPair("obtained","imageID")
     769
     770        # check for & create output directory first
     771        datadumpDir = "/tmp/datadump"
     772        try:
     773            statinfo = os.stat(datadumpDir)
     774            # check on the stat results?
     775        except:
     776            print "making the data dump directory ", datadumpDir
     777            os.mkdir(datadumpDir)
     778            os.chmod(datadumpDir, 0777)
     779            statinfo = os.stat(datadumpDir)
     780
     781        dumpFile = datadumpDir + "/genetest.xx.dat"
     782        files = glob.glob(dumpFile)
     783        if len(files) > 0:
     784            os.unlink(dumpFile)
     785
     786        # insert all detections into table
     787        sql = "SELECT \
     788          a.objID,    \
     789          a.stackDetectID, \
     790          a.ippObjID,      \
     791          a.ippDetectID,   \
     792          a.filterID,      \
     793          a.surveyID,      \
     794          b.ra,            \
     795          b.dec_,          \
     796          b.raErr,         \
     797          b.decErr,        \
     798          b.zp,            \
     799          b.zpErr,         \
     800          b.expTime,       \
     801          b.airMass,       \
     802          " + str(self.skychunk.dataRelease) + " \
     803         FROM              \
     804           StackDetection as a \
     805         JOIN " + self.scratchDb.dvoDetectionTable + " as b \
     806         ON (a.stackDetectID = b.detectID) where b.imageID = " + str(imageID) + \
     807         " INTO OUTFILE '" + dumpFile + "'"
     808        print "sql: ", sql
     809        self.scratchDb.execute(sql)
     810
     811        sql = "LOAD DATA INFILE '" + dumpFile + "' INTO TABLE " + tableName
     812        print "sql: ", sql
     813        self.scratchDb.execute(sql)
     814
     815        ## XXX write this with the select/insert
     816        # self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.skychunk.dataRelease))
    720817
    721818    '''
     
    737834
    738835        self.scratchDb.updateFilterID("ObjectCalColor", self.filter)
    739         self.scratchDb.updateAllRows("ObjectCalColor", "dataRelease", str(self.config.dataRelease))
     836        self.scratchDb.updateAllRows("ObjectCalColor", "dataRelease", str(self.skychunk.dataRelease))
    740837
    741838
     
    802899               WHERE a.ippDetectID = b.ippDetectID \
    803900               AND b.imageID = " + str(imageID)
     901
     902        # print "update dvo sql: ", sql
     903        # response = raw_input("update dvo...")
    804904        self.scratchDb.execute(sql)
    805905   
Note: See TracChangeset for help on using the changeset viewer.