def load_coordinate_row(self, feature): id = self.getID(feature) locations = self.getLocationList(feature) if (feature == None or id == None): self.stderr.write("missing id or locations") return # For current zone, load coordinates zone = Zone() zone.name = feature["id"] zone.zone_type = feature["properties"]["Name"] zone_center = GeoUtils().getCentroid(locations) zone.center_lat = zone_center[1] zone.center_lon = zone_center[0] zone.save() print("**** created zone:", zone) for lat_lon in locations: lat = lat_lon[0] lon = lat_lon[1] coordinate = \ Coordinate(name=zone, lat=lat, lon=lon) coordinate.save() print("added", coordinate)
def main(): # print "reade ntuple for file ", sys.arg[1] # print "read geometry from file ", sys.argv[2] # ntuple = HGCalNtuple(sys.argv[1]) # planes = GeoUtils.read_planes(sys.argv[2]) # for plane in planes: # print_geo(ntuple, plane) print "read geometry from file: ", "fullgeometry_.txt" print "reading planes" planes = GeoUtils.read_planes("fullgeometry_.txt") c = TCanvas() mg = TMultiGraph() cells = planes[0].cells for cell in cells: x = array("d", cell.coordinates.vertices[:, 0]) x.append(x[0]) y = array("d", cell.coordinates.vertices[:, 1]) y.append(y[0]) gi = TGraph(len(x), x, y) gi.SetMarkerStyle(1) mg.Add(gi, "AL") # mg.Draw("AL") mg.Draw("A") c.Draw() c.SaveAs("hex0.png")
def processGEview(bbox,ge_key): # Get current user's information DBhandle.setUser(ge_key) user = DBhandle.ConnUserName() # Import shelving and datetime modules import shelve from datetime import datetime, timedelta # Get BBOX boundaries west = float(bbox[0]) east = float(bbox[2]) north = float(bbox[3]) south = float(bbox[1]) # If large view, create small square view at center if abs(east-west) > 30 or abs(north-south) > 30: center_lng = ((east - west) / 2) + west center_lat = ((north - south) / 2) + south west = center_lng - 0.2 east = center_lng + 0.2 north = center_lat + 0.2 south = center_lat - 0.2 # Create bounding polygon boundingPoly = GeoUtils.makeBoundingPolygon(north,south,east,west) # KML Header kml_output = '<Folder id="ConnUserViewInfo">\n' kml_output += '<styleUrl>%s/kml_styles.py#check-hide-children</styleUrl>\n' % (BASE_URL,) kml_output += '<name>Connected User View Information</name><open>0</open><visibility>1</visibility>\n' # Open persistent object storage s = shelve.open('realtimeGEuserview.db', writeback=True) try: if not 'liveview' in s: s.update(liveview={}) s['liveview'][user] = { 'timestamp' : datetime.now(), 'view' : boundingPoly } for u in s['liveview'].keys(): if s['liveview'][u]['timestamp'] + timedelta(minutes = 5) < datetime.now(): del s['liveview'][u] elif u == "visitor": continue else: if not s['liveview'][u]['view'] == boundingPoly: kml_output += createViewPoly(u, s['liveview'][u]) finally: s.close() # KML footer kml_output += '</Folder>\n' return kml_output
def visible(p, points, q, T, S): if points.index(q) == 0: ant_point = None else: ant_point = points[points.index(q) - 1] for poly in S: if q in poly.vertices: for edge in poly.edges: if GeoUtils.edge_intersect(p, q, edge): return False elif ant_point == None or not GeoUtils.is_on(p, ant_point, q): for edge in poly.edges: found = T.min_item() == edge if found and GeoUtils.edge_intersect(p, q, edge): return False else: return True elif not visible(p, points, ant_point, T, S): return False else: for edge in T: if GeoUtils.edge_intersect(p, q, edge): return False else: return True
def visible_vertices(p, S, start, goal): #NAIVE: V = getAllVertices(S) V.append(start) V.append(goal) V.remove(p) W = [] for point in V: visible = True for poly in S: for edge in poly.edges: if p not in edge and point not in edge: #the two vertexs of the same edge can see each other, disjoint polygons if GeoUtils.edge_intersect(p, point, edge): visible = False if p in poly.vertices and point in poly.vertices: if GeoUtils.midpoint_in_polygon([p, point], poly): visible = False else: for poly2 in S: if GeoUtils.midpoint_in_polygon([p, point], poly2): visible = False if visible: W.append(point) return W
def visibility_graph(S, start, goal): V = getAllVertices(S) V.append(start) V.append(goal) E = [] for v in V: W = visible_vertices(v, S, start, goal) for w in W: E.append((v, w)) Gvis = Graph() for v in V: Gvis.addVertex(v) for e in E: Gvis.addEdge(e[0], e[1]) cost = GeoUtils.euclidean_distance(e[0], e[1]) Gvis.addCost((e[0], e[1]), cost) return Gvis
def visibility_graph(S, start, goal): V = getAllVertices(S) V.append(start) V.append(goal) E = [] for v in V: W = visible_vertices(v, S, start, goal) for w in W: E.append((v, w)) Gvis = Graph() for v in V: Gvis.addVertex(v) for e in E: Gvis.addEdge(e[0], e[1]) cost = GeoUtils.euclidean_distance(e[0],e[1]) Gvis.addCost((e[0], e[1]), cost) return Gvis
def KMLout(bbox=["-74.4","40.4","-73.5","40.9"],ge_key=""): # Dictionary of KML Styles associated with type noteStatusStyle = { "Caution" : 'noteCaution', "Sticky" : 'noteSticky', "Info" : 'noteInfo', "Hidden" : 'noteHidden' } # Get BBOX boundaries west = bbox[0] east = bbox[2] north = bbox[3] south = bbox[1] # Database query dbq = "SELECT ID,attribution,details,status,visible,AsText(feature_geometry) FROM notes WHERE MBRIntersects(PolyFromText('%s'),feature_geometry) AND visible=1" \ % (GeoUtils.makeBoundingPolygon(north,south,east,west),) # Query database dbdata,rowcount = DBhandle.query(dbq) # Close database DBhandle.close() if rowcount > 0: # Folder contents import operator FolderContents = reduce(operator.concat,[GeoUtils.Interface.genKML.InterfaceNotePlacemark(ge_key,noteStatusStyle,r) for r in dbdata]) else: FolderContents = '' # Folder details FolderID = 'UserNotes' FolderName = 'User Notes' FolderStyle = '%s/kml_styles.py#check-hide-children' % (BASE_URL,) FolderOpen = 0 FolderVisibility = 1 # Create output kml_output = GeoUtils.Interface.genKML.Folder(id=FolderID,name=FolderName,open=FolderOpen,visibility=FolderVisibility,contents=FolderContents) # Return KML output return kml_output
def makeNetwork(pid,w=1,h=1,eq=GeoUtils.constants.Equations.BMASW,elev_data=GeoUtils.constants.ElevSrc.DEFAULT30SEC): ''' Create network from elevation grid Parameters: @param pid - port ID @param w - grid width in degrees (default: 1) @param h - grid height in degrees (default: 1) @param eq - design equation as constant in GeoUtils.constants.Equations (default: SUPERSLR Minimum-Criteria Dike Design) @param elevdata - elevation data to use for grid as constant in GeoUtils.constants.ElevSrc (default: 30-second SRTM30Plus) ''' # Query database for port details portq = "SELECT ID,name,latitude,longitude FROM portdata WHERE ID='%s'" % (pid,) portdata,portrowcount = DBhandle.query(portq) # If not only one port returned from database, raise error if portrowcount == 0 or portrowcount > 1: # Return error errtxt = "There was an error while retrieving the port data. <br/><br/>\n" errtxt += "Please report this error to %s " % (GeoUtils.constants.contactEmail,) errtxt += "including the following information: " errtxt += "Port ID - %s, Number of ports - %s" % (pid,portrowcount) # Return error text and error # Function exits return errtxt,True # Get port latitude and longitude port_lat = float(portdata[0]['latitude']) port_lon = float(portdata[0]['longitude']) # Determine bounding box for area of interest surrounding port west = float(port_lon) - float(w) / 2 east = float(port_lon) + float(w) / 2 north = float(port_lat) + float(h) / 2 south = float(port_lat) - float(h) / 2 # Create bounding polygon syntax for SQL boundingPoly = "PolyFromText('%s')" % (GeoUtils.makeBoundingPolygon(north,south,east,west),) # Query database for associated port polygons polyq = "SELECT ID,AsText(feature_geometry) FROM current_features WHERE " polyq += "(feature_type = 'Port Infrastructure Polygon' OR feature_type = 'Model Avoid Polygon') " polyq += "AND MBRIntersects(%s,feature_geometry)" % (boundingPoly,) polydata,polyrowcount = DBhandle.query(polyq) # Query database for associated port polygons seq = "SELECT ID,AsText(feature_geometry) FROM current_features WHERE " seq += "feature_type = 'Model StartEnd Polygon' " seq += "AND MBRIntersects(%s,feature_geometry)" % (boundingPoly,) sedata,serowcount = DBhandle.query(seq) # Query database for elevation grid elevq = "SELECT longitude,latitude,elevation FROM elev_data WHERE " elevq += "longitude <= %s AND longitude >= %s AND latitude <= %s AND latitude >= %s AND source='%s' ORDER BY latitude, longitude ASC" % \ (east,west,north,south,elev_data) #elevdata,elevrowcount = elevDBhandle.query(elevq) elevdata,elevrowcount = DBhandle.query(elevq) # If there are results from the database, process elevation grid if elevrowcount == 0: # Return error message errtxt = "There was an error while retrieving the elevation grid. " errtxt += "The elevation data may not currently be loaded in the database. <br/><br/>" errtxt += "Please report this error to %s " % (GeoUtils.constants.contactEmail,) errtxt += "along with the following information: Port ID - %s" % (pid,) # Return error text and error # Function exits return errtxt,True # Import design cost functions import designs # Dictionary of possible cross-section equations eqns = { GeoUtils.constants.Equations.BMASW : designs.pieceByPiece, GeoUtils.constants.Equations.SMCDD : designs.SMCDD } # Query database for global parameters gpq = "SELECT * FROM modelparameters WHERE eqn = '%s'" % (eq,) gpdata,gprowcount = DBhandle.query(gpq) # Query database for local parameters lpq = "SELECT mean_low_low_tide,mean_high_high_tide,storm_surge,design_wave_height " lpq += "FROM portdata WHERE ID = '%s'" % (pid,) lpdata,lprowcount = DBhandle.query(lpq) # Process global parameters database result # If more than one record returned or no records returned, raise error if gprowcount == 0 or gprowcount > 1: # Return error errtxt = "There was an error while retrieving the global port protector parameters.<br/><br/>y\n" errtxt += "Please report this error to %s, " % (GeoUtils.constants.contactEmail,) errtxt += "including the information below.\n\n" errtxt += "Port ID: %s\n" % (pid,) errtxt += "Design equation: %s\n" % (eq,) errtxt += "Number of global parameter rows: %s\n" % (gprowcount,) errtxt += "Number of local parameter rows: %s\n" % (lprowcount,) # Return error text and error # Function exits return errtxt,True # Set parameters to global values params = gpdata[0] # Only work with localized parameters if only one set is returned if lprowcount == 1: # Search for localized parameters, if exists and different from global value, # set parameter to localized value for i in params: if not lpdata[0].has_key(i) or lpdata[0][i] == "-9999" or lpdata[0][i] == -9999 or lpdata[0][i] == params[i]: continue else: params[i] = lpdata[0][i] # Get initial point initPt = GeoUtils.Features.Point(x=float(elevdata[0]['longitude']),y=float(elevdata[0]['latitude']),elev=float(elevdata[0]['elevation'])) # Select elevation grid size based on elevation data source dr = GeoUtils.constants.ElevSize.get(elev_data) # Get local distance between points distDiffInit = initPt.distanceFrom(GeoUtils.Features.Point(x=initPt.lon+dr,y=initPt.lat+dr)) # Dictionary for grid vertices grid = {} for r in elevdata: # Create new Point based on database record curPt = GeoUtils.Features.Point(x=float(r['longitude']),y=float(r['latitude']),elev=float(r['elevation'])) # Get metric distances from initial point distCurInit = curPt.distanceFrom(initPt) # Convert to integer coordinates on grid IntCoordX = int(round(distCurInit["horiz"] / distDiffInit["horiz"],0)) IntCoordY = int(round(distCurInit["vertical"] / distDiffInit["vertical"],0)) GridCoord = (IntCoordX,IntCoordY) # Store raw metric coordinates and elevation at integer coordinate on grid grid[GridCoord] = { "latlon" : (curPt.lon,curPt.lat), "metric" : (distCurInit["horiz"],distCurInit["vertical"]), "elev" : curPt.elev } # List of keys to delete because of avoid polygons or parameter exclusion del_keys = [] # If there is one or more avoid polygons, delete vertices inside these polygons if polyrowcount > 0: # For each avoid polygon, if vertex lies within polygon, add to list of keys to be deleted for polygon in polydata: poly = GeoUtils.Features.Polygon() poly.fromMySQL_polygon(polygon['AsText(feature_geometry)']) del_keys.extend([ v for v in grid if poly.containsPoint(GeoUtils.Features.Point(x=grid[v]["latlon"][0],y=grid[v]["latlon"][1])) ]) # Add vertices excluded by parameters to delete list # Current disqualifying parameters: max_elevation, min_elevation del_keys.extend([ v for v in grid if grid[v]["elev"] > float(params['max_elevation']) or grid[v]["elev"] < float(params['min_elevation']) ]) # Delete listed keys from available vertices for v in del_keys: if v in grid: del grid[v] # Process start/end points # If two start end polygons in immediate vicinity, use these regions for starting and ending points if serowcount == 2: # Start and end polygons startpoly = GeoUtils.Features.Polygon() startpoly.fromMySQL_polygon(sedata[0]['AsText(feature_geometry)']) endpoly = GeoUtils.Features.Polygon() endpoly.fromMySQL_polygon(sedata[1]['AsText(feature_geometry)']) # Check vertices for appropriate inclusion in start and end points spts = [ v for v in grid if startpoly.containsPoint(GeoUtils.Features.Point(x=grid[v]["latlon"][0],y=grid[v]["latlon"][1])) ] epts = [ v for v in grid if endpoly.containsPoint(GeoUtils.Features.Point(x=grid[v]["latlon"][0],y=grid[v]["latlon"][1])) ] else: # Return error message errtxt = "There was an error while retrieving the starting and ending polygons.<br/><br/>\n" errtxt += "Please ensure that there are exactly two StartEnd Polygons in the prescribed grid " errtxt += "and that each polygon contains possible grid points.<br/><br/>\n" errtxt += "Please report this error to %s " % (GeoUtils.constants.contactEmail,) errtxt += "along with the following information:\n" errtxt += "Port ID - %s\n" % (pid,) errtxt += "SE Polygons returned - %s\n" % (serowcount,) # Return error text and error # Function exits return errtxt,True # Dictionary to store graph graph = {} # Create network based on vertices for vertex in grid: # Create directory for edges graph[vertex] = {} # Get grid x and y for current vertex x,y = vertex # Neighbors of current vertex neighbors = [ (x,y + 1), (x,y - 1), (x - 1,y), (x - 1,y + 1), (x - 1,y - 1), (x + 1,y), (x + 1,y + 1), (x + 1,y - 1) ] # For each neighbor, check for key and compute cost based on distance and average elevation for neighbr in neighbors: if grid.has_key(neighbr): # Calculate distance between current vertex and neighbor vertexPt = GeoUtils.Features.Point(x=grid[vertex]["latlon"][0],y=grid[vertex]["latlon"][1]) nighbrPt = GeoUtils.Features.Point(x=grid[neighbr]["latlon"][0],y=grid[neighbr]["latlon"][1]) dist = vertexPt.distanceFrom(nighbrPt) # Calculate average elevation avg_elev = (float(grid[vertex]["elev"]) + float(grid[neighbr]["elev"])) / 2 # Get cost for edge graph[vertex][neighbr] = eqns.get(eq)(dist["total"],avg_elev,params) # List of edges to delete #del_edges = [] # For each avoid polygon, if edges intersects with polygon, add to list of edges to be deleted #for polygon in polydata: # poly = GeoMySQL.poly2coords(polygon['AsText(feature_geometry)'])["outer"] # for v in graph: # for e in graph[v]: # edge = (grid[v]["latlon"],grid[e]["latlon"]) # if edgeintersectpoly(edge,poly): # del_edges.append((v,e)) # Delete listed edges from graph #for e in del_edges: # if e[0] in graph: # if e[1] in graph[e[0]]: # pass # #del graph[e[0]][e[1]] # #print e # Return graph and no error return (grid,graph,spts,epts,boundingPoly),False
def KMLout(bbox=["-74.4","40.4","-73.5","40.9"],ge_key="",type="Port Infrastructure Polygon"): # Dictionary of IDs associated with type polyIDs = { "Port Infrastructure Polygon" : 'PortInfraPoly', "Basin Polygon" : 'BasinPoly', "Model Avoid Polygon" : 'AvoidPoly', "Berm Avoid Polygon" : 'BermAvoidPoly', "Model StartEnd Polygon" : 'StartEndPoly' } # Dictionary of KML Styles associated with type polyStyles = { "Port Infrastructure Polygon" : 'portInfrastructure', "Basin Polygon" : 'basinPolygon', "Model Avoid Polygon" : 'avoidPolygon', "Berm Avoid Polygon" : 'bermAvoidPolygon', "Model StartEnd Polygon" : 'startEndPolygon' } # Dictionary of heights associated with polygon types polyHeights = { "Port Infrastructure Polygon" : 120, "Basin Polygon" : 20, "Model Avoid Polygon" : 50, "Berm Avoid Polygon" : 50, "Model StartEnd Polygon" : 75 } # Get BBOX boundaries west = bbox[0] east = bbox[2] north = bbox[3] south = bbox[1] # Database query dbq = "SELECT ID,portID,AsText(feature_geometry) FROM current_features WHERE feature_type = '%s' AND MBRIntersects(PolyFromText('%s'),feature_geometry)" % (type,GeoUtils.makeBoundingPolygon(north,south,east,west)) # Query database dbdata,rowcount = DBhandle.query(dbq) if rowcount > 0: # Folder contents import operator FolderContents = reduce(operator.concat,[GeoUtils.Interface.genKML.InterfacePortPolygon(ge_key,polyIDs.get(type),polyStyles.get(type),polyHeights.get(type,0),r) for r in dbdata]) else: FolderContents = '' # Folder details FolderID = str(polyIDs.get(type)) FolderName = '%ss' % (type,) FolderStyle = '%s/kml_styles.py#check-hide-children' % (BASE_URL,) FolderOpen = 0 FolderVisibility = 1 # Create output kml_output = GeoUtils.Interface.genKML.Folder(id=FolderID,name=FolderName,open=FolderOpen,visibility=FolderVisibility,contents=FolderContents) # Return KML output return kml_output
def KMLout(bbox=["-74.4","40.4","-73.5","40.9"],ge_key=""): # Database table information table = 'current_features' # Get BBOX boundaries west = bbox[0] east = bbox[2] north = bbox[3] south = bbox[1] # Database query dbq = "SELECT ID,portID,attribution,path_length,structure_height_above_msl, AsText(path_geometry) FROM portprotector WHERE MBRIntersects(PolyFromText('%s'),path_geometry)" % (GeoUtils.makeBoundingPolygon(north,south,east,west),) # Query database dbdata,rowcount = DBhandle.query(dbq) # Close database DBhandle.close() if rowcount > 0: # Folder contents import operator FolderContents = reduce(operator.concat,[GeoUtils.Interface.genKML.InterfacePath(ge_key,r) for r in dbdata]) else: FolderContents = '' # Folder details FolderID = 'ModelPaths' FolderName = 'Port Protector Model Paths' FolderOpen = 0 FolderVisibility = 1 FolderStyle = '%s/kml_styles.py#check-hide-children' % (BASE_URL,) # Create output kml_output = GeoUtils.Interface.genKML.Folder(id=FolderID,name=FolderName,open=FolderOpen,visibility=FolderVisibility,contents=FolderContents) # Return KML output return kml_output