Model Builder geoprocessing example - Extent Of Selected Features

1919
2
11-19-2016 01:17 PM

Model Builder geoprocessing example - Extent Of Selected Features

The following Python function returns the extent of selected features as a string.

There may be other ways to do this, but I think this a nice example of using the arcpy geometry object!

import arcpy

def extent_of_selected(lyr):
    """Return the extent of all selected features in a feature layer (as text)"""
    x0, y0, x1, y1 = 1e99, 1e99, -1e99, -1e99
    ext = None
    with arcpy.da.SearchCursor(lyr, "SHAPE@") as rows:
        for row in rows:
            ext = row[0].extent
            x0 = min(x0, ext.XMin)
            y0 = min(y0, ext.YMin)
            x1 = max(x1, ext.XMax)
            y1 = max(y1, ext.YMax)
    if ext:
        ext = "{} {} {} {}".format(x0, y0, x1, y1)
    else:
        ext = arcpy.Describe(lyr).Extent
        ext = "{} {} {} {}".format(ext.XMin, ext.YMin, ext.XMax, ext.YMax)
    return ext‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Python example

arcpy.SelectLayerByAttribures("wells", "", "DEPTH > 100")
arcpy.env.extent = extent_of_selected("wells")
arcpy.SelectLayerByAttribures("wells", "CLEAR_SELECTION")
# the following will copy all features in the extent of depth > 100 wells
arcpy.CopyFeatures_management("wells", "wells1")‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Model Builder example

The attached toolbox demonstrates how this function can be used in Model Builder. The model tool is called Extent Of Selected and takes a feature layer as input.  (Model Builder is the main reason I set up the Python function to return a text representation of extent instead of an extent object -- the text rep is easily represented as a model element which can then be connected to a tool as in the example below.)

extent of selected tool model builder example

Attachments
Comments

Curtis Price‌ this is an issue I come across regularly in model builder, especially when raster processing. I have my own approach but I suspect yours is faster! Anyway it struck me that this would be a useful tool on the ESRI code sharing website? Currently it is buried away here inside geonet and I don't think easily discovered. With a bit of metadata added and a description of it's intend use I think this would be a very useful addition to the code sharing website. Just an idea?

It saved me a tonnes of time when I used it in iterations through selecting areas in a deep learning project. Well done, thanks. 

Version history
Last update:
‎12-12-2021 03:46 AM
Updated by: