Changeset 35097 for trunk/ippToPsps/jython
- Timestamp:
- Feb 6, 2013, 3:16:35 PM (13 years ago)
- Location:
- trunk/ippToPsps
- Files:
-
- 28 edited
- 3 copied
-
. (modified) (1 prop)
-
jython (modified) (1 prop)
-
jython/Makefile.am (copied) (copied from branches/eam_branches/ipp-20121219/ippToPsps/jython/Makefile.am )
-
jython/batch.py (modified) (16 diffs)
-
jython/batchRepublisher.py (modified) (3 diffs)
-
jython/cleanup.py (modified) (5 diffs)
-
jython/config.py (modified) (5 diffs)
-
jython/console.py (modified) (3 diffs)
-
jython/datastore.py (modified) (4 diffs)
-
jython/datastoreRemover.py (modified) (1 diff)
-
jython/detectionbatch.py (modified) (22 diffs)
-
jython/dvo.py (modified) (12 diffs)
-
jython/dvodetections.py (modified) (6 diffs)
-
jython/dvoobjects.py (modified) (4 diffs)
-
jython/fits.py (modified) (1 diff)
-
jython/gpc1db.py (modified) (6 diffs)
-
jython/initbatch.py (modified) (2 diffs)
-
jython/ippjython (copied) (copied from branches/eam_branches/ipp-20121219/ippToPsps/jython/ippjython )
-
jython/ipptopsps.py (modified) (9 diffs)
-
jython/ipptopspsdb.py (modified) (44 diffs)
-
jython/loader.py (modified) (12 diffs)
-
jython/objectbatch.py (modified) (5 diffs)
-
jython/plot.py (modified) (3 diffs)
-
jython/plotter.py (modified) (1 diff)
-
jython/pollOdm.py (modified) (2 diffs)
-
jython/pslogger.py (modified) (2 diffs)
-
jython/queue.py (modified) (8 diffs)
-
jython/scratchdb.py (modified) (6 diffs)
-
jython/setupScratchDb.py (modified) (4 diffs)
-
jython/skychunk.py (copied) (copied from branches/eam_branches/ipp-20121219/ippToPsps/jython/skychunk.py )
-
jython/stackbatch.py (modified) (24 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/ippToPsps
- Property svn:mergeinfo changed
-
trunk/ippToPsps/jython
- Property svn:ignore
-
old new 1 1 *.class 2 Makefile 3 Makefile.in
-
- Property svn:ignore
-
trunk/ippToPsps/jython/batch.py
r33787 r35097 30 30 logger, 31 31 config, 32 skychunk, 32 33 gpc1Db, 33 34 ippToPspsDb, … … 39 40 useFullTables): 40 41 42 # print "starting the batch" 43 44 # self.printline = 0 45 # self.testprint() 46 41 47 self.readHeader = False 42 48 self.config = config 49 self.skychunk = skychunk 43 50 self.fits = fits 44 51 self.useFullTables = useFullTables … … 48 55 self.logger.infoSeparator() 49 56 self.logger.debug("Batch class constructor") 57 58 # self.testprint() 50 59 51 60 # set up class variables … … 56 65 self.scratchDb = scratchDb 57 66 self.batchType = batchType; 58 self.pspsVoTableFilePath = "../config/" + batchType + "/tables.vot" 67 self.pspsVoTableFilePath = self.config.configDir + "tables." + batchType + ".vot" 68 69 # self.testprint() 59 70 60 71 # check FITS file is ok … … 64 75 # now check that the fits header is readable 65 76 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) 67 78 raise 68 79 … … 72 83 self.tablesToExport = [] 73 84 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) 76 87 else: 77 88 self.surveyID = -1; 78 89 79 90 # create datastore object 80 self.datastore = Datastore(self.logger, self. config, self.ippToPspsDb)81 82 # get local storage location from config91 self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb) 92 93 # get local storage location from skychunk 83 94 self.batchName = Batch.getNameFromID(self.batchID) 84 95 self.subDir = Batch.getSubDir( 85 self. config.basePath,96 self.skychunk.basePath, 86 97 self.batchType, 87 self. config.dvoLabel)98 self.skychunk.dvoLabel) 88 99 89 100 self.localOutPath = Batch.getOutputPath( 90 self. config.basePath,101 self.skychunk.basePath, 91 102 self.batchType, 92 self. config.dvoLabel,103 self.skychunk.dvoLabel, 93 104 self.batchID) 94 105 95 106 if not os.path.exists(self.localOutPath): os.makedirs(self.localOutPath) 107 108 # self.testprint() 96 109 97 110 # store today's date … … 112 125 self.logger.infoPair("Input FITS primary header", "%s cards found" % self.fits.getPrimaryHeaderCardCount()) 113 126 127 # self.testprint() 128 114 129 self.logger.infoPair("Output path", self.localOutPath) 115 130 116 131 132 def testprint(self): 133 print "here ", self.printline 134 self.printline += 1 135 117 136 ''' 118 137 Static method to generated batch name from batch ID … … 232 251 root.attrib['type'] = self.batchType 233 252 root.attrib['timestamp'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 234 root.attrib['survey'] = self. config.pspsSurvey253 root.attrib['survey'] = self.skychunk.pspsSurvey 235 254 236 255 # min/max object IDs … … 273 292 # set up filenams and paths 274 293 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) 276 295 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) 278 297 279 298 # tar directory … … 376 395 self.logger.infoPair("Importing tables with filter", filter) 377 396 397 # print "trying to read ", self.fits.getPath() 398 378 399 try: 379 400 tables = stilts.treads(self.fits.getPath()) … … 385 406 for table in tables: 386 407 408 # print "import smf table ", table 387 409 match = re.match(filter, table.name) 388 410 if not match: continue 389 411 self.logger.debugPair("Reading IPP table", table.name) 390 412 table = stilts.tpipe(table, cmd='explodeall') 413 414 # print "read smf table ", table 391 415 392 416 # drop any previous tables before import … … 398 422 table = stilts.tpipe(table, cmd='replaceval -Infinity null *') 399 423 table = stilts.tpipe(table, cmd='replaceval Infinity null *') 424 # print "cleaned up values ", table 400 425 401 426 try: 402 427 table.write(self.scratchDb.url + '#' + table.name) 428 # print "wrote to mysql ", table 403 429 self.scratchDb.killLastConnectionID() 404 430 count = count + 1 … … 488 514 489 515 # TODO path to DVO prog hardcoded temporarily 490 cmd = "../src/dvograbber " + self.config.settingsPath + " " + self.scratchDb.dbName + " " + self. config.dvoLocation516 cmd = "../src/dvograbber " + self.config.settingsPath + " " + self.scratchDb.dbName + " " + self.skychunk.dvoLocation 491 517 self.logger.infoPair("Running DVO", cmd) 492 518 p = Popen(cmd, shell=True, stdout=PIPE) … … 504 530 ''' 505 531 Creates and publishes a batch 506 TODO all method s callbelow should throw exceptions on failure532 TODO all method calls below should throw exceptions on failure 507 533 ''' 508 534 def run(self): 509 535 536 # this is badly named : it creates the tables and then fills in 537 # the ImageMeta tables for each ota (alterPspsTables) 510 538 if not self.createEmptyPspsTables(): 511 539 self.logger.errorPair("Aborting this batch", "could not create empty PSPS tables") … … 513 541 raise 514 542 543 # for P2/ST, this reads the detection tables from the CMF/SMF file(s) 544 # for OB, this imports object data from DVO 515 545 if not self.importIppTables(): 516 546 self.logger.errorPair("Aborting this batch", "could not import IPP tables") … … 529 559 530 560 if self.writeBatchManifest(): 531 if self. config.datastorePublishing:561 if self.skychunk.datastorePublishing: 532 562 533 563 # tar and zip ready for publication to datastore -
trunk/ippToPsps/jython/batchRepublisher.py
r33866 r35097 30 30 self.exitProgram("incorrect args") 31 31 32 self.datastore = Datastore(self.logger, self. config, self.ippToPspsDb)32 self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb) 33 33 self.BATCHID = int(sys.argv[2]) 34 34 … … 40 40 batchName = Batch.getNameFromID(self.BATCHID) 41 41 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) 43 43 tarballFile = Batch.getTarballFile(self.BATCHID) 44 44 … … 50 50 self.logger.infoPair("Reseting batch in database", "%d" % self.BATCHID) 51 51 self.ippToPspsDb.resetBatch(self.BATCHID) 52 self.logger.infoPair("publishing to", self. config.datastoreProduct)52 self.logger.infoPair("publishing to", self.skychunk.datastoreProduct) 53 53 Batch.publishToDatastore(self.datastore, self.BATCHID, batchName, subDir, tarballFile) 54 54 -
trunk/ippToPsps/jython/cleanup.py
r33818 r35097 26 26 super(Cleanup, self).__init__(argv) 27 27 28 self.datastore = Datastore(self.logger, self. config, self.ippToPspsDb)28 self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb) 29 29 self.dxlayer = DXLayer(self.logger) 30 30 if len(argv) > 2: self.parsePollTimeArg(sys.argv[2]) … … 40 40 41 41 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() 44 44 self.clean("IN") 45 45 self.clean("P2") … … 89 89 90 90 # delete stuff from local disk 91 if self. config.deleteLocal:91 if self.skychunk.deleteLocal: 92 92 count = 0 93 93 for id in deleteFromLocalIDs: 94 94 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): 96 96 self.ippToPspsDb.updateDeletedLocal(id, 1) 97 97 count = count + 1 … … 100 100 101 101 # remove stuff from datastore 102 if self. config.deleteDatastore:102 if self.skychunk.deleteDatastore: 103 103 count = 0 104 104 for id in deleteFromDatastoreIDs: … … 112 112 113 113 # remove stuff from DXLayer 114 if self. config.deleteDxLayer:114 if self.skychunk.deleteDxLayer: 115 115 count = 0 116 116 for id in deleteFromDxLayerIDs: -
trunk/ippToPsps/jython/config.py
r33728 r35097 1 1 #!/usr/bin/env jython 2 2 3 import sys 4 import os 3 5 import logging 4 6 from xml.etree.ElementTree import ElementTree, Element, tostring … … 6 8 from pslogger import PSLogger 7 9 8 9 10 ''' 10 A class encapsulating a ippToPsps configuration. This information is stored in the 'config' table11 of the ipptopsps database, but there are some higher level config details in the 'settings.xml' file 11 A class encapsulating the globald ippToPsps configuration information. 12 This is stored in the 'settings.xml' file in the config directory 12 13 ''' 13 14 class Config(object): 14 15 15 16 16 ''' … … 19 19 Basically reads the entire config and stores values to class variables 20 20 ''' 21 def __init__(self , programName, name):21 def __init__(self): 22 22 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 26 55 self.logger = None 27 56 28 57 self.settingsDoc = ElementTree(file=self.settingsPath) 29 58 self.logPath = self.settingsDoc.find("logPath").text 30 self.czarPlotsPath = self.settingsDoc.find("czarPlotsPath").text31 59 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 68 65 69 66 ''' … … 72 69 def getLogger(self, host, pid, stdout=1, sendToFile=0): 73 70 71 print "get Logger: ", host, pid 74 72 logging.setLoggerClass(PSLogger) 73 print "done Logger 1" 75 74 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" 77 81 78 82 return self.logger 79 80 '''81 Prints the currently set DVO info82 '''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 pass90 91 '''92 Prints datastore info93 '''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 pass103 104 '''105 Prints the current deletion policy106 '''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 pass115 116 '''117 Prints the currently set RA/Dec bounding box118 '''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 pass127 128 83 129 84 ''' … … 134 89 def getDbUser(self, dbType): return self.settingsDoc.find(dbType +"/user").text 135 90 def getDbPassword(self, dbType): return self.settingsDoc.find(dbType +"/password").text 136 -
trunk/ippToPsps/jython/console.py
r33729 r35097 37 37 38 38 self.frame = JFrame( 39 "ippToPsps console for config '" + self.config.name + "'",39 "ippToPsps console for skychunk '" + self.skychunk.name + "'", 40 40 layout=BorderLayout(), 41 41 size=(1000, 500), … … 74 74 button = JButton('Purge dead', actionPerformed=self.purgeDead) 75 75 buttonPanel.add(button) 76 button = JButton('Change config', actionPerformed=self.changeConfig)76 button = JButton('Change skychunk', actionPerformed=self.changeSkychunk) 77 77 buttonPanel.add(button) 78 78 … … 136 136 self.ippToPspsDb.purgeDeadClients() 137 137 self.refreshClientTable(None) 138 def change Config(self, event):138 def changeSkychunk(self, event): 139 139 ids = self.getSelectedIds() 140 140 if len(ids) < 1: 141 141 JOptionPane.showMessageDialog(None, "No clients selected", "Error", JOptionPane.ERROR_MESSAGE) 142 142 return 143 comboBox = JComboBox(self.ippToPspsDb.getActive ConfigList())143 comboBox = JComboBox(self.ippToPspsDb.getActiveSkychunkList()) 144 144 if JOptionPane.showConfirmDialog(None, 145 145 comboBox, 146 "Choose a config",146 "Choose a skychunk", 147 147 JOptionPane.OK_CANCEL_OPTION, 148 148 JOptionPane.PLAIN_MESSAGE) == JOptionPane.CANCEL_OPTION: return 149 149 150 self.ippToPspsDb.set ConfigForLoaders(comboBox.getSelectedItem(), ids)150 self.ippToPspsDb.setSkychunkForLoaders(comboBox.getSelectedItem(), ids) 151 151 self.refreshClientTable(None) 152 152 -
trunk/ippToPsps/jython/datastore.py
r33774 r35097 1 1 #!/usr/bin/env jython 2 # EAM : config -> skychunk DONE 2 3 3 4 from subprocess import call, PIPE, Popen … … 19 20 20 21 ''' 21 def __init__(self, logger, config, ippToPspsDb):22 def __init__(self, logger, skychunk, ippToPspsDb): 22 23 23 24 # setup logger 24 25 self.logger = logger 25 self. config = config26 self.skychunk = skychunk 26 27 self.ippToPspsDb = ippToPspsDb 27 28 … … 42 43 command = "dsreg --add " + name + "\ 43 44 --link --datapath " + path + "\ 44 --type " + self. config.datastoreType + "\45 --product " + self. config.datastoreProduct + "\45 --type " + self.skychunk.datastoreType + "\ 46 --product " + self.skychunk.datastoreProduct + "\ 46 47 --list " + tempFile.name 47 48 … … 75 76 --del " + name + " \ 76 77 --rm \ 77 --product " + self. config.datastoreProduct78 --product " + self.skychunk.datastoreProduct 78 79 79 80 p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE) -
trunk/ippToPsps/jython/datastoreRemover.py
r33787 r35097 24 24 self.exitProgram("incorrect args") 25 25 26 self.datastore = Datastore(self.logger, self. config, self.ippToPspsDb)26 self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb) 27 27 28 28 ''' -
trunk/ippToPsps/jython/detectionbatch.py
r34879 r35097 3 3 import os.path 4 4 import sys 5 import glob 5 6 import time 6 7 import stilts 8 7 9 from java.lang import * 8 10 from java.sql import * … … 34 36 logger, 35 37 config, 38 skychunk, 36 39 gpc1Db, 37 40 ippToPspsDb, … … 44 47 logger, 45 48 config, 49 skychunk, 46 50 gpc1Db, 47 51 ippToPspsDb, … … 72 76 self.outputFitsPath = "%s/%s" % (self.localOutPath, self.outputFitsFile) 73 77 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 85 82 86 83 #self.startX = 1 … … 89 86 #self.endY = 8 90 87 91 # get a f reprimary header values. if in test mode, then use defaults88 # get a few primary header values. if in test mode, then use defaults 92 89 if self.safeDictionaryAccessWithDefault(self.header, 'MJD-OBS', "1") == "NULL": 93 90 self.logger.errorPair("Could not get", "MJD-OBS") … … 214 211 ," + self.safeDictionaryAccess(self.header, 'PCA2X0Y2') + " \ 215 212 )" 213 214 print "frame meta sql: ", sql 215 216 216 self.scratchDb.execute(sql) 217 217 … … 219 219 self.scratchDb.updateFilterID("FrameMeta", self.filter) 220 220 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)) 222 222 223 223 ''' … … 228 228 tableName = "ImageMeta_" + ota 229 229 230 # XXX we drop the table above so it is not left behind on failure 230 231 # drop then re-create table 231 self.scratchDb.dropTable(tableName)232 # self.scratchDb.dropTable(tableName) 232 233 sql = "CREATE TABLE " + tableName + " LIKE ImageMeta" 233 234 try: self.scratchDb.execute(sql) 234 235 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 237 240 sql = "INSERT INTO " + tableName + " ( \ 238 241 frameID \ … … 299 302 ) VALUES ( \ 300 303 " + str(self.expID) + " \ 301 ," + ota[2:4]+ " \304 ," + str(ccdID) + " \ 302 305 ," + str(self.bias) + " \ 303 306 ," + str(self.biasScat) + " \ … … 366 369 self.scratchDb.updateFilterID(tableName, self.filter) 367 370 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)) 369 372 if 'NASTRO' in header: self.totalNumPhotoRef = self.totalNumPhotoRef + int(header['NASTRO']) 370 373 self.scratchDb.replaceNullsInThisColumn(tableName, "polyOrder", "0") … … 386 389 except: pass 387 390 388 # delete all detections with PSF_INST_MAG < 17.5, as decreed by Gene391 # delete all detections with PSF_INST_MAG < -17.5, as decreed by Gene 389 392 BEFORE = self.scratchDb.getRowCount(ippTableName) 390 393 #don't do this anymore … … 464 467 , '" + self.dateStr + "' \ 465 468 , 0 \ 466 , " + str(self. config.dataRelease) + "\469 , " + str(self.skychunk.dataRelease) + "\ 467 470 FROM " + ippTableName 468 471 # self.logger.info(sql) 472 469 473 self.scratchDb.execute(sql) 470 474 … … 517 521 self.scratchDb.execute(sql) 518 522 519 self.scratchDb.updateAllRows(tableName, "dataRelease", str(self. config.dataRelease))523 self.scratchDb.updateAllRows(tableName, "dataRelease", str(self.skychunk.dataRelease)) 520 524 521 525 ''' 522 526 Populates the DetectionCalib table for this OTA 523 527 ''' 524 def populateDetectionCalibTable (self, ota):528 def populateDetectionCalibTableUpdateInsert(self, ota): 525 529 526 530 tableName = "DetectionCalib_" + ota … … 562 566 WHERE a.objID = b.objID AND a.detectID = b.detectID" 563 567 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) 565 633 566 634 ''' … … 591 659 592 660 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 595 696 596 697 ''' … … 623 724 ota = "XY%d%d" % (x, y) 624 725 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 646 731 # now run DVO code to get all IDs 647 732 if not self.useFullTables: … … 651 736 # the column in PSPS 652 737 self.scratchDb.execute("ALTER TABLE DetectionCalib CHANGE dec_ `dec` double") 653 654 655 738 656 739 return True … … 675 758 extension = "XY%d%d_psf" % (x, y) 676 759 self.scratchDb.createIndex(extension, "IPP_IDET") 760 # try the test Chip 761 self.scratchDb.createIndex("Chip_psf", "IPP_IDET") 762 677 763 self.logger.infoPair("created indexes on", "IPP tables") 764 678 765 ''' 679 766 Updates provided table with DVO IDs from DVO table … … 693 780 self.scratchDb.execute(sql) 694 781 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 695 860 696 861 ''' … … 705 870 otaCount = 0 706 871 results = {} 707 totalOriginal = totalSatDet = totalNulIInstFlux = totalNullPeakFlux = totalNullObjID =totalDetections = 0872 self.totalOriginal = self.totalSatDet = self.totalNulIInstFlux = self.totalNullPeakFlux = self.totalNullObjID = self.totalDetections = 0 708 873 self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+---------------+") 709 874 self.logger.info("| OTA | Initial total | Sat Det | NULL instFlux | NULL peak ADU | NULL obj ID | Remainder |") … … 721 886 if ota not in self.imageIDs: continue 722 887 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 783 892 # print totals 784 893 self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+---------------+") 785 894 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) 792 901 self.logger.info("+-------+---------------+---------------+---------------+---------------+---------------+---------------+") 793 902 … … 830 939 def importIppTables(self, filter=""): 831 940 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" 834 944 945 # XXX EAM NOTE : this is fragile : requires PS1_V4 835 946 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" 836 947 -
trunk/ippToPsps/jython/dvo.py
r34107 r35097 33 33 34 34 ''' 35 def __init__(self, logger, config, s cratchDbName="ipptopsps_scratch"):35 def __init__(self, logger, config, skychunk, ippToPspsDb, scratchDbName=None): 36 36 37 37 # set up logging 38 38 self.logger = logger 39 39 self.config = config 40 self.skychunk = skychunk 41 self.ippToPspsDb = ippToPspsDb 40 42 41 43 # set up empty lists … … 46 48 self.regionsIngestedButOutOfDate = [] 47 49 48 # connect to the specified scratch database 50 # connect to the specified scratch database, if a name is given, otherwise use the first version 49 51 try: 50 self.scratchDb = ScratchDb(self.logger, self.config, scratchDbName)52 self.scratchDb = ScratchDb(self.logger, self.config, '1', scratchDbName) 51 53 except: raise 52 54 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 53 62 self.scratchDb.setUseFullTables(True) 54 63 55 64 # 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) 57 66 58 67 # this scratch Db either has no DVO info ingested, or a different DVO ingested. Prompt user 59 68 if not self.correctDvo: 60 69 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 + "'?") 62 71 response = raw_input("(y/n) ") 63 72 if response == "y": … … 101 110 102 111 # check if we have up-to-date version 103 path = self. config.dvoLocation + "/Photcodes.dat"112 path = self.skychunk.dvoLocation + "/Photcodes.dat" 104 113 if self.scratchDb.alreadyImportedThisDvoTable(path): 105 114 self.logger.debugPair("DVO Photcodes.dat file", "up-to-date") … … 126 135 127 136 # check if we have up-to-date version 128 path = self. config.dvoLocation + "/Images.dat"137 path = self.skychunk.dvoLocation + "/Images.dat" 129 138 if self.scratchDb.alreadyImportedThisDvoTable(path): 130 139 self.logger.debugPair("DVO Images.dat file", "up-to-date") … … 151 160 if not self.correctDvo: return False 152 161 153 path = self. config.dvoLocation + "/SkyTable.fits"162 path = self.skychunk.dvoLocation + "/SkyTable.fits" 154 163 if self.scratchDb.alreadyImportedThisDvoTable(path): 155 164 self.logger.debugPair("DVO SkyTable.fits file", "up-to-date") … … 158 167 self.logger.infoSeparator() 159 168 self.logger.infoPair("DVO SkyTable.fits file", "NOT up-to-date") 160 self.importFits( 169 170 if self.useStilts: 171 self.importFits( 161 172 path, 162 173 "R_MIN R_MAX D_MIN D_MAX INDEX NAME", 163 174 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() 164 198 165 199 self.logger.infoPair("Adding index to", self.scratchDb.dvoSkyTable) … … 168 202 169 203 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) 171 205 172 206 return True … … 231 265 paths = [] 232 266 for fileType in self.ingestFileTypes: 233 paths.append(self. config.dvoLocation + "/" + regionPath + "." + fileType)267 paths.append(self.skychunk.dvoLocation + "/" + regionPath + "." + fileType) 234 268 235 269 # check for the existence of all interested file types … … 304 338 # go no further if we've already partly ingested a different DVO 305 339 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) 307 341 return 308 342 … … 387 421 size = 0.0 388 422 for region in regions: 389 423 self.logger.infoPair("sizes for region", region) 390 424 # get combined size of all interested files 391 425 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) 393 429 394 430 return size … … 519 555 try: 520 556 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) 522 558 break 523 559 except: … … 532 568 return tableName 533 569 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 20 20 Constructor 21 21 ''' 22 def __init__(self, logger, config, s cratchDbName):22 def __init__(self, logger, config, skychunk, ippToPspsDb, scratchDbName): 23 23 24 super(DvoDetections, self).__init__(logger, config, s cratchDbName)24 super(DvoDetections, self).__init__(logger, config, skychunk, ippToPspsDb, scratchDbName) 25 25 26 26 # declare DVO file types of interest … … 32 32 def ingestRegion(self, region): 33 33 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" 36 36 37 37 cpmTableName = self.scratchDb.getDbFriendlyTableName(region + ".cpm") … … 83 83 # first try to add the new columns. catch failure and continue 84 84 try: 85 sql = "ALTER TABLE " + cpmTableName + " ADD COLUMN (PSPS_OBJ_ID BIGINT), (ZP REAL), (RA FLOAT), (DECFLOAT)"85 sql = "ALTER TABLE " + cpmTableName + " ADD COLUMN (PSPS_OBJ_ID BIGINT), ADD COLUMN (ZP REAL), ADD COLUMN (RA FLOAT), ADD COLUMN (DEC_ FLOAT)" 86 86 self.scratchDb.execute(sql) 87 87 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) 89 91 90 92 # shove PSPS objIDs from cpt table and the calibrated zero point and coordinates which are formed 91 93 # 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" 101 106 107 # EAM : add some debug I/O 108 # self.logger.infoPair("sql command", sql) 102 109 self.scratchDb.execute(sql) 103 110 … … 136 143 ,POW(10.0, 0.4 * M_TIME) \ 137 144 ,RA \ 138 ,DEC \145 ,DEC_ \ 139 146 ,X_CCD_ERR*PLTSCALE \ 140 147 ,Y_CCD_ERR*PLTSCALE \ 141 148 , " + str(fileId) + " \ 142 149 FROM " + cpmTableName 150 151 # print "sql :", sql 152 # response = raw_input("prepare to insert dvoDetectionTable ") 143 153 144 154 try: … … 148 158 return False 149 159 finally: 160 # response = raw_input("insert dvoDetectionTable ") 150 161 self.logger.infoPair("Dropping tables", "%s and %s" % (cpmTableName, cptTableName)) 151 162 self.scratchDb.dropTable(cpmTableName) … … 155 166 156 167 return True 157 158 -
trunk/ippToPsps/jython/dvoobjects.py
r33675 r35097 8 8 import logging 9 9 import glob 10 from subprocess import call, PIPE, Popen 10 11 11 12 from dvo import Dvo 12 13 13 14 14 ''' … … 20 20 Constructor 21 21 ''' 22 def __init__(self, logger, config, s cratchDbName=None):22 def __init__(self, logger, config, skychunk, ippToPspsDb, scratchDbName=None): 23 23 24 super(DvoObjects, self).__init__(logger, config, s cratchDbName)24 super(DvoObjects, self).__init__(logger, config, skychunk, ippToPspsDb, scratchDbName) 25 25 26 26 # declare DVO file types of interest … … 37 37 for fileType in self.ingestFileTypes: 38 38 39 path = self. config.dvoLocation + "/" + region + "." + fileType39 path = self.skychunk.dvoLocation + "/" + region + "." + fileType 40 40 tableName = self.scratchDb.getDbFriendlyTableName(region + "." + fileType) 41 41 … … 47 47 48 48 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 137 137 138 138 # 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) 140 140 if match: 141 141 -
trunk/ippToPsps/jython/gpc1db.py
r34884 r35097 21 21 ''' 22 22 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) 24 30 25 31 ''' … … 93 99 94 100 try: 101 # XXX EAM : test output 102 self.logger.infoPair("sql for dvo items:", sql) 95 103 rs = self.executeQuery(sql) 96 104 while (rs.next()): … … 112 120 self.logger.debug("Querying GPC1 for image IDs for stack ID: " + str(stackID)) 113 121 122 # JOIN stackInputSkyfile shoule use stack_id as well as warp_id, right? (maybe not -- the join to warp is first) 114 123 sql = "SELECT DISTINCT CONCAT(exp_id, SUBSTR(class_id, 3, 4)) FROM ( \ 115 124 SELECT DISTINCT exp_id,class_id \ … … 226 235 if path.startswith("neb"): 227 236 237 # XXX EAM : this should just use the name (path.smf) instead of a wildcard, right? 228 238 f=os.popen("neb-ls -p "+path+"%smf") 229 239 for i in f.readlines(): … … 234 244 files = glob.glob(path + ".smf") 235 245 246 # XXX EAM : test output 247 self.logger.infoPair("smf files:", files) 236 248 if len(files) < 1: return None 237 249 … … 290 302 291 303 304 # print "staring stack stage cmf" 305 292 306 # get single path base for the directory containing all cmf files, one of which is hopefully for our stack_id 293 307 try: 294 308 rs = self.executeQuery(sql) 295 309 rs.first() 310 except: 311 self.logger.errorPair("Can't query for stack cmfs", "stack_id = %d" % stackID) 312 return None 313 314 try: 296 315 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): 297 341 298 342 # 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 333 375 334 376 ''' -
trunk/ippToPsps/jython/initbatch.py
r33727 r35097 28 28 logger, 29 29 config, 30 skychunk, 30 31 gpc1Db, 31 32 ippToPspsDb, … … 34 35 super(InitBatch, self).__init__(logger, 35 36 config, 37 skychunk, 36 38 gpc1Db, 37 39 ippToPspsDb, -
trunk/ippToPsps/jython/ipptopsps.py
r33790 r35097 1 1 #!/usr/bin/env jython 2 # EAM : config -> skychunk DONE 2 3 3 4 import signal … … 9 10 10 11 from config import Config 12 from skychunk import Skychunk 11 13 from pslogger import PSLogger 12 14 from ipptopspsdb import IppToPspsDb … … 23 25 def __init__(self, argv, logToStdout=1, logToFile=0): 24 26 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 26 31 if len(sys.argv) < 2: 27 32 self.printUsage() 28 33 self.exitProgram("Wrong args") 29 34 30 35 # some class constants 31 self.PROGNAME = sys.argv[0]32 CONFIGNAME = sys.argv[1]33 36 self.HOST = socket.gethostname() 34 37 self.PID = os.getpid() … … 38 41 self.SECONDS = None 39 42 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) 46 44 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) 50 47 51 48 # create connection to databases database 52 49 try: 53 self.ippToPspsDb = IppToPspsDb(self.logger, self.config )50 self.ippToPspsDb = IppToPspsDb(self.logger, self.config, self.skychunk) 54 51 except: 55 52 self.exitProgram("Could not connect to ipptopsps Db") … … 63 60 # title for log 64 61 self.logger.infoSeparator() 65 self.logger.infoTitle("ippToPsps '" + self. PROGNAME+ "' started")62 self.logger.infoTitle("ippToPsps '" + self.config.programName + "' started") 66 63 self.logger.infoPair("Host", self.HOST) 67 64 self.logger.infoPair("PID", "%d" % self.PID) 68 self.logger.infoPair(" Config", self.config.name)65 self.logger.infoPair("Skychunk", self.skychunk.name) 69 66 70 67 ''' … … 104 101 105 102 # write message to log or stdout if no logger set up 106 msg = sys.argv[0] + " < configName|all|edit> " + extra103 msg = sys.argv[0] + " <skychunkName|all|edit> " + extra 107 104 try: 108 105 self.logger.errorPair("Usage:", msg) … … 111 108 112 109 ''' 113 Refreshes the configthen recreates objects with new settings110 Refreshes the skychunk then recreates objects with new settings 114 111 ''' 115 def refresh Config(self):112 def refreshSkychunk(self): 116 113 117 # new config?118 if self. createNewConfig:119 self.ippToPspsDb.edit Config()120 self.ippToPspsDb.set ConfigForThisClient(self.config.name, self.HOST, self.PID)121 self. createNewConfig= False114 # 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 122 119 123 # if we are rotating configs, then look for next active one in list124 if self. rotateConfigs:125 self.ippToPspsDb.get ConfigForThisClient(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() 127 124 128 125 i = 1 129 for config in configs:130 if config == self.config.name: break126 for skychunk in skychunks: 127 if skychunk == self.skychunk.name: break 131 128 i += 1 132 129 133 if i >= len( configs): newConfig = configs[0]134 else: new Config = configs[i]130 if i >= len(skychunks): newSkychunk = skychunks[0] 131 else: newSkychunk = skychunks[i] 135 132 136 self.ippToPspsDb.set ConfigForThisClient(newConfig, self.HOST, self.PID)133 self.ippToPspsDb.setSkychunkForThisClient(newSkychunk, self.HOST, self.PID) 137 134 138 return self.ippToPspsDb.read Config(self.HOST, self.PID)135 return self.ippToPspsDb.readSkychunk(self.HOST, self.PID) 139 136 140 137 ''' 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 configdata138 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 142 139 ''' 143 140 def checkClientStatus(self): 144 141 145 self.ippToPspsDb.updateClient(self. PROGNAME, self.HOST, self.PID)142 self.ippToPspsDb.updateClient(self.config.programName, self.HOST, self.PID) 146 143 147 144 if self.ippToPspsDb.isKilled(self.HOST, self.PID): 148 145 self.exitProgram("killed via Db") 149 146 150 # this loop pauses the process if we have no configor we have set it to pause147 # this loop pauses the process if we have no skychunk or we have set it to pause 151 148 firstTimeIn = True 152 while not self.refresh Config() or self.ippToPspsDb.isPaused(self.HOST, self.PID):149 while not self.refreshSkychunk() or self.ippToPspsDb.isPaused(self.HOST, self.PID): 153 150 154 self.ippToPspsDb.updateClient(self. PROGNAME, self.HOST, self.PID)151 self.ippToPspsDb.updateClient(self.config.programName, self.HOST, self.PID) 155 152 if self.ippToPspsDb.isKilled(self.HOST, self.PID): 156 153 self.exitProgram("killed while paused") … … 175 172 # write message to log or stdout if no logger set up 176 173 try: 177 self.logger.infoPair(self. PROGNAME+ " exited", exitReason)174 self.logger.infoPair(self.config.programName + " exited", exitReason) 178 175 except: 179 176 print "*** Program exited: " + exitReason … … 186 183 187 184 sys.exit(0) 188 189 -
trunk/ippToPsps/jython/ipptopspsdb.py
r34661 r35097 17 17 Constructor 18 18 ''' 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 21 27 22 28 self.MAX_FAILS = 5 … … 29 35 sql = "SELECT DISTINCT batch_id \ 30 36 FROM batch \ 31 WHERE timestamp > '" + self. config.epoch + "' \37 WHERE timestamp > '" + self.skychunk.epoch + "' \ 32 38 AND batch_type = '" + batchType + "' \ 33 AND dvo_db = '" + self. config.dvoLabel + "' \39 AND dvo_db = '" + self.skychunk.dvoLabel + "' \ 34 40 AND merged = 1 \ 35 41 AND " + column + " = 0" … … 54 60 sql = "SELECT DISTINCT batch_id \ 55 61 FROM batch \ 56 WHERE timestamp > '" + self. config.epoch + "' \62 WHERE timestamp > '" + self.skychunk.epoch + "' \ 57 63 AND batch_type = '" + batchType + "' \ 58 AND dvo_db = '" + self. config.dvoLabel + "' \64 AND dvo_db = '" + self.skychunk.dvoLabel + "' \ 59 65 AND purged = 1 \ 60 66 AND " + column + " = 0" … … 80 86 sql = "SELECT DISTINCT batch_id \ 81 87 FROM batch \ 82 WHERE timestamp > '" + self. config.epoch + "' \88 WHERE timestamp > '" + self.skychunk.epoch + "' \ 83 89 AND batch_type = '" + batchType + "' \ 84 AND dvo_db = '" + self. config.dvoLabel + "' \90 AND dvo_db = '" + self.skychunk.dvoLabel + "' \ 85 91 AND (loaded_to_ODM = -1 OR merge_worthy = 1) \ 86 92 AND " + column + " = 0" … … 148 154 sql = "SELECT DISTINCT batch_id \ 149 155 FROM batch \ 150 WHERE timestamp > '" + self. config.epoch + "' \156 WHERE timestamp > '" + self.skychunk.epoch + "' \ 151 157 AND batch_type = '" + batchType + "' \ 152 AND dvo_db = '" + self. config.dvoLabel + "' \158 AND dvo_db = '" + self.skychunk.dvoLabel + "' \ 153 159 AND processed = 1\ 154 160 AND loaded_to_datastore != 1 \ … … 177 183 sql = "SELECT batch_id \ 178 184 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 + "' \ 181 187 AND loaded_to_datastore = 1 \ 182 188 AND batch_type = '" + batchType + "' \ … … 206 212 sql = "SELECT batch_id \ 207 213 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 + "' \ 210 216 AND loaded_to_datastore = 1 \ 211 217 AND batch_type = '" + batchType + "' \ … … 235 241 sql = "SELECT batch_id \ 236 242 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 + "' \ 239 245 AND merge_worthy = 1 \ 240 246 AND batch_type = '" + batchType + "' \ … … 262 268 sql = "SELECT DISTINCT batch_id \ 263 269 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 + "' \ 266 272 AND " + column + " = " + str(value) 267 273 … … 288 294 FROM batch \ 289 295 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 + "' \ 292 298 AND processed = 1 \ 293 299 AND loaded_to_datastore = 1 \ … … 315 321 FROM batch \ 316 322 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 + "' \ 319 325 AND " + column + " = " + str(value) 320 326 … … 387 393 WHERE batch_type = '" + batchType + "' \ 388 394 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 + "' \ 391 397 AND timestamp BETWEEN now() - INTERVAL " + interval + " AND now()" 392 398 … … 412 418 WHERE batch_type = '" + batchType + "' \ 413 419 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 + "' \ 416 422 ORDER BY timestamp DESC LIMIT 1" 417 423 … … 511 517 WHERE stage_id = " + str(stage_id) + " \ 512 518 AND batch_type = '" + batchType + "' \ 513 AND dvo_db = '" + self. config.dvoLabel + "' \519 AND dvo_db = '" + self.skychunk.dvoLabel + "' \ 514 520 AND batch_type != 'IN' \ 515 521 AND timestamp BETWEEN now() - INTERVAL 12 HOUR AND now()" … … 554 560 WHERE stage_id = " + str(stage_id) + " \ 555 561 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 + "' \ 558 564 AND batch_type != 'IN' \ 559 565 AND processed = 1" … … 579 585 WHERE stage_id = " + str(stage_id) + " \ 580 586 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 + "' \ 583 589 AND processed = -1" 584 590 … … 602 608 FROM batch \ 603 609 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 + "' \ 606 612 AND processed = -1 \ 607 613 GROUP BY stage_id HAVING numoccur >= " + str(self.MAX_FAILS) … … 634 640 batchID = -1; 635 641 636 if self. config.force or \642 if self.skychunk.force or \ 637 643 (not self.alreadyProcessed(batchType, stageID) \ 638 644 and not self.processingNow(batchType, stageID) \ … … 650 656 '" + batchType + "', \ 651 657 " + 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 + "' \ 655 661 )" 656 662 self.logger.infoPair("heather:","sql") … … 749 755 750 756 ''' 751 Sets the configfield for this client752 ''' 753 def set ConfigForThisClient(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 + "' \ 756 762 WHERE host = '" + host + "' \ 757 763 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): 762 769 763 770 for id in ids: 764 self.execute("UPDATE clients SET config = '" + config+ "' \771 self.execute("UPDATE clients SET skychunk = '" + skychunk + "' \ 765 772 WHERE type = 'loader.py' \ 766 773 AND id = " + str(id)) … … 796 803 ''' 797 804 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 + "')") 799 806 800 807 ''' … … 831 838 try: 832 839 rs = self.executeQuery(sql) 833 rs.first()840 if rs.first() is False: return False 834 841 if rs.getInt(1) == 1: return True 835 842 else: return False … … 840 847 841 848 ''' 842 Returns a list of available configs843 ''' 844 def getActive ConfigList(self):849 Returns a list of available skychunks 850 ''' 851 def getActiveSkychunkList(self): 845 852 846 sql = "SELECT DISTINCT name FROM configWHERE 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 confignames", 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) 854 861 finally: 855 862 rs.close() 856 863 857 return configs858 859 ''' 860 Prompts user for info about a new or existing configand lets them neter the various details861 ''' 862 def edit Config(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): 863 870 864 871 print " ********************************************************************" 865 print " * Configeditor"872 print " * Skychunk editor" 866 873 print " *" 867 response = raw_input(" * Name for new config, or existing configto edit? ")874 response = raw_input(" * Name for new skychunk, or existing skychunk to edit? ") 868 875 if response == "": return 869 self. config.name = response870 871 # attempt to insert new config, if it already exists then carry on with update872 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 + "')" 873 880 try: 874 881 self.execute(sql) 875 882 except: pass 876 883 877 # for each column in the configtable878 sql = "SHOW COLUMNS FROM config"884 # for each column in the skychunk table 885 sql = "SHOW COLUMNS FROM skychunk" 879 886 rs = self.executeQuery(sql) 880 887 while (rs.next()): … … 887 894 if field == 'timestamp': continue 888 895 if field == 'name': continue 896 if field == 'ingested_det': continue 897 if field == 'ingested_obj': continue 889 898 890 899 # get current value for this field, if any 891 900 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 + "'") 893 902 rs2.first() 894 903 default = rs2.getString(1) … … 907 916 if type.find("varchar") != -1 or type.find("timestamp") != -1: quotes = "'" 908 917 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 + "'") 910 919 911 920 print " *" … … 913 922 914 923 ''' 915 Returns configfor this client916 ''' 917 def get ConfigForThisClient(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 \ 920 929 FROM clients \ 921 930 WHERE host = '" + host + "' \ … … 925 934 rs = self.executeQuery(sql) 926 935 rs.first() 927 self. config.name = rs.getString(1)928 except: 929 self.logger.errorPair("No configset for", "%s (pid=%d)" % (host, pid))930 self. config.isLoaded = False936 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 931 940 return False 932 941 … … 934 943 935 944 ''' 936 Reads config from the database and populates Configobject937 ''' 938 def read Config(self, host, pid):939 940 # first get configdefined for this client941 if not self.get ConfigForThisClient(host, pid): return False942 943 # now load that config945 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 944 953 sql = "SELECT \ 945 954 datastore_product \ … … 964 973 ,queue_ST \ 965 974 ,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 972 983 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 = True976 else: self. config.datastorePublishing = False977 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) 978 989 979 990 # 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 1010 1030 1011 1031 ''' … … 1015 1035 1016 1036 sql = "SELECT id FROM box \ 1017 WHERE config = '" + self.config.name + "' \1037 WHERE skychunk = '" + self.skychunk.name + "' \ 1018 1038 AND ra_center = " + str(ra) + " \ 1019 1039 AND dec_center = " + str(dec) + " \ 1020 AND box_side = " + str(self. config.boxSize)1040 AND box_side = " + str(self.skychunk.boxSize) 1021 1041 1022 1042 id = -1 … … 1034 1054 ''' 1035 1055 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 + "'") 1037 1057 1038 1058 ''' … … 1047 1067 1048 1068 sql = "INSERT INTO box \ 1049 ( config, ra_center, dec_center, box_side) \1069 (skychunk, ra_center, dec_center, box_side) \ 1050 1070 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) + ")" 1052 1072 1053 1073 self.execute(sql) … … 1055 1075 1056 1076 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 1057 1121 1058 1122 ''' … … 1088 1152 FROM box \ 1089 1153 JOIN pending ON (id = box_id) \ 1090 WHERE config = '" + self.config.name + "' \1154 WHERE skychunk = '" + self.skychunk.name + "' \ 1091 1155 AND batch_type = '" + batchType + "' \ 1092 1156 AND ra_center NOT IN \ 1093 1157 (SELECT ra_center \ 1094 1158 FROM stripe \ 1095 WHERE config = '" + self.config.name + "') \1159 WHERE skychunk = '" + self.skychunk.name + "') \ 1096 1160 GROUP BY ra_center LIMIT 1" 1161 1162 # XXX print "sql: ", sql 1097 1163 1098 1164 try: … … 1106 1172 FROM box \ 1107 1173 JOIN pending ON (id = box_id) \ 1108 WHERE config = '" + self.config.name + "' \1174 WHERE skychunk = '" + self.skychunk.name + "' \ 1109 1175 AND batch_type = '" + batchType + "' \ 1110 1176 GROUP BY ra_center \ … … 1126 1192 WHERE ra_center = " + str(raCenter) + " \ 1127 1193 AND batch_type = '" + batchType + "' \ 1128 AND config = '" + self.config.name + "' \1194 AND skychunk = '" + self.skychunk.name + "' \ 1129 1195 ORDER BY dec_center DESC" 1130 1196 … … 1159 1225 # now insert new stripe entry 1160 1226 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) + " \ 1163 1229 FROM clients \ 1164 1230 WHERE host = '" + host + "' \ … … 1188 1254 1189 1255 ''' 1190 Returns ids for pending items for this config1256 Returns ids for pending items for this skychunk 1191 1257 ''' 1192 1258 def getPendingIds(self, batchType): … … 1195 1261 FROM pending \ 1196 1262 JOIN box ON (box_id = id) \ 1197 WHERE config = '" + self.config.name + "' \1263 WHERE skychunk = '" + self.skychunk.name + "' \ 1198 1264 AND batch_type = '" + batchType + "'" 1199 1265 … … 1204 1270 rs.close() 1205 1271 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) 1207 1273 1208 1274 return ids … … 1235 1301 WHERE stage_id = " + str(stageID) + " \ 1236 1302 AND batch_type = '" + batchType + "' \ 1237 AND config = '" + self.config.name + "'"1303 AND skychunk = '" + self.skychunk.name + "'" 1238 1304 1239 1305 self.execute(sql) 1240 1306 1241 1307 ''' 1242 Writes density-plot data to file for pending stuff over sky for given config1308 Writes density-plot data to file for pending stuff over sky for given skychunk 1243 1309 ''' 1244 1310 def createPendingDensityPlotData(self, batchType, DATFILE): … … 1246 1312 sql = "SELECT id, ra_center, dec_center \ 1247 1313 FROM box \ 1248 WHERE config = '" + self.config.name + "' \1314 WHERE skychunk = '" + self.skychunk.name + "' \ 1249 1315 ORDER BY ra_center, dec_center" 1250 1316 … … 1299 1365 def getItemsInThisThisBox(self, ra, dec): 1300 1366 1301 halfSide = self. config.boxSize/2.01367 halfSide = self.skychunk.boxSize/2.0 1302 1368 minRa = ra-halfSide 1303 1369 maxRa = ra+halfSide … … 1328 1394 FROM stripe \ 1329 1395 JOIN clients ON (client_id = id) \ 1330 WHERE clients. config = '" + self.config.name + "' \1396 WHERE clients.skychunk = '" + self.skychunk.name + "' \ 1331 1397 ORDER BY host, started" 1332 1398 -
trunk/ippToPsps/jython/loader.py
r34661 r35097 34 34 super(Loader, self).__init__(argv, 1, 1) 35 35 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 37 42 self.gpc1Db = Gpc1Db(self.logger, self.config) 38 43 39 44 # connect to scratch database 40 scratchDbs = [' ipptopsps_scratch', 'ipptopsps_scratch2', 'ipptopsps_scratch3']41 for db Namein scratchDbs:42 self.scratchDb = ScratchDb(self.logger, self.config, db Name)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) 45 50 self.scratchDb.disconnect() 46 51 continue … … 52 57 53 58 # create Datastore objects 54 self.datastore = Datastore(self.logger, self. config, self.ippToPspsDb)59 self.datastore = Datastore(self.logger, self.skychunk, self.ippToPspsDb) 55 60 56 61 # if an IN batch is requested, create and quit … … 60 65 batch = InitBatch(self.logger, 61 66 self.config, 67 self.skychunk, 62 68 self.gpc1Db, 63 69 self.ippToPspsDb, … … 72 78 73 79 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 74 85 # set a poll time of about 1 minute 75 86 self.parsePollTimeArg("0.0166") 76 87 77 self. config.printAll()88 self.skychunk.printAll() 78 89 79 90 ''' 80 91 Overrides base-class version so we can ensure our scratch Db is using the right DVO Db 81 92 ''' 82 def refresh Config(self):83 84 ret = super(Loader, self).refresh Config()93 def refreshSkychunk(self): 94 95 ret = super(Loader, self).refreshSkychunk() 85 96 try: self.scratchDb 86 97 except: return ret 87 98 88 self.dvoDetections = DvoDetections(self.logger, self.config, self.s cratchDb.dbName)99 self.dvoDetections = DvoDetections(self.logger, self.config, self.skychunk, self.ippToPspsDb, self.scratchDb.dbName) 89 100 90 101 return ret 91 102 92 103 ''' 93 Overrides base_class version so we can break out of processing loops if the configchanges104 Overrides base_class version so we can break out of processing loops if the skychunk changes 94 105 ''' 95 106 def checkClientStatus(self): 96 107 97 old ConfigName = self.config.name108 oldSkychunkName = self.skychunk.name 98 109 super(Loader, self).checkClientStatus() 99 if old ConfigName != 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() 102 113 return False 103 114 … … 115 126 116 127 abort = False 117 for batchType in self. config.batchTypes:128 for batchType in self.skychunk.batchTypes: 118 129 119 130 # get a stripe's worth of box IDs … … 141 152 ids = self.ippToPspsDb.getPendingIdsForThisBox(boxId, batchType) 142 153 154 # ids are the stage_ids for items to be processed (eg, stack_id for a stack CMF, cam_id for P2 smf) 155 143 156 if len(ids) < 1: 144 157 self.logger.debugPair("No " + batchType + " items found in this box", "skipping") … … 149 162 self.logger.infoPair("Box dimensions", "%.1f / %.1f / %.1f" % (boxDim['RA'], boxDim['DEC'], boxDim['SIDE'])) 150 163 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'] 152 166 self.logger.infoPair("got here", "ok") 153 167 useFullTables = 0 154 168 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 170 202 useFullTables = 1 171 203 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 ''' 172 214 self.logger.infoBool("Using pre-ingested DVO data?", useFullTables) 173 215 if not self.processTheseItems(batchType, ids, useFullTables): … … 175 217 break 176 218 self.logger.infoPair("processed","ok") 219 177 220 if abort or not self.checkClientStatus(): abort = True 178 221 elif numAttempts > 1 and not self.waitForPollTime(): break 179 222 223 if self.onePassOnly: self.exitProgram("one pass completed") 180 224 181 225 ''' … … 210 254 batch = DetectionBatch(self.logger, 211 255 self.config, 256 self.skychunk, 212 257 self.gpc1Db, 213 258 self.ippToPspsDb, … … 219 264 batch = StackBatch(self.logger, 220 265 self.config, 266 self.skychunk, 221 267 self.gpc1Db, 222 268 self.ippToPspsDb, … … 229 275 batch = ObjectBatch(self.logger, 230 276 self.config, 277 self.skychunk, 231 278 self.gpc1Db, 232 279 self.ippToPspsDb, … … 260 307 ''' 261 308 def printUsage(self): 262 super( Cleanup, self).printUsage("<[init]>")309 super(Loader, self).printUsage("<[init]>") 263 310 264 311 -
trunk/ippToPsps/jython/objectbatch.py
r34834 r35097 32 32 logger, 33 33 config, 34 skychunk, 34 35 gpc1Db, 35 36 ippToPspsDb, … … 42 43 logger, 43 44 config, 45 skychunk, 44 46 gpc1Db, 45 47 ippToPspsDb, … … 52 54 53 55 try: 54 self.dvoObjects = DvoObjects(self.logger, self.config, self.s cratchDb.dbName)56 self.dvoObjects = DvoObjects(self.logger, self.config, self.skychunk, self.ippToPspsDb, self.scratchDb.dbName) 55 57 except: 56 58 self.logger.errorPair("Unable to create instance of", "DvoObjects") … … 71 73 self.region = self.scratchDb.getRegionNameFromThisDvoIndex(self.id) 72 74 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) 74 79 75 80 return True … … 261 266 ,PSF_QF_PERF \ 262 267 ,STARGAL_SEP \ 263 , " + str(self. config.dataRelease) + "\268 , " + str(self.skychunk.dataRelease) + "\ 264 269 , RAND() \ 265 270 FROM " + cptTableName -
trunk/ippToPsps/jython/plot.py
r34165 r35097 15 15 Constructor 16 16 ''' 17 def __init__(self, logger, config, ippToPspsDb):17 def __init__(self, logger, skychunk, ippToPspsDb): 18 18 19 19 self.logger = logger 20 self. config = config20 self.skychunk = skychunk 21 21 self.ippToPspsDb = ippToPspsDb 22 22 23 23 ''' 24 Creates a density plot of pending exposures for this config24 Creates a density plot of pending exposures for this skychunk 25 25 ''' 26 26 def createDensityPlot(self, batchType, forCzartool=False): 27 27 28 tempFilename = "./" + self. config.name + "_" + batchType + "_plotData.dat"28 tempFilename = "./" + self.skychunk.name + "_" + batchType + "_plotData.dat" 29 29 DATFILE = open(tempFilename,'w') 30 30 max = self.ippToPspsDb.createPendingDensityPlotData(batchType, DATFILE) … … 36 36 37 37 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" 39 40 else: 40 OUTPUTFILE = self. config.name + "_" + batchType + "_" + timestamp + ".png"41 OUTPUTFILE = self.skychunk.name + "_" + batchType + "_" + timestamp + ".png" 41 42 42 43 f = os.popen('/home/panstarrs/ipp/local/bin/gnuplot', 'w') … … 49 50 print >> f, "set term " + TERM + "; \ 50 51 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 + "\"; \ 52 53 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) + "]; \ 55 56 unset key; \ 56 57 set palette rgb 22,13,10; \ -
trunk/ippToPsps/jython/plotter.py
r33787 r35097 18 18 super(Plotter, self).__init__(argv) 19 19 20 self.plot = Plot(self.logger, self. config, self.ippToPspsDb)20 self.plot = Plot(self.logger, self.skychunk, self.ippToPspsDb) 21 21 22 22 if len(argv) < 3: -
trunk/ippToPsps/jython/pollOdm.py
r33787 r35097 9 9 10 10 from ipptopsps import IppToPsps 11 from config import Config11 from skychunk import Skychunk 12 12 from odm import Odm 13 13 from batch import Batch … … 56 56 57 57 self.logger.infoSeparator() 58 self.logger.infoPair(" Config", self.config.name)58 self.logger.infoPair("Skychunk", self.skychunk.name) 59 59 60 60 for stage in self.stages: -
trunk/ippToPsps/jython/pslogger.py
r33349 r35097 11 11 This will default to stout and no file output 12 12 ''' 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): 14 14 15 15 formatter = logging.Formatter('%(asctime)s | %(levelname)7s | %(message)s', '%Y-%m-%d %H:%M:%S') … … 21 21 PATH = basePath + "/log" 22 22 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" 24 24 # opens file to be appended 25 25 hdlr = logging.FileHandler(FULLPATH, "a") -
trunk/ippToPsps/jython/queue.py
r33787 r35097 29 29 # create various objects 30 30 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 32 33 try: 33 self.dvoObjects = DvoObjects(self.logger, self.config )34 self.dvoObjects = DvoObjects(self.logger, self.config, self.skychunk, self.ippToPspsDb) 34 35 except: 35 36 self.exitProgram("Unable to create instance of DvoObject") 36 37 raise 37 38 38 self. config.printAll()39 self.skychunk.printAll() 39 40 40 41 if len(argv) > 2: self.parsePollTimeArg(sys.argv[2]) 41 42 42 43 43 ''' 44 44 Main processing loop. 45 Tiled area is defined in configand looks for available stage_ids for each tile and writes them to ippToPsps database ready for processing45 Tiled area is defined in 'skychunk' and looks for available stage_ids for each tile and writes them to ippToPsps database ready for processing 46 46 by one or more loading clients that may be running on any host 47 47 ''' … … 54 54 55 55 # 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: 57 57 58 58 self.logger.infoTitle("Previous failed datastore loads") … … 64 64 65 65 # 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 66 67 if batchType == "OB": 67 68 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) 72 73 rows = self.dvoObjects.allPopulatedRegionInfo 73 74 self.dvoObjects.printSummary() … … 76 77 else: 77 78 rows = self.gpc1Db.getItemsInThisDVODbForThisStage( 78 self. config.dvoLabel,79 self.skychunk.dvoLabel, 79 80 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)) 84 88 85 89 # first report total stuff … … 104 108 self.ippToPspsDb.storeAllItems(pending) 105 109 106 # loop through full range of RA/Dec queueing stuff in boxes of size self. config.boxSize110 # loop through full range of RA/Dec queueing stuff in boxes of size self.skychunk.boxSize 107 111 if len(ids) > 0: 108 112 … … 112 116 113 117 # starting positions 114 ra = self. config.minRa + self.config.halfBox115 dec = self. config.minDec + self.config.halfBox118 ra = self.skychunk.minRa + self.skychunk.halfBox 119 dec = self.skychunk.minDec + self.skychunk.halfBox 116 120 117 while ra <= self. config.maxRa:118 while dec <= self. config.maxDec:121 while ra <= self.skychunk.maxRa: 122 while dec <= self.skychunk.maxDec: 119 123 120 124 box_id = self.ippToPspsDb.insertBox(ra, dec) … … 125 129 ra, 126 130 dec, 127 self. config.boxSize,131 self.skychunk.boxSize, 128 132 len(ids))) 129 133 130 134 if len(ids) > 0: self.ippToPspsDb.insertPending(box_id, batchType, ids) 131 135 132 dec = dec + self. config.boxSize133 dec = self. config.minDec + self.config.halfBox134 ra = ra + self. config.boxSize136 dec = dec + self.skychunk.boxSize 137 dec = self.skychunk.minDec + self.skychunk.halfBox 138 ra = ra + self.skychunk.boxSize 135 139 136 140 self.logger.info("+-------------+-------------+-------------+-------------+") … … 150 154 151 155 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) 153 157 tarballFile = Batch.getTarballFile(batchID) 154 158 self.logger.infoPair("Batch name", batchName) -
trunk/ippToPsps/jython/scratchdb.py
r34638 r35097 19 19 Constructor 20 20 ''' 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) 23 34 24 35 self.dvoDoneTable = "dvoDone" … … 340 351 rs.first() 341 352 if rs.getInt(1) < 50: 353 # print "bad astromety" 342 354 self.logger.debug("Bad astrometric solution for", ota) 343 355 return False 344 356 else: 357 # print "good astromety" 345 358 return True 346 359 except: 360 # print "query failed" 347 361 self.logger.debug("Unable to check astrometric solution") 362 return False 348 363 349 364 return True … … 355 370 def createDvoTables(self): 356 371 372 dvoImagesTable = "dvoImages" 373 dvoDetectionTable = "dvoDetections" 374 357 375 # 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 360 379 try: self.execute(sql) 361 380 except: pass 362 381 363 sql = "CREATE TABLE " + self.dvoImagesTable + " ( \382 sql = "CREATE TABLE " + dvoImagesTable + " ( \ 364 383 SOURCE_ID SMALLINT, \ 365 384 IMAGE_ID INT, \ … … 375 394 376 395 # now detection table 377 self.logger.debugPair("Creating DVO table", self.dvoDetectionTable)378 sql = "DROP TABLE " + self.dvoDetectionTable396 self.logger.debugPair("Creating DVO table", dvoDetectionTable) 397 sql = "DROP TABLE " + dvoDetectionTable 379 398 try: self.execute(sql) 380 399 except: pass … … 396 415 raErr REAL, \ 397 416 decErr REAL, \ 398 PRIMARY KEY (imageID, ippDetectID) \ 399 )" 417 PRIMARY KEY (imageID, ippDetectID), \ 418 KEY (objID, detectID) \ 419 )" 400 420 401 421 try: self.execute(sql) 402 422 except: 403 423 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") 405 427 406 428 ''' … … 479 501 self.createIndex(self.dvoDetectionTable, "fileID") 480 502 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 \ 483 507 ADD CONSTRAINT fk_fileID \ 484 508 FOREIGN KEY (fileID) \ 485 509 REFERENCES dvoDone(id) \ 486 510 ON DELETE CASCADE" 487 try: self.execute(sql)488 except:489 self.logger.errorPair("Unable to create foreign key on", self.dvoDoneTable)490 return False511 try: self.execute(sql) 512 except: 513 self.logger.errorPair("Unable to create foreign key on", self.dvoDoneTable) 514 return False 491 515 492 516 return True -
trunk/ippToPsps/jython/setupScratchDb.py
r33787 r35097 2 2 3 3 import sys 4 import os 5 import socket 4 6 import stilts 5 7 from java.lang import * 6 8 from java.sql import * 7 9 8 9 from ipptopsps import IppToPsps 10 from config import Config 10 11 from scratchdb import ScratchDb 12 from ipptopspsdb import IppToPspsDb 11 13 12 14 ''' 13 15 SetupScratchDb class 14 16 ''' 15 class SetupScratchDb(IppToPsps): 17 class 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 16 51 17 52 ''' … … 19 54 ''' 20 55 def __init__(self, argv): 21 super(SetupScratchDb, self).__init__(argv) 56 # set up config object 57 self.config = Config() 22 58 23 if len(argv) < 3:59 if len(argv) < 2: 24 60 self.printUsage() 25 61 self.exitProgram("incorrect args") 26 62 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 27 71 try: 28 self.scratchDb = ScratchDb(self.logger, self.config, argv[ 2])72 self.scratchDb = ScratchDb(self.logger, self.config, argv[1]) 29 73 except: 30 74 self.exitProgram("Could not connect to a scratch Db") 31 75 raise 32 33 76 34 77 def run(self): … … 42 85 # install IN tables 43 86 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 45 90 for table in tables: 91 # EAM TEST I/O 92 self.logger.infoPair("Creating IN table: ", table.name) 46 93 self.logger.debug("Creating IN table: " + table.name) 47 94 table.write(self.scratchDb.url + '#' + table.name) 48 95 49 ''' 50 Overrides base-class version 51 ''' 96 # create basic DVO tables 97 self.logger.infoPair("Installing", "initialization tables") 98 self.scratchDb.createDvoTables() 99 52 100 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 54 107 55 108 ''' … … 61 114 setupScratchDb.exitProgram("completed") 62 115 except: pass 63 64 -
trunk/ippToPsps/jython/stackbatch.py
r34879 r35097 2 2 3 3 import os.path 4 import glob 4 5 import sys 5 6 … … 32 33 logger, 33 34 config, 35 skychunk, 34 36 gpc1Db, 35 37 ippToPspsDb, … … 42 44 logger, 43 45 config, 46 skychunk, 44 47 gpc1Db, 45 48 ippToPspsDb, … … 48 51 batchID, 49 52 "ST", 50 gpc1Db.getStackStageCmf( config.dvoLabel, stackID),53 gpc1Db.getStackStageCmf(skychunk.dvoLabel, stackID), 51 54 useFullTables) 55 56 # self.printline = 0 57 # # self.testprint() 52 58 53 59 self.stackType = "DEEP_STACK" # TODO … … 63 69 self.filterID = self.scratchDb.getFilterID(self.filter) 64 70 self.skycell = meta[1]; 71 72 # self.testprint() 65 73 66 74 # skycell is, eg "skycell.1133.081" … … 76 84 self.skycell = self.skycell[8:12] 77 85 self.projectioncell = self.skycell 86 87 # self.testprint() 78 88 79 89 # proposed new values. Need to coordinate with the SkyCell table … … 96 106 self.scratchDb.dropTable("StackDetectionCalib") 97 107 108 # self.testprint() 109 98 110 # delete IPP tables 99 111 self.scratchDb.dropTable("SkyChip_psf") … … 115 127 if not self.useFullTables: 116 128 self.scratchDb.insertNewDvoExternID(self.header['SOURCEID'], self.header['IMAGEID']) 129 130 # self.testprint() 117 131 118 132 # dump stuff to log … … 139 153 self.scratchDb.execute(sql) 140 154 155 156 def testprint(self): 157 print "here ", self.printline 158 self.printline += 1 141 159 142 160 ''' … … 348 366 self.logger.infoPair("Procesing table", "StackMeta") 349 367 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 350 378 sql = "INSERT INTO StackMeta (\ 351 379 stackMetaID \ … … 375 403 ," + self.header['FPA.ZP'] + " \ 376 404 ," + 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) + " \ 380 408 ,'" + self.header['CTYPE1'] + "' \ 381 409 ,'" + self.header['CTYPE2'] + "' \ … … 395 423 self.scratchDb.updateAllRows("StackMeta", "surveyID", str(self.surveyID)) 396 424 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)) 398 426 self.updateStackTypeID("StackMeta") 399 427 … … 486 514 ," + self.historyModNum + " \ 487 515 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 490 522 #it is possible to drop some detections from dvo (that are present in the cmf). when that happens we get a 0 for objid 491 523 #we drop those... … … 498 530 self.scratchDb.updateFilterID("StackDetection", self.filter) 499 531 500 self.scratchDb.updateAllRows("StackDetection", "dataRelease", str(self. config.dataRelease))532 self.scratchDb.updateAllRows("StackDetection", "dataRelease", str(self.skychunk.dataRelease)) 501 533 502 534 self.scratchDb.updateAllRows("StackDetection", "primaryF", "0") … … 509 541 510 542 self.updateDvoIDsAndFlags("StackDetection") 543 # response = raw_input("updated dvo ") 511 544 512 545 sql = "ALTER IGNORE TABLE StackDetection ADD PRIMARY KEY (objID)" 513 546 514 547 self.scratchDb.execute(sql) 548 # response = raw_input("add primary key? ") 515 549 516 550 if self.stackType == "DEEP_STACK": … … 524 558 525 559 self.scratchDb.execute(sql) 560 # response = raw_input("add psf flux ") 526 561 527 562 #leave null instflux in … … 529 564 530 565 self.scratchDb.reportAndDeleteRowsWithNULLS("StackDetection", "objID") 566 # response = raw_input("delete nulls ") 531 567 532 568 sql="DELETE FROM StackDetection where objID = 0" 533 569 534 570 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 ") 536 573 537 574 … … 577 614 self.scratchDb.updateAllRows("StackApFlx", "surveyID", str(self.surveyID)) 578 615 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)) 580 617 self.scratchDb.updateAllRows("StackApFlx", "primaryF", "0") 581 618 self.scratchDb.updateAllRows("StackApFlx", "activeFlag", "0") … … 611 648 self.scratchDb.updateAllRows("StackModelFit", "surveyID", str(self.surveyID)) 612 649 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)) 614 651 self.scratchDb.updateAllRows("StackModelFit", "primaryF", "0") 615 652 self.scratchDb.updateAllRows("StackModelFit", "activeFlag", "0") … … 676 713 677 714 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)) 679 716 680 717 ''' 681 718 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): 684 723 self.logger.infoPair("Processing table", "StackDetectionCalib") 685 724 tableName = "StackDetectionCalib" … … 702 741 FROM StackDetection" 703 742 self.scratchDb.execute(sql) 743 744 imageID = self.scratchDb.getImageIDFromExternID(self.header['IMAGEID']) 745 self.logger.infoPair("obtained","imageID") 746 704 747 # insert calibration information from dvoDetections into the Table 705 748 sql = "UPDATE " + tableName + " AS a, " + self.scratchDb.dvoDetectionTable + " AS b \ … … 712 755 a.expTime = b.expTime, \ 713 756 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)) 720 817 721 818 ''' … … 737 834 738 835 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)) 740 837 741 838 … … 802 899 WHERE a.ippDetectID = b.ippDetectID \ 803 900 AND b.imageID = " + str(imageID) 901 902 # print "update dvo sql: ", sql 903 # response = raw_input("update dvo...") 804 904 self.scratchDb.execute(sql) 805 905
Note:
See TracChangeset
for help on using the changeset viewer.
