Getting g Started With Python y In ArcGIS
Dale Honeycutt David Wynne
Agenda
8:30 9:30: Python 101 and ArcPy 101
Essentials of the language U Using g ArcPy y to execute g geoprocessing p g tools Python window
9:30 9:30 10:00: Script and Script tool basics
Creating C a standalone script Creating a script tool
10:00 10:15: Map 10:00 p automation 10:15 10:45: Break 10:45 10:45 11:00: Raster analysis and Map Algebra 11:00 11:00 11:45: Tool Design and Validation
Python y 101
Why Python?
ESRI has embraced Python for ArcGIS 10 Python is the language that fulfills the needs of our user community
Easy to learn Excellent for beginners and experts Suitable S it bl for f large l projects j t or small ll scripts i t Cross Cross-platform
Python 101
Clear, easy to read syntax Easy to use, makes it simple to get started Variety of basic data types
Including lists and dictionaries
Comes with a large standard library Supports raising and catching exceptions Code can be grouped into modules and packages Supports S t objectobject bj t-oriented i t d programming i
http://www.python.org/about/
Python at 10.0 10 0
ESRI has fully embraced Python as its language for automation 1. ArcPy site site-package
Includes mapping and Map Algebra support Successor to the arcgisscripting module Python access and interaction from within ArcGIS
2. Python window 3. Python script tool framework
A brief history of Python in ArcGIS
dispatchbased Geoprocessor Python 2.1
arcgisscripting module Cross-platform Cross platform Python 2.4 arcgisscripting module, 9.3 version Pythonic Python 2.5
ArcPy y site-package p g Mapping & Map Algebra support Python window Python 2.6 26
ArcPy y 101
What is ArcPy ArcPy? ?
A cornerstone for automation in ArcGIS
data analysis data conversion data management map automation
ArcPy is a native Python sitesite-package
Access to 800 800+ geoprocessing tools Provides embedded reference documentation for each function, class and module Code completion for ArcGIS components in your favorite Python editor Familiar to arcgisscripting users
ArcPy improvements
Improved coding experience, such as:
Cursors Classes C Multi Multi-value parameters can be expressed as Python lists Ability to convert rasters to and from NumPy arrays
ArcPy is supported by modules, including:
A mapping module (arcpy.mapping (arcpy.mapping) ) A Spatial Analyst module (arcpy.sa) to support map algebra A Geostatistical Analyst module (arcpy.ga)
What is the Python window?
An embedded Interactive Python window within ArcGIS
Can access ArcPy ArcPy, , including tools and environments Can C access any y other Python y functionality, y, Better code completion and intelligence
The Python y window is for:
Testing ideas Experimenting with and learning Python Simple execution of tools Building quick and easy workflows in Python
Demo: A tour of ArcPy and the Python window
Getting more help
Desktop help
Resource Center
http://resourcesbeta.esri.com/ content/geoprocessing
Running tools
Tools are accessed as functions on arcpy Environments as properties from arcpy.env class
# ~~~ PYTHON CODE ~~~ import arcpy # Set the workspace arcpy.env.workspace = "c:/st_Johns/GISData.gdb" # Execute Geoprocessing tool arcpy.Intersect_analysis(["roads","urban_area","urban_roads", 5, , "j join")
Environments
Script writers set the environment and tools use it
General settings
Current Workspace, p Output p Spatial p Reference, Extent
Raster analysis settings
Cell Size, Mask
Many more arcpy.env.workspace arcpy.env.outputCoordinateSystem arcpy.env.extent py arcpy.env.cellSize arcpy.env.mask
Tool messages
Executing E ti a tool t l will ill produce d 3 types t of f messages.
Informative messages (severity = 0) Warning messages (severity = 1) Error messages (severity = 2)
# start try block try: arcpy.Buffer("c:/ws/roads.shp", "c:/outws/roads10.shp", 10) # If an error occurs when running a geoprocessing tool, tool # print the tool messages except arcpy.ExecuteError: print arcpy.GetMessages(2) # Any other error except Exception as e: print e.message
Functions
Functions perform useful scripting tasks
Access geoprocessing tool messages (GetMessages (GetMessages) ) List data to for batch p processing g (ListFeatureClasses (ListFeatureClasses, C , ListFields, ListFields , nine other List functions) Retrieve a datasets properties (Describe (Describe) )
import arcpy # Set the workspace for ListFeatureClasses function arcpy env workspace = "c:/test" arcpy.env.workspace c:/test # For each fc, create a scratch name and clip for fc in arcpy.ListFeatureClasses(): outName = arcpy.CreateScratchName("clipped_" + fc, "", "featureclass", arcpy.env.workspace) arcpy Clip analysis(fc "boundary" arcpy.Clip_analysis(fc, boundary , outName)
Describe
Returns an object with dynamic properties Allows script to determine properties of data
Data type (shapefile (shapefile, shapefile, coverage, coverage network dataset, dataset etc) Shape type (point, polygon, line, etc) Spatial reference Extent of f features f List of fields
Logic g can be added to a script p to branch (if ( statement) ) based data properties
Describe
# Describe a feature class d = arcpy.Describe("c:/base.gdb/rivers") # Branch based on the # inputs p ShapeType p yp p property p y if d.shapeType == "Polygon": arcpy.FeatureToLine_management(inFC, outFC) else: l arcpy.CopyFeatures_management(inFC, outFC)
Classes
Most tool parameters can be easily defined
Such as a path or buffer distance
Some parameters cannot be easily defined with a string
Such as a spatial reference or field mapping
Classes can be used to define parameters
prjFile = "c:/North America Equidistant Conic.prj" # Create a spatial reference using a projection file spatialRef = arcpy.SpatialReference(prjFile) # Run CreateFeatureclass using the spatial reference arcpy.CreateFeatureclass management(inputWorkspace, arcpy.CreateFeatureclass_management(inputWorkspace, outputName, "POLYLINE", "", "", "", spatialRef)
Cursors
Cursors allows
Iteration over the set of rows in a table Ability y to insert new rows into a table Geometry access
Cursors have three forms
Search, S Insert and Update
import arcpy # Print road name and road type for row in arcpy.SearchCursor("D:/data.gdb/roads"): print Road name: row.roadname print i t Road R d t type: row.getValue( tV l (roadtype") dt ") del row
Demo: Converting GPS in XML to useable Geographic data
A note on Cursor functions
ArcPy cursors support iteration
At 9.3
rows = gp.SearchCursor(myTable) row = rows.next() while row: print row.GetValue(Rank) row = rows.next()
At 10
for row in arcpy.SearchCursor(myTable) print row.GetValue(Rank)
Insert Cursor
Cursors support creation of new geometries
# Open an insert cursor for the feature class cur = arcpy.InsertCursor(fc) # Create array and point objects ptList = [arcpy.Point(358331, 5273193), arcpy.Point(358337, 5272830)] lineArray = arcpy.Array(ptList) # Create a new row for the feature class feat = cur.newRow() # Set the geometry of the new feature to the # array of points feat.Shape p = lineArray y # Insert the feature cur.insertRow(feat) # Delete objects del cur, feat
Creating g Python y script tools
Demo: Map automation tools
BREAK!
See you at 10:45
Raster analysis y and Map Algebra g
Raster class
Returned output from Spatial Analyst tools
Used to represent a raster dataset on disk C Can be used as inputs p to tools and Sp Spatial Analyst y Map p Algebra expressions
Supports operators (or arithmetic operations in Map Algebra expressions) Has properties and methods for analysis
raster.min raster.max raster.save raster.save() ()
Spatial Analyst module
Spatial Analyst module that integrates Map Algebra into Python
Includes all Spatial p Analyst y tools Supports operators in Map Algebra expressions Helper classes that can be used to support complex parameter Output on the leftleft-side
from arcpy.sa import * demm = Raster("DEM") / 3.28 slpdeg = Slope(demm, "DEGREE") demfs = FocalStatistics( FocalStatistics("DEM" DEM , NbrRectangle(3,3), NbrRectangle(3 3) "MEAN") MEAN )
Raster Integration
d party Python library for scientific computing NumPy is a 3rd
A powerful array object S Sophisticated p analysis y capabilities p
ArcPy Raster objects can be converted to NumPy arrays for analysis
RasterToNumPyArray R t T N P A RasterToNumPyArray(), () NumPyArrayToRaster() (), N P A NumPyArrayToRaster T R t ()
inras = "ras100" # convert t raster t t to Numnpy N array. rasArray = arcpy.RasterToNumPyArray(inras) get the total sum of every y third value # ARRAY SLICING: g # from every third row of the raster sampArray = rasArray[::3,::3] sum = NUM.sum(sampArray) print i t sum
Demo: Working with Map Algebra and NumPy
Tool Design g and Validation
Dales Dale s script tool wizardry validation