def updateProjections(projection): from com.raytheon.uf.common.dataplugin.gfe.config import ProjectionData # extract projection data projFmt = ( str, "com.raytheon.uf.common.dataplugin.gfe.config.ProjectionData$ProjectionType", tuple, tuple, tuple, float, float, tuple, tuple, float, float, float) projID, ptype, pllll, pllur, pllo, pspo, pspt, pgpll, pgpur, pli, \ plc, plo = check(projection, projFmt, "Format error in Projection") check(pllll, (float, float), "Format error lower left long/lat in Projection", projection) check(pllur, (float, float), "Format error upper right long/lat in Projection", projection) check(pllo, (float, float), "Format error long/lat origin in Projection", projection) check(pgpll, (int, int), "Format error lower left grid point in Projection", projection) check(pgpur, (int, int), "Format error upper right grid point in Projection", projection) if not Projections.has_key(projID): Projections[projID] = ProjectionData(projID, ptype, Coordinate(pllll[0], pllll[1]), Coordinate(pllur[0], pllur[1]), Coordinate(pllo[0], pllo[1]), pspo, pspt, Point(pgpll[0], pgpll[1]), Point(pgpur[0], pgpur[1]), pli, plc, plo)
def testMultiPointFromJTS(self): mp = geom.MultiPoint( self.gf.createMultiPoint([ self.gf.createPoint(Coordinate(1, 2)), self.gf.createPoint(Coordinate(3, 4)) ])) self.assertEqual('MULTIPOINT ((1 2), (3 4))', str(mp))
def testMultiLineStringFromJTS(self): mls = self.gf.createMultiLineString([ self.gf.createLineString([Coordinate(1, 2), Coordinate(3, 4)]), self.gf.createLineString([Coordinate(5, 6), Coordinate(7, 8)]) ]) ml = geom.MultiLineString(mls) self.assertEqual('MULTILINESTRING ((1 2, 3 4), (5 6, 7 8))', str(ml))
def testPolygonFromJTS(self): poly = self.gf.createPolygon( self.gf.createLinearRing([ Coordinate(1, 2), Coordinate(3, 4), Coordinate(5, 6), Coordinate(1, 2) ]), []) p = geom.Polygon(poly) self.assertEqual('POLYGON ((1 2, 3 4, 5 6, 1 2))', str(p))
def __init__(self, *coord): if len(coord) == 1 and isinstance(coord[0], _Point): p = coord[0] else: c = Coordinate(coord[0], coord[1]) if len(coord) > 2: c.z = coord[2] p = geom._factory.createPoint(c) _Point.__init__(self, p.coordinateSequence, geom._factory)
def testMultiPolygonFromJTS(self): mp = geom.MultiPolygon( self.gf.createMultiPolygon([ self.gf.createPolygon( self.gf.createLinearRing([ Coordinate(1, 2), Coordinate(3, 4), Coordinate(5, 6), Coordinate(1, 2) ]), []) ])) self.assertEqual('MULTIPOLYGON (((1 2, 3 4, 5 6, 1 2)))', str(mp))
def append_to_errors(self, errorsList, check): """Clean errors list from duplicate errors and ids that must be ignored """ if errorsList[0][0] == "": #osmId == "", this tool doesn't give id of OSM objects check.errors = [Error(check, e) for e in errorsList] else: if check.ignoreIds != []: #remove OSM objects that the user wants to ignore check.errors = [Error(check, e) for e in errorsList if e[0] not in check.ignoreIds] #remove duplicate ids #check.errors = dict((e.osmId, e) for e in check.errors).values() else: #copy all errors and remove duplicate ids #check.errors = dict((e[0], Error(e)) for e in errorsList).values() check.errors = [Error(check, e) for e in errorsList] #Remove from the list of errors those that have been reviewed yet #while clicking the "Next" button check.errors = [e for e in check.errors if e.osmId not in check.reviewedIds] #print "\n- errors of selected check in current zone:", [e.osmId for e in check.errors] #Randomize the errors so that different users don't start #correcting the same errors Collections.shuffle(check.errors) #Filter errors in favourite zone if self.app.favouriteZoneStatus and self.app.favZone.zType != "rectangle": #not rectangular favourite area, use jts from com.vividsolutions.jts.geom import Coordinate, GeometryFactory polygon = self.app.favZone.wktGeom errorsInPolygon = [] for error in check.errors: (lat, lon) = error.coords point = GeometryFactory().createPoint(Coordinate(lon, lat)) if polygon.contains(point): if error not in errorsInPolygon: errorsInPolygon.append(error) check.errors = errorsInPolygon #Apply limits from preferences #max number of errors limits = [] if self.app.maxErrorsNumber != "": limits.append(self.app.maxErrorsNumber) try: if self.tool.prefs["limit"] != "": limits.append(int(self.tool.prefs["limit"])) except: pass if limits != []: check.errors = check.errors[:min(limits)] #Reset index of current error check.currentErrorIndex = -1 check.toDo = len(check.errors)
def makePoint(point): " Make a CartCoord2D from the point in format: x,y" ind = string.find(point, ",") latStr = point[0:ind - 1] lonStr = point[ind + 1:len(point)] lat = float(latStr) lon = float(lonStr) return Coordinate(lon, lat)
def makePoint(point): " Make a CartCoord2D from the point in format: x,y" from com.vividsolutions.jts.geom import Coordinate ind = string.find(point, ",") latStr = point[0:ind - 1] lonStr = point[ind + 1:len(point)] lat = float(latStr) lon = float(lonStr) return Coordinate(lon, lat)
def parseGridLocation(domain): from com.raytheon.edex.plugin.gfe.config import SimpleGridLocation #if office type is present: if len(domain) == 6: domainFmt = (list, tuple, tuple, str, tuple, str) gridSize, origin, extent, tz, proj, officeType = check( domain, domainFmt, "Format error in SITES line") #if office type is not present: else: domainFmt = (list, tuple, tuple, str, tuple) gridSize, origin, extent, tz, proj = check( domain, domainFmt, "Format error in SITES line") check(gridSize, (int, int), "GridSize format error from SITES", domain) check(origin, (float, float), "Origin format error from SITES", domain) check(extent, (float, float), "Extent format error from SITES", domain) projFmt = ( str, "com.raytheon.uf.common.dataplugin.gfe.config.ProjectionData$ProjectionType", tuple, tuple, tuple, float, float, tuple, tuple, float, float, float) projID, projType, llll, llur, llo, sp1, sp2, gpll, gpur, li, lc, lo = \ check(proj, projFmt, "Format error in Projection") check(llll, (float, float), "Format error lower left long/lat in Projection", proj) check(llur, (float, float), "Format error upper right long/lat in Projection", proj) check(llo, (float, float), "Format error long/lat origin in Projection", proj) check(gpll, (int, int), "Format error lower left grid point in Projection", proj) check(gpur, (int, int), "Format error upper right grid point in Projection", proj) gloc = SimpleGridLocation(Point(gridSize[0], gridSize[1]), Coordinate(origin[0], origin[1]), Coordinate(extent[0], extent[1]), projID, projType, Coordinate(llll[0], llll[1]), Coordinate(llur[0], llur[1]), Coordinate(llo[0], llo[1]), sp1, sp2, Point(gpll[0], gpll[1]), Point(gpur[0], gpur[1]), li, lc, lo) return gloc
def finalDraw(self, event): p = event.coords width = abs(p[0].x - p[1].x) height = abs(p[0].y - p[1].y) geo = GeometryFactory() shapeFac = GeometricShapeFactory(geo) lowLeft = Coordinate() lowLeft.x = min(p[0].x, p[1].x) lowLeft.y = min(p[0].y, p[1].y) shapeFac.setBase(lowLeft) shapeFac.setWidth(width) shapeFac.setHeight(height) shapeFac.setNumPoints(48) pa = shapeFac.createCircle().coordinates p.clear() for pt in pa: p.add(pt) panel = event.wc.layerViewPanel statMsg = "[" + panel.format(width) + ", " + panel.format(height) + "]" event.statusMessage = statMsg
def finalDraw(self, event): p = event.coords width = abs(p[0].x - p[1].x) height = abs(p[0].y - p[1].y) geo = GeometryFactory() shapeFac = GeometricShapeFactory(geo) lowLeft = Coordinate() lowLeft.x = min(p[0].x, p[1].x) lowLeft.y = min(p[0].y ,p[1].y) shapeFac.setBase(lowLeft) shapeFac.setWidth(width) shapeFac.setHeight(height) shapeFac.setNumPoints(48) pa = shapeFac.createCircle().coordinates p.clear() for pt in pa: p.add(pt) panel = event.wc.layerViewPanel statMsg = "[" + panel.format(width) + ", " + panel.format(height) + "]" event.statusMessage = statMsg
def finalDraw(self, event): p = event.coords dist = distancePointLinePerpendicular(p[2], p[0], p[1]) toLeft = computeOrientation(p[1], p[0], p[2]) == LEFT p[2] = GeoUtils.perpendicularVector(p[1], p[0], dist, toLeft) p.add(GeoUtils.vectorAdd(p[2], GeoUtils.vectorBetween(p[1], p[0]))) #p.add(CoordUtils.add(p[2], CoordUtils.subtract(p[1], p[0]) )) #jts way p.add(Coordinate(p[0])) width = p[0].distance(p[1]) length = p[1].distance(p[2]) panel = event.wc.layerViewPanel statMsg = "[" + panel.format(width) + ", " + panel.format(length) + "]" event.statusMessage = statMsg
def __init__(self, *coords): if len(coords) == 1 and isinstance(coords[0], _LineString): ls = coords[0] else: l = [] for c in coords: l.append(Coordinate(c[0], c[1])) if len(c) > 2: l[-1].z = c[2] ls = geom._factory.createLineString(l) _LineString.__init__(self, ls.coordinateSequence, geom._factory)
def __init__(self, *coords): tolerance = Double.MAX_VALUE if len(coords) == 1 and isinstance(coords[0], _CircularRing): cs = coords[0].coordinateSequence else: l = [] for c in coords: l.append(Coordinate(c[0], c[1])) if len(c) > 2: l[-1].z = c[2] cs = geom._factory.coordinateSequenceFactory.create(l) doubles = [] for c in cs.toCoordinateArray(): doubles.append(c.x) doubles.append(c.y) cgf = CurvedGeometryFactory(tolerance) _CircularRing.__init__(self, doubles, cgf, tolerance)
def _retrieveMapData(siteIDs, timeSeconds, parameters=Parameters): import JUtil from com.raytheon.uf.common.dataplugin.gfe.request import GetPointDataRequest from com.vividsolutions.jts.geom import Coordinate from com.raytheon.viz.aviation.guidance import GuidanceUtil from com.raytheon.uf.viz.core.localization import LocalizationManager gfeSiteId = LocalizationManager.getInstance().getCurrentSite() task = GetPointDataRequest() task.setSiteID(gfeSiteId) db = gfeSiteId + '_GRID__Official_00000000_0000' task.setDatabaseID(db) for siteID in siteIDs: config = AvnParser.getTafSiteCfg(siteID) lat = config['geography']['lat'] lon = config['geography']['lon'] c = Coordinate(float(lon), float(lat)) task.addCoordinate(c) task.setNumberHours(_NumHours) task.setStartTime(long(timeSeconds * 1000)) for p in parameters: task.addParameter(p) pdcs = GuidanceUtil.getGFEPointsData(task) results = {} if pdcs is None: for siteId in siteIDs: _Logger.info('Data not available for %s', siteID) results[siteID] = None return results for i, siteID in enumerate(siteIDs): data = None if i < pdcs.getSize(): pdc = pdcs.getContainer(i) data = _getData(pdc, timeSeconds * 1000) if data is None: _Logger.info('Data not available for %s', siteID) results[siteID] = data return results
def executeIscExtract(parmNames, databaseName, startTime, endTime, irtTableAddressA, irtTableAddressB, transmitScript, ourServerHost, ourServerPort, ourServerProtocol, ourMHSid, ourSiteID, destinations=None): startT = time.time() parms = parmNames dbid = databaseName startTR = startTime endTR = endTime xmlDestinations = destinations ancf = irtTableAddressA bncf = irtTableAddressB xmtScript = transmitScript serverHost = ourServerHost serverPort = ourServerPort serverProtocol = ourServerProtocol mhsid = ourMHSid siteID = ourSiteID myOfficeType = IFPServerConfigManager.getServerConfig(siteID).officeType() #-------------------------------------------------------------------- # determine the list of destination servers #-------------------------------------------------------------------- try: nowT = time.time() #current time useUntilTime = None #cached use until time cacheFilename = "/tmp/" + serverHost + serverPort + ".iscExtract" cachedXmlDestinations = None #if xmlDestinations is None: #destinations not on command line # # check the cache # try: # fd = open(cacheFilename, 'rb') # buf = fd.read() # fd.close() # useUntilTime, cachedXmlDestinations = cPickle.loads(buf) # nowT = time.time() #current time # if nowT > useUntilTime: # xmlDestinations = None #cache is too old # useUntilTime = None # else: # logEvent('Using xmlDestinations cache') # xmlDestinations = cachedXmlDestinations # except: # pass # need to contact IRT to get destinations irt = IrtAccess.IrtAccess(ancf, bncf) if xmlDestinations is None: logEvent('contacting IRT to get destinations') count = 1 while True: status, xmlDestinations = irt.getSendAddrs(siteID) logEvent('IRT getSendAddrs status:', status) if status: # if we obtained XML destinations from IRT, then decode # the useUntilTime field try: d = ElementTree.ElementTree(ElementTree.XML(xmlDestinations)) dE = d.getroot() for e in dE: if e.tag == "useuntil": isoTimeStr = e.text idx = isoTimeStr.find(".") if idx != - 1: isoTimeStr = isoTimeStr[0:idx] #eliminate subseconds useUntilTime = time.mktime(time.strptime(isoTimeStr, "%Y-%m-%dT%H:%M:%S")) logEvent("Use Until: ", isoTimeStr) except: logProblem("Malformed XML on getSendAddrs()") logProblem("XML=", xmlDestinations) return if useUntilTime is None: useUntilTime = time.time() + 180.0 #3 minutes default logEvent("Using default 180 second useUntilTime") # write the cache fd = open(cacheFilename, 'wb') buf = cPickle.dumps((useUntilTime, xmlDestinations)) fd.write(buf) fd.close() break #success from the irt else: # try again and again for 10 minutes, then use cache # if available and alert GFE users if time.time() - nowT > 600.00: logProblem("Unable to access IRT for send addrs") if cachedXmlDestinations is None: s = "Unable to access IRT for send addrs. Previous" + \ " cache not available." logProblem(s) return # use cached value, even if out of date else: xmlDestinations = cachedXmlDestinations if useUntilTime is not None: s = time.asctime(time.gmtime(useUntilTime)) else: s = "Unknown" logProblem("Using expired cache. Date=", s) #determine when we issued our last GFE alert #we alert every 30 minutes. try: fd = open(cacheFilename + "-warn", 'rb') buf = fd.read() fd.close() lastAlertTime = cPickle.loads(buf) except: lastAlertTime = 0 #for way long ago if time.time() - lastAlertTime > 1800.0: logProblem("Sending GFE notification") msg = """ Contact NCF. ifpServer is unable to contact IRT central server. ISC traffic routing information is old and possibly incorrect.""" os.system("sendGfeMessage -u -c GFE -m '" + \ msg + "'") fd = open(cacheFilename + "-warn", 'wb') fd.write(cPickle.dumps(time.time())) fd.close() break time.sleep(15.0) #sleep awhile and then try again count = count + 1 logProblem("Retrying to getSendAddrs()", count) # qc the XML try: destTree = ElementTree.ElementTree(ElementTree.XML(xmlDestinations)) destE = destTree.getroot() except: logProblem("Malformed XML on getSendAddrs() or provided xmlDest") logProblem("XML=", xmlDestinations) return #-------------------------------------------------------------------- # determine how many transmissions are necessary #-------------------------------------------------------------------- xmt = [] logEvent("XML dest:", xmlDestinations) if destE.tag != "destinations": logProblem("Destinations packet missing from web service") return # create list of individual transmissions (before attempting to combine doClip = 1 #0 to send entire domain, 1 to do destination clipping (default) destStr = "Destination Servers:\n" for addressE in destE: if addressE.tag == "doclip": for name, value in addressE.items(): if name == "clip": if value == "1": doClip = 1 elif value == "0": doClip = 0 logEvent("Clipping State: ", doClip) for addressE in destE: if addressE.tag != "address": continue # find destination server info and domain information serverInfo = irt.decodeXMLAddress(addressE) if doClip == 0: serverInfo['domain'] = None keycheckfail = False for key in ['mhsid', 'host', 'port', 'protocol', 'site']: if not serverInfo.has_key(key): logProblem("Fail to decode XML. Skipping serverInfo:", serverInfo) keycheckfail = True continue if keycheckfail: continue #skipping this destination due to insufficient info # get the destination office type try: siteIndex = IFPServerConfigManager.getServerConfig(siteID).allSites().indexOf(serverInfo['site']) destOfficeType = str(IFPServerConfigManager.getServerConfig(siteID).officeTypes().get(siteIndex)) except: logProblem("Unknown site id to get office type. ", "Skipping serverInfo:", serverInfo) continue #skipping this destination due to unknown site id # find weather elements that remote ifpServer wants # that is available in our server and in the -p parm switches any = False for parm in serverInfo['parms']: p1 = string.replace(parm, "_SFC", "") #remove _SFC if exists # translation of parm name needed, also if no office type, then # not wanted from this office. # example: changes QPFwfo to QPF if we are wfo # example: discards T if we are wfo and site is non-wfo if myOfficeType != destOfficeType: if p1.find(myOfficeType) != - 1: p1 = string.replace(p1, myOfficeType, "") #remove type else: continue #no type, so not intended for our type # see if parm was listed in the command line switches if parms.contains(p1): xmt.append({'serverInfo':[serverInfo], 'parms':[p1], 'domain': serverInfo['domain'], 'area': serverInfo['area']}) if not any: destStr += irt.printServerInfo(serverInfo) + "\n" any = True logEvent(destStr) # now combine transmissions # find same domains, same parms, to combine servers/destinations i = 0 while i < len(xmt): j = i + 1 while j < len(xmt): if xmt[i]['domain'] == xmt[j]['domain'] and \ xmt[i]['area'] == xmt[j]['area'] and \ xmt[i]['parms'] == xmt[j]['parms']: for si in xmt[j]['serverInfo']: if si not in xmt[i]['serverInfo']: dests = xmt[i]['serverInfo'] dests.append(si) xmt[j]['serverInfo'] = dests del xmt[j] #delete the entry j = j - 1 #redo this entry index next loop j = j + 1 i = i + 1 # now try to combine common parm lists (same domain, same servers/destinations) i = 0 while i < len(xmt): j = i + 1 while j < len(xmt): if xmt[i]['domain'] == xmt[j]['domain'] and \ xmt[i]['area'] == xmt[j]['area'] and \ xmt[i]['serverInfo'] == xmt[j]['serverInfo'] : iparms = xmt[i]['parms'] for p in xmt[j]['parms']: if p not in iparms: iparms.append(p) xmt[i]['parms'] = iparms del xmt[j] #delete the entry j = j - 1 #redo this entry index for next loop j = j + 1 i = i + 1 # if doClip, gather some required information if doClip: #get the isc send area and grid domain from the ifpServer iscSendAreaGrid = iscUtil.getEditArea("ISC_Send_Area",siteID) sourceDomain = IFPServerConfigManager.getServerConfig(siteID).dbDomain() iscSendAreaGrid.setGloc(sourceDomain) iscSendAreaGrid = iscSendAreaGrid.getGrid() #-------------------------------------------------------------------- # prepare output files #-------------------------------------------------------------------- for dest in xmt: s = "Processing Xmt Pass:\n" for sv in dest['serverInfo']: s += irt.printServerInfo(sv) + '\n' s += "Domain:" + `dest['domain']` + '\n' s += "Area:" + `dest['area']` + '\n' s += "Parms:" + `dest['parms']` + '\n\n' logEvent(s) # extract the data using ifpnetCDF if os.path.exists(siteConfig.GFESUITE_HOME + "/products/ISC") == False: os.makedirs(siteConfig.GFESUITE_HOME + "/products/ISC") tempfile.tempdir = siteConfig.GFESUITE_HOME + "/products/ISC" fname = tempfile.mktemp(".isc") # Determine domain edit area. if doClip == 1 and dest['domain'] is not None and \ dest['domain']['proj'] == sourceDomain.getProjection().getProjectionID(): #make a GridLocation for our domain gridSize = Coordinate(float(str(sourceDomain.getNx())), float(str(sourceDomain.getNy()))) origin = sourceDomain.getOrigin() extent = sourceDomain.getExtent() domain = CartDomain2D(origin, extent) gloc = sourceDomain #make a GridLocation covering the area for the destination, expanded #by 1/2 grid cell dd = dest['domain'] da = dest['area'] cellsizeX = float(dd['extx']) / (float(da['xdim']) - 1.0) cellsizeY = float(dd['exty']) / (float(da['ydim']) - 1.0) originD = Coordinate(float(dd['origx']) - cellsizeX / 2.0, float(dd['origy']) - cellsizeY / 2.0) extentD = Coordinate(float(dd['extx']) + cellsizeX, float(dd['exty']) + cellsizeY) domainD = CartDomain2D(originD, extentD) #check for overlap if not domainD.overlaps(domain): logEvent("No intersection of domain box, skipping....") continue #no bits set in the resulting mask, no intersect domainD.trim(domain) #trim it to just the overlapping section gridSize = Point(int(da['xdim']),int(da['ydim'])) destGridLocation = GridLocation("Dest",sourceDomain.getProjection(), gridSize,domainD.getOrigin(),domainD.getExtent(),"GMT") # make a Reference Set refid = ReferenceID("jibberish") refSet = ReferenceData(gloc, refid, destGridLocation.getGeometry(), CoordinateType.LATLON) # convert destination site's domain to gridpoints iscMask = refSet.getGrid() # "and" it with our ISC_Send_Area iscMask.andEquals(iscSendAreaGrid) if not iscMask.isAnyBitsSet(): logEvent("No intersection of domain points, skipping....") continue #no bits set in the resulting mask, no intersect # store the grid back into the ifpServer maskName = "iscExtract" + `time.time()` refSet.setGrid(iscMask) iscUtil.saveEditAreaGrid(maskName, refSet, siteID) else: #no clipping, or different projection maskName = "ISC_Send_Area" # Run ifpnetCDF for the data argv = {"outputFilename": fname, "parmList": dest['parms'], "databaseID": dbid, "startTime": startTR, "endTime": endTR, "mask": maskName, "geoInfo": False, "compressFileFlag": True, "configFileName": "iscSendSampleDef", "compressFileFactor": 6, "trim": True, "krunch": True, "userID": "iscExtract", "logFileName": None, "siteIdOverride": None} ifpnetCDF.main(**argv) fname = fname + '.gz' size = os.stat(fname)[stat.ST_SIZE] endT = time.time() logEvent('File Size: ', size) logEvent('After ifpnetCDF, ,wctime:', "%-6.2f" % (endT - startT), ',cputime:', "%-6.2f" % time.clock()) # create XML destinations file for this output iscE = Element('isc') #create the XML tree root sourceServer = {'mhsid': mhsid, 'host': serverHost, 'port': serverPort, 'protocol': serverProtocol, 'site': siteID} irt.addSourceXML(iscE, sourceServer) irt.addDestinationXML(iscE, dest['serverInfo']) #get the unique list of mhs sites mhsSites = [] for si in dest['serverInfo']: if si['mhsid'] not in mhsSites: mhsSites.append(si['mhsid']) # create the XML file fnameXML = tempfile.mktemp(".xml") fd = open(fnameXML, 'wb') fd.write(ElementTree.tostring(iscE)) fd.close() # Transmit files - do string substitution irt.transmitFiles("ISCGRIDS2", mhsSites, mhsid, [fname,fnameXML], xmtScript) # Delete temporary files if maskName != "ISC_Send_Area": iscUtil.deleteEditArea(maskName,siteID) endT = time.time() logEvent('After transmission pass, ,wctime:', "%-6.2f" % (endT - startT), ',cputime:', "%-6.2f" % time.clock()) except: logProblem("Failure", traceback.format_exc())
def filter(self, coordinate): global _xDisp, _yDisp displacement = Coordinate(_xDisp, _yDisp) coordinate.setCoordinate(CoordUtil.add(coordinate, displacement))
def testPointFromJTS(self): p = geom.Point(self.gf.createPoint(Coordinate(1, 2))) self.assertEqual('POINT (1 2)', str(p))
def testLineStringFromJTS(self): ls = self.gf.createLineString([Coordinate(1, 2), Coordinate(3, 4)]) l = geom.LineString(ls) self.assertEqual('LINESTRING (1 2, 3 4)', str(l))
def createParm(parminfo, domain, tc): from com.raytheon.edex.plugin.gfe.config import SimpleGridParmConfig m = "Format Error in Weather Element Definition" if len(parminfo) < 2: raise TypeError, m + ': ' + ` parminfo ` dim, origin, extent, timezone, projection, officeType = domain if parminfo[1] == 'Scalar' or parminfo[1] == 'Vector': parmInfoFmt = (str, str, str, str, float, float, int, int) name, type, units, description, max, min, precision, \ rateParm = check(parminfo, parmInfoFmt, m) elif parminfo[1] == 'Weather': name, type, units, description = \ check(parminfo, (str, str, str, str), m) max = 0 min = 0 precision = 0 rateParm = False elif parminfo[1] == 'Discrete': if len(parminfo) == 6: parmInfoFmt = (str, str, str, str, int, list) name, type, units, description, overlaps, keys = \ check(parminfo, parmInfoFmt, m) auxSize = 0 else: parmInfoFmt = (str, str, str, str, int, list, int) name, type, units, description, overlaps, keys, auxSize = \ check(parminfo, parmInfoFmt, m) max = 0.0 min = 0.0 precision = 0 rateParm = False parseKeys(name, overlaps, auxSize, keys) else: raise Exception, "Illegal WE type specified for " + ` parminfo[0] ` #don't add parms with your own office type in the name. if name.endswith(officeType): return None #skip this one if len(units) == 0: raise Exception, 'Unit string must not be empty. For unitless quantities enter "1"' updateProjections(projection) start, repeat, duration = tc timeIndependentParm = (repeat == 0 and duration == 0) # return WeatherElement(name, type, units, description, max, min, # precision, timeIndependentParm, dim, origin, # extent, start, repeat, duration, rateParm) return SimpleGridParmConfig(name, type, units, description, 1.0 * max, 1.0 * min, precision, timeIndependentParm, Point(dim[0], dim[1]), Coordinate(origin[0], origin[1]), Coordinate(extent[0], extent[1]), start, repeat, duration, rateParm)