コード例 #1
0
def getBoundingBoxForCatchmentsForGage(config, outputDir, reachcode, measure, deleteIntermediateFiles=True):
    """ Get bounding box coordinates (in WGS 84) for the drainage area associated with a given NHD 
        (National Hydrography Dataset) streamflow gage identified by a reach code and measure.
        
        @param config A Python ConfigParser containing the following sections and options:
            'GDAL/OGR' and option 'PATH_OF_OGR2OGR' (absolute path of ogr2ogr binary)
            'NHDPLUS2' and option 'PATH_OF_NHDPLUS2_DB' (absolute path to SQLite3 DB of NHDFlow data)
            'NHDPLUS2', 'PATH_OF_NHDPLUS2_CATCHMENT' (absolute path to NHD catchment SQLite3 spatial DB)
        @param outputDir String representing the absolute/relative path of the directory into which output rasters should be written
        @param reachcode String representing NHD streamflow gage 
        @param measure Float representing the measure along reach where Stream Gage is located 
            in percent from downstream end of the one or more NHDFlowline features that are 
            assigned to the ReachCode (see NHDPlusV21 GageLoc table)
        @param deleteIntermediateFiles A boolean, True if intermediate files generated from the analysis should be deleted
         
        @return A dictionary with keys: minX, minY, maxX, maxY, srs. The key srs is set to 'EPSG:4326' (WGS 84)
        
        @raise ConfigParser.NoSectionError
        @raise ConfigParser.NoOptionError
        @raise IOError(errno.ENOTDIR) if outputDir is not a directory
        @raise IOError(errno.EACCESS) if outputDir is not writable
    """
    nhddbPath = config.get('NHDPLUS2', 'PATH_OF_NHDPLUS2_DB')
    if not os.access(nhddbPath, os.R_OK):
        raise IOError(errno.EACCES, "The database at %s is not readable" %
                      nhddbPath)
    nhddbPath = os.path.abspath(nhddbPath)
        
    catchmentFeatureDBPath = config.get('NHDPLUS2', 'PATH_OF_NHDPLUS2_CATCHMENT')
    if not os.access(catchmentFeatureDBPath, os.R_OK):
        raise IOError(errno.EACCES, "The catchment feature DB at %s is not readable" %
                      catchmentFeatureDBPath)
    catchmentFeatureDBPath = os.path.abspath(catchmentFeatureDBPath)
    
    ogrCmdPath = config.get('GDAL/OGR', 'PATH_OF_OGR2OGR')
    if not os.access(ogrCmdPath, os.X_OK):
        raise IOError(errno.EACCES, "The ogr2ogr binary at %s is not executable" %
                      ogrCmdPath)
    ogrCmdPath = os.path.abspath(ogrCmdPath)
    
    if not os.path.isdir(outputDir):
        raise IOError(errno.ENOTDIR, "Output directory %s is not a directory" % (outputDir,))
    if not os.access(outputDir, os.W_OK):
        raise IOError(errno.EACCES, "Not allowed to write to output directory %s" % (outputDir,))
    outputDir = os.path.abspath(outputDir)
    
    # Connect to DB
    conn = sqlite3.connect(nhddbPath)
    
    comID = getComIdForStreamGage(conn, reachcode, measure)
    #sys.stderr.write("Gage with reachcode %s, measure %f has ComID %d" % (reachcode, measure, comID))
    
    # Get upstream reaches
    upstream_reaches = []
    getUpstreamReachesSQL(conn, comID, upstream_reaches)
    #sys.stderr.write("Upstream reaches: ")
    #sys.stderr.write(upstream_reaches)
    
    # Extract polygons for upstream catchments
    catchmentOut = os.path.join(outputDir, "catchment-%s.shp" % time.time())
    ogrCommand = "%s -s_srs EPSG:4326 -t_srs EPSG:4326  -f 'ESRI Shapefile' -sql 'SELECT * FROM catchment WHERE featureid=%s" % (ogrCmdPath, comID) # NHDPlusV2
    for reach in upstream_reaches:
        ogrCommand = ogrCommand + " OR featureid=%s" % reach # NHDPlusV2
    ogrCommand = ogrCommand +"' " + catchmentOut + " " + catchmentFeatureDBPath  
    #sys.stderr.write("ogr command: %s" % ogrCommand)
    os.system(ogrCommand)
    
    bbox = getBoundingBoxForShapefile(catchmentOut)
    
    # Clean-up temporary shapefile/ancillary files
    if deleteIntermediateFiles:
        deleteShapefile(catchmentOut)
    
    conn.close()

    return bbox
コード例 #2
0
parser.add_argument(
    '-b',
    '--buffer',
    dest='buffer',
    required=False,
    help='Number of WGS84 degrees by which to buffer the bounding box')
args = parser.parse_args()
cmdline = GenericMetadata.getCommandLine()

context = Context(args.projectDir, None)

buffer = 0.01
if args.buffer:
    buffer = float(args.buffer)

# Get name of study area shapefile
manifest = GenericMetadata.readManifestEntries(context)
shapefileName = manifest['study_area_shapefile']

shapefilePath = os.path.join(context.projectDir, shapefileName)
if not os.access(shapefilePath, os.R_OK):
    raise IOError(errno.EACCES, "Unable to read shapefile %s" % args.shapefile)

# Get bounding box, buffer by about 1 km
bbox = getBoundingBoxForShapefile(shapefilePath, buffer=buffer)
GenericMetadata.writeStudyAreaEntry(
    context, "bbox_wgs84",
    "%f %f %f %f" % (bbox['minX'], bbox['minY'], bbox['maxX'], bbox['maxY']))

# Write processing history
GenericMetadata.appendProcessingHistoryItem(context, cmdline)
# Handle command line options
parser = argparse.ArgumentParser(description='Get bounding box from study area shapefile')
parser.add_argument('-p', '--projectDir', dest='projectDir', required=True,
                    help='The directory to which metadata, intermediate, and final files should be saved')
parser.add_argument('-b', '--buffer', dest='buffer', required=False,
                    help='Number of WGS84 degrees by which to buffer the bounding box')
args = parser.parse_args()
cmdline = GenericMetadata.getCommandLine()

context = Context(args.projectDir, None)

buffer = 0.01
if args.buffer:
    buffer = float(args.buffer)

# Get name of study area shapefile
manifest = GenericMetadata.readManifestEntries(context)
shapefileName = manifest['study_area_shapefile']

shapefilePath = os.path.join(context.projectDir, shapefileName)
if not os.access(shapefilePath, os.R_OK):
    raise IOError(errno.EACCES, "Unable to read shapefile %s" %
                  args.shapefile)

# Get bounding box, buffer by about 1 km
bbox = getBoundingBoxForShapefile(shapefilePath, buffer=buffer)
GenericMetadata.writeStudyAreaEntry(context, "bbox_wgs84", "%f %f %f %f" % (bbox['minX'], bbox['minY'], bbox['maxX'], bbox['maxY']))

# Write processing history
GenericMetadata.appendProcessingHistoryItem(context, cmdline)
コード例 #4
0
def getBoundingBoxForCatchmentsForGage(config,
                                       outputDir,
                                       reachcode,
                                       measure,
                                       deleteIntermediateFiles=True):
    """ Get bounding box coordinates (in WGS 84) for the drainage area associated with a given NHD 
        (National Hydrography Dataset) streamflow gage identified by a reach code and measure.
        
        @param config A Python ConfigParser containing the following sections and options:
            'GDAL/OGR' and option 'PATH_OF_OGR2OGR' (absolute path of ogr2ogr binary)
            'NHDPLUS2' and option 'PATH_OF_NHDPLUS2_DB' (absolute path to SQLite3 DB of NHDFlow data)
            'NHDPLUS2', 'PATH_OF_NHDPLUS2_CATCHMENT' (absolute path to NHD catchment SQLite3 spatial DB)
        @param outputDir String representing the absolute/relative path of the directory into which output rasters should be written
        @param reachcode String representing NHD streamflow gage 
        @param measure Float representing the measure along reach where Stream Gage is located 
            in percent from downstream end of the one or more NHDFlowline features that are 
            assigned to the ReachCode (see NHDPlusV21 GageLoc table)
        @param deleteIntermediateFiles A boolean, True if intermediate files generated from the analysis should be deleted
         
        @return A dictionary with keys: minX, minY, maxX, maxY, srs. The key srs is set to 'EPSG:4326' (WGS 84)
        
        @raise ConfigParser.NoSectionError
        @raise ConfigParser.NoOptionError
        @raise IOError(errno.ENOTDIR) if outputDir is not a directory
        @raise IOError(errno.EACCESS) if outputDir is not writable
    """
    nhddbPath = config.get('NHDPLUS2', 'PATH_OF_NHDPLUS2_DB')
    if not os.access(nhddbPath, os.R_OK):
        raise IOError(errno.EACCES,
                      "The database at %s is not readable" % nhddbPath)
    nhddbPath = os.path.abspath(nhddbPath)

    catchmentFeatureDBPath = config.get('NHDPLUS2',
                                        'PATH_OF_NHDPLUS2_CATCHMENT')
    if not os.access(catchmentFeatureDBPath, os.R_OK):
        raise IOError(
            errno.EACCES, "The catchment feature DB at %s is not readable" %
            catchmentFeatureDBPath)
    catchmentFeatureDBPath = os.path.abspath(catchmentFeatureDBPath)

    ogrCmdPath = config.get('GDAL/OGR', 'PATH_OF_OGR2OGR')
    if not os.access(ogrCmdPath, os.X_OK):
        raise IOError(
            errno.EACCES,
            "The ogr2ogr binary at %s is not executable" % ogrCmdPath)
    ogrCmdPath = os.path.abspath(ogrCmdPath)

    if not os.path.isdir(outputDir):
        raise IOError(errno.ENOTDIR,
                      "Output directory %s is not a directory" % (outputDir, ))
    if not os.access(outputDir, os.W_OK):
        raise IOError(
            errno.EACCES,
            "Not allowed to write to output directory %s" % (outputDir, ))
    outputDir = os.path.abspath(outputDir)

    # Connect to DB
    conn = sqlite3.connect(nhddbPath)

    comID = getComIdForStreamGage(conn, reachcode, measure)
    #sys.stderr.write("Gage with reachcode %s, measure %f has ComID %d" % (reachcode, measure, comID))

    # Get upstream reaches
    upstream_reaches = []
    getUpstreamReachesSQL(conn, comID, upstream_reaches)
    #sys.stderr.write("Upstream reaches: ")
    #sys.stderr.write(upstream_reaches)

    # Extract polygons for upstream catchments
    catchmentOut = os.path.join(outputDir, "catchment-%s.shp" % time.time())
    ogrCommand = "%s -s_srs EPSG:4326 -t_srs EPSG:4326  -f 'ESRI Shapefile' -sql 'SELECT * FROM catchment WHERE featureid=%s" % (
        ogrCmdPath, comID)  # NHDPlusV2
    for reach in upstream_reaches:
        ogrCommand = ogrCommand + " OR featureid=%s" % reach  # NHDPlusV2
    ogrCommand = ogrCommand + "' " + catchmentOut + " " + catchmentFeatureDBPath
    #sys.stderr.write("ogr command: %s" % ogrCommand)
    os.system(ogrCommand)

    bbox = getBoundingBoxForShapefile(catchmentOut)

    # Clean-up temporary shapefile/ancillary files
    if deleteIntermediateFiles:
        deleteShapefile(catchmentOut)

    conn.close()

    return bbox