using python with arcgis - citeseerx

33
Using Python with ArcGIS Drew Flater, Nobbir Ahmed Offering 184

Upload: khangminh22

Post on 08-Mar-2023

1 views

Category:

Documents


0 download

TRANSCRIPT

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

Getting started with Python in ArcGIS

Python Essentials

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

Calling geoprocessing tools through ArcPy and stringing them together

Script Geoprocessing Workflows

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

Perform batch processing, and string together multiple tools to perform spatial analysis

Script Geoprocessing Workflows

Demo

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

Working with maps and layers using arcpy.mapping

Automate Map Management & Production

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

Make a multi-page map book using arcpy.mapping and data driven pages

Automate Map Management & Production

Demo

Run Python code in response to button clicks and application events

Customize ArcGIS Desktop with Python Add-ins

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 onClick()

Tool 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

Python Add-in toolbar with buttons to select and zoom to next or previous feature

Customize ArcGIS Desktop with Python Add-ins

Demo

Using arcpy.sa (Spatial Analyst) to efficiently work with rasters

Analyze Rasters with Map Algebra

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")

Use raster processing with Python to perform probability-based site suitability

Analyze Rasters with Map Algebra

Demo

Using Python to do stuff that's not in the ArcGIS box

Extend ArcGIS with Python

Python packages

ArcGIS includes several 3rd-party Python packages and modules

No separate install or config required, just import

PyPI - official Python Package Index Vast collection of 3rd-party packages with easy browse/search

Windows binaries UC-Irvine maintains unofficial package installs for Windows

"A simple approach for including 3rd party Python libraries with your scripts"

NumPy Statistical computation, powerful array object Matplotlib Data presentation and graphing Xlrd, Xlwt Excel spreadsheet read/write (new at 10.2)

NumPy

NumPy is useful for mathematical & statistical computation Feature, table, and raster data can be converted to NumPy arrays

1 2 4

3 4 3

1 2 4

3 4 3

Numpy Array

Raster

To NumPy From ArcGIS To ArcGIS From NumPy arcpy.da.FeatureClassToNumPyArray arcpy.da.NumPyArrayToFeatureClass

arcpy.da.TableToNumPyArray arcpy.da.NumPyArrayToTable arcpy.RasterToNumPyArray 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

ArcGIS and NumPy roundtrip and using 3rd-party packages

Extend ArcGIS with 3rd-Party Python Libraries

Demo

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