Using Python with ArcGIS Drew Flater, Nobbir Ahmed Offering 184
Agenda Python essentials Arcpy, functions & classes Script geoprocessing workflows Automate map management & production Customize Desktop with Python Add-ins Analyze rasters with map algebra Extend ArcGIS with Python
Python Essentials Getting started with Python in ArcGIS
What is Python? Python is an easy to learn, powerful language (with) high-level data structures and a simple but effective approach to object-oriented programming. Python s elegant syntax and dynamic typing make it an ideal language for scripting in many areas and on most platforms. python.org Scripting language of ArcGIS Free, cross-platform, easy to learn, widely useful, great community
Python 101 Where do I write Python code? Python file is text with.py extension Edit in IDE like PyScripter, Wing IDE Logic for testing conditions If, else statement Operators like >, <, ==,!=, in Techniques for iteration or looping While loop; for loop Building blocks Function, Module, Package math.sqrt(100) 10 Python Standard Library / Built-ins os, sys, math, datetime, urllib2
ArcPy Site package included with ArcGIS that enables interaction with Python The access point to 900+ geoprocessing tools A package of functions, classes and modules Helper functions that perform useful tasks and enable automation (ListFeatureClasses, Describe, SearchCursor) Classes that can be used to create complex objects (SpatialReference, Geometry, FieldMap) Modules that provide specialized functionality (mapping, SpatialAnalyst, data access) Enhancement of arcgisscripting module (pre-10.0) Your old scripts will work
Why use Python and ArcGIS? Automate repetitive tasks Batch processing Develop workflows that leverage hundreds of tools and functions Add geoprocessing services to your application Customize Desktop apps with a language Esri is committed to support Extend the capabilities of ArcGIS
Script Geoprocessing Workflows Calling geoprocessing tools through ArcPy and stringing them together
Geoprocessing and Python import arcpy Follow tool syntax arcpy.toolname_toolboxalias() Enter input and output parameters How do I use a specific tool? Tool help page Copy as Python Snippet help(arcpy.buffer_analysis) Use geoprocessing environments as global parameters Accessed from arcpy.env Productivity / code cleanup tool workspace, extent, cellsize, mask
Demo Script Geoprocessing Workflows Perform batch processing, and string together multiple tools to perform spatial analysis
Tips & Tricks Use the result object of geoprocessing tools Returned by all tools Maintains messages, parameters, and outputs result = arcpy.buffer_analysis( ) Write intermediate tool output to in_memory workspace Automatic cleanup Faster read-write
Automate Map Management & Production Working with maps and layers using arcpy.mapping
ArcPy Mapping module arcpy.mapping Module that contains functions and classes used to automate mapping tasks Manage map documents, layers, and data Find and fix broken data sources Update layer symbology across many maps Export and print map documents Automate map production / map series
ArcPy Mapping module MapDocument object is essential References.mxd on disk; has methods and properties Needed to perform most mapping tasks MapDocument as input to function Functions called from MapDocument md = arcpy.mapping.mapdocument(" /NtlParks.mxd") # Set map document properties md.description = "Map of National Parks" # List layers in the map maplayers = arcpy.mapping.listlayers(md) # Fix Data Sources md.replaceworkspaces( ) # Export the map to PDF arcpy.mapping.exporttopdf(md, " /NtlParks.pdf")
Mapping module resources Download sample tools
Demo Automate Map Management & Production Make a multi-page map book using arcpy.mapping and data driven pages
Customize ArcGIS Desktop with Python Add-ins Run Python code in response to button clicks and application events
ArcGIS Desktop Add-ins Add-in framework provided to customize and extend ArcGIS Desktop applications Easy to build, install and share Secured through digital signing Supports C#, VB.NET, Java, and Python Python makes add-ins easier! No dlls, compiling, or ArcObjects, and less code
Python Add-in Types Button Tool Toolbar Tool Pallet Combo Box Menu Extension Dockable windows are not supported No custom UI support
Python Add-In Classes and Methods Button Tool onclick() oncircle(), online(), onrectangle() onmousedown(), onmousedownmap() Application Extension startup() newdocument(), opendocument(), closedocument() contentschanged(), itemadded(), itemdeleted() Full documentation of all functions and classes
Python Add-In Wizard Add-ins are built using the Python Add-in wizard The wizard generates fully stubbed out add-in projects including the config.xml, folders, and the Python script Download the Python Wizard from arcgis.com Extract the contents of the.zip Launch the addin_assistant.exe from the bin folder
Demo Customize ArcGIS Desktop with Python Add-ins Python Add-in toolbar with buttons to select and zoom to next or previous feature
Analyze Rasters with Map Algebra Using arcpy.sa (Spatial Analyst) to efficiently work with rasters
Spatial Analyst Module from arcpy.sa import * arcpy.checkoutextension("spatial") Includes all Spatial Analyst tools Helper classes that can be used to support complex parameter in scripting Integrates Map Algebra into Python Defines geographic analysis as algebraic expressions Supports mathematical, relational, other operators Output on the left-side sloperas = Slope("elevRas") * 100.0
Raster Class Reference to raster on disk, created in two ways: Returned output from arcpy.sa functions Cast using arcpy.raster() function Necessary for map algebra expressions using operators Temporary raster dataset that can be saved Has properties and method raster.minimum, raster.format, raster.extent raster.save() dem = arcpy.raster("elevation_meters.tif")) demft = dem * 3.28 # Rescale elevation to 0 1 scale rescale = (dem - dem.minimum)/(dem.maximum-dem.minimum) rescale.save("elevation_rescale_0_1.tif")
Demo Analyze Rasters with Map Algebra Use raster processing with Python to perform probabilitybased site suitability
Extend ArcGIS with Python Using Python to do stuff that's not in the ArcGIS box
Python packages ArcGIS includes several 3 rd -party Python packages and modules No separate install or config required, just import NumPy Matplotlib PyPI - official Python Package Index Vast collection of 3 rd -party packages with easy browse/search Windows binaries Statistical computation, powerful array object Data presentation and graphing Xlrd, Xlwt Excel spreadsheet read/write (new at 10.2) UC-Irvine maintains unofficial package installs for Windows "A simple approach for including 3 rd party Python libraries with your scripts"
NumPy NumPy is useful for mathematical & statistical computation Feature, table, and raster data can be converted to NumPy arrays 1 3 2 4 1 3 2 4 3 4 3 4 Raster Numpy Array To NumPy From ArcGIS arcpy.da.featureclasstonumpyarray arcpy.da.tabletonumpyarray arcpy.rastertonumpyarray To ArcGIS From NumPy arcpy.da.numpyarraytofeatureclass arcpy.da.numpyarraytotable arcpy.numpyarraytoraster
ArcGIS, Python, and Beyond Use Python as a communication language between ArcGIS and other APIs, packages, or applications "Extend ArcGIS with R" "Call a dll from a script tool using ctypes" Python Retrieves and organizes parameters/arguments from ArcGIS Converts data as needed (shapefiles, IMG, NetCDF, etc.) Constructs strings and uses operating system or class for execution After execution, applies symbology, coordinate system, and creates reports
Demo Extend ArcGIS with 3 rd -Party Python Libraries ArcGIS and NumPy roundtrip and using 3 rd -party packages
Resources resources.arcgis.com Python community arcpy.wordpress.com GIS Stack Exchange, Stack Overflow Python References Learning Python by Lutz The Python Standard Library by Example by Hellmann Python Scripting for ArcGIS by Esri press diveintopython.org python.org Working with the ArcPy DA Module Wed 1:00pm Smoketree A-E Creating Tools in a Python Toolbox Wed 2:30pm Mesquite GH Creating Geoprocessing Services Tue 1:00pm Smoketree A-E Python Scripting for Map Automation Wed 1:00 pm Mojave Learning Ctr Developing Python Add-ins Tue 4:00pm Primrose A Working with Raster Data Using Py Thu 8:30am Primrose A Integrating Open Source Stats Pkgs Tue 1:30pm Demo Theater 1, Oasis 1 Offering 184