Python in arcgis

Download Report

Transcript Python in arcgis

UNIVERSITATEA DE VEST DIN TIMISOARA
DEPARTAMENTUL DE GEOGRAFIE
GEOPROCESARE IN ARCGIS
FOLOSIND PYTHON
SUPORT DE CURS SI APLICATII PRACTICE
MASTER: SISTEME INFORMATIONALE GEOGRAFICE
AUTOR:
OVIDIU CSILLIK
CUPRINS
INTRODUCERE
FUNCTII SI PROPRIETATI AVANSATE
ARCPY SI PYTHON
FUNCTII DESCRIPTIVE
GEOPROCESSING TOOLS
FUNCTII DE LISTA
REGULI DE SCRIERE A SCRIPTURILOR
FUNCTII CURSOR
NOTIUNI DE BAZA PYTHON
FUNCTII DE GEOMETRIE
EXERCITII
CREAREA UNEI UNELTE IN ARCTOOLBOX
DEPANAREA UNUI SCRIPT
MAPPING MODULE
EXEMPLU DE COD PYTHON
MANIPULAREA HARTILOR SI A LAYERELOR
CE ESTE ARCPY ?!?
ArcPy este succesorul modulului arcgisscripting.
Crearea unei baze folositoare si productive pentru:
•
•
•
•
analiza datelor geografice
conversiilor de date
managementului de date
automatizarii crearii hartilor cu ajutorul Python.
>>> import arcpy
>>> help(arcpy)
ARCPY SI PYTHON
• Unelte de geoprocesare
automate
• Cautare in inregistrari, citirea si
scrierea valorilor specifice
• Manipularea documentelor de
harta si layere
• Crearea si manipularea
geometriei
UNDE EXECUTAM CODURILE PYTHON ?!?
Editorul PythonWin
Python 2.6.5 IDLE
Fereastra Python din ArcMap
UNDE EXECUTAM CODURILE PYTHON ?!?
Field Calculator - ArcMap
Script in Toolbox
GEOPROCESSING TOOLS IN ARCGIS
Toolbox Name
Alias
Analysis Toolbox
analysis
Cartography Toolbox
cartography
Conversion Toolbox
conversion
Coverage Toolbox
arc
Data Management Toolbox
management
Geocoding Toolbox
geocoding
Geostatistical Analyst Tools
ga
Linear Referencing Toolbox
lr
Network Analyst Tools
na
Samples
samples
Spatial Analyst Toolbox
sa
Spatial Statistics Toolbox
stat
3D Analyst Toolbox
3d
ACCESSING ENVIRONMENT SETTINGS
VIA ARCPY
Environment settings as properties from arcpy.env class:
import arcpy
# setting the environment: object.properties = value
arcpy.env.workspace = "C:\\temp"
arcpy.env.cellSize = 100
# retrieve settings: result = object.properties
variableWorkspace = arcpy.env.workspace
print "the name of the workspace is: " + variableWorkspace
print "cell size is: " + " arcpy.env.cellSize
ACCESSING TOOLS VIA ARCPY
Tools can be accessed as functions directly from arcpy
import arcpy
arcpy.env.workspace = "C:\\temp"
# Tool access follows (usually) the following scheme:
# object.Tool (parameter 1, parameter 2, parameter n)
arcpy.Buffer_analysis (InFeature, "c:\\ buff.shp", 100)
input feature class – output - buffer value
BINE DE STIUT 
• Comentariile din interiorul scriptului : #
• Numele de variabile nu pot incepe cu o cifra
• Case sensitive:
• Variables names
• Statements
• Functions
• Geoprocessing function and class names
• Not case sensitive:
• Pathnames
PENTRU CURIOSI 
Books
• Learning Python, (4th Edition) by Mark Lutz
• Learn to Program Using Python by Alan Gauld
• Programming Python by Mark Lutz
Web sites
• www.python.org
• Tutorials, documentation, forums
• diveintopython.org
• Online tutorial book
• http://code.activestate.com/recipes/langs/python/
• Learn Python functionality, share sample non-GIS Python scripts
NOTIUNI DE BAZA - PYTHON
Tipuri de date
• Variabilele pot stoca valori de diferite tipuri
NOTIUNI DE BAZA - PYTHON
Statements
• Indeplinesc o sarcina, dar nu returneaza o valoare
• Importarea modulelor in script
• Printarea stringurilor in fereastra interactiva
NOTIUNI DE BAZA - PYTHON
Statements
• Indeplinesc o sarcina, dar nu returneaza o valoare
• Testarea daca o conditie e True sau False
• Bucla de cautare intr-o colectie
FII PE FAZA !
Gaseste 3 erori in scriptul de mai jos:
if x = 5:
print "x is equal to 5"
elif x > 5
print "x is greater than 5"
else:
print "x is not equal to or greater than 5'
Gaseste 4 erori in scriptul de mai jos:
# This script buffers the Railroads feature class from the
# SanDiego.gdb geodatabase. The buffer distance is 500 meters
import arcpy
arcpy.env.Workspace = "C:\Student\\PYTH\\Database\\SanDiego.mdb"
inFC = "Railroads"
distance = 500
arcpy.Buffer_analysis(inFC, newBuffFC, distance)
FII PE FAZA !
Gaseste 5 erori in scriptul de mai jos:
# This script prints each item in the Python list to the
# Interactive Window.
listFC = ["Airports", "BusStations", "Schools", "Parcels"]
For fc in listFc:
print fc
Print len(lstFc)
FII PE FAZA !
Gaseste 3 erori in scriptul de mai jos:
# This script compares the square root of 25 with 6 and
# reports the comparison to the Interactive Window.
Import math
z = 25
y = 6
x = math.sqrt(z)
if x = y:
print "x and y are the same"
elif x > y:
print "x is greater than y"
else
print "x is less than y"
DEBUGGING WORKFLOW
1
Check for syntax errors
2
Run with arguments
3
Comment out code
4
Use print statements
5
Use Debugging Toolbar
EXEMPLU PYTHON
Statement
Variabila
Lista
Bucla FOR
PYTHON – FIELD CALCULATOR
FUNCTII SI PROPRIETATI AVANSATE
Proprietati si functii suplimentare, ce nu se gasesc in ArcToolbox
FUNCTII SI PROPRIETATI AVANSATE
Proprietati si functii suplimentare, ce nu se gasesc in ArcToolbox
FUNCTII DESCRIPTIVE
Extrag informatii despre date pentru luarea deciziilor
• Shape, Raster, Tabele, Workspace etc.
Linie
Numele campului
Tipul: integer, string etc.
FUNCTII DE LISTA
Obtinerea unei lista cu shape, rastere sau tabele
• Adaugarea intr-o geodatabase prin cautarea de .shp intr-o lista
Geodatabase
os.sep = \
# print os.sep
rstrip returneaza o
copie a stringului din
care taie “.shp”
# gaseste toate .shp
FUNCTII CURSOR
Acceseaza o colectie de inregistrari
• Citeste si scrie valori in timpul iteratiilor fiecarei inregistrari pe rand
FUNCTIA SEARCHCURSOR
Cursor Task
Reading
SearchCursor
(parameters)
Row(s)
#Set current workspace
arcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
#Create cursor on MajorAttractions feature class
curs = arcpy.SearchCursor("MajorAttractions")
# Iterate through the rows in the cursor
# Print the name and Address of each Major Attraction
for row in curs:
print row.Name
print row.Addr
del curs, row
FUNCTIA UPDATECURSOR
Cursor Task
Updating
UpdateCursor
(parameters)
Row(s)
#Set current workspace
arcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
#Create cursor on MajorAttractions feature class
curs = arcpy.UpdateCursor("MajorAttractions",
'"NAME" = \'San Diego Zoo\'')
# Iterate through the rows in the cursor and update the address
for row in curs:
row.Addr = "1900 ZOO PLACE"
cur.updateRow(row)
del curs, row
FUNCTIA INSERTCURSOR
Cursor Task
Insert
InsertCursor
(parameters)
New
Row
row
#Set current workspace
arcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
#Create cursor on MajorAttractions feature class
curs = arcpy.InsertCursor("MajorAttractions")
# Create new row, update fields and insert row.
row = curs.newRow()
row.Name = "BLACK MOUNTAIN PARK"
row.Addr = "12115 BLACK MOUNTAIN RD"
curs.insertRow(row)
del curs, row
GEOMETRIA OBIECTELOR
Creare, stergere, mutare sau remodelarea caracteristicilor
SCRIPT TOOL
Adaugarea unui script ca o unealta in ArcToolbox
• Un tool de geoprocesare care executa un script
• Full membership in geoprocessing framework
• Communicates with ArcGIS applications:
•
•
•
•
Messages
Environments
Outputs added to map
Etc.
SCRIPT TOOL
Avantaje
•
•
•
•
Sunt usor de share-uit
Utilizabile si de incepatori (creaza automat casute de dialog)
Pot fi adaugate in Bara de unelte
Inserarea scriptului intr-un Model
ARCPY FUNCTION: GETPARAMETERASTEXT
ArcPy function: GetParameterAsText
Function directly accessible through ArcPy
Used to capture input parameters
• This method can only be used with ArcToolbox. Not for use with PythonWin
or Command Prompt
Zero based. First argument is at position 0, and each argument thereafter is
incremented by one.
import arcpy
# GetParameterAsText function (numbered for each parameter)
arcpy.env.workspace = arcpy.GetParameterAsText(0)
bufFC = arcpy.GetParameterAsText(1)
bufOut = arcpy.GetParameterAsText(2)
bufDist = arcpy.GetParameterAsText(3)
arcpy.Buffer_analysis(bufFC, bufOut, bufDist)
DISPLAY ERROR MESSAGE / INFORMATION
MESSAGES IN ARCGIS
Show error or information messages in the Python Editor:
print statement (only valid in the Python Editor and/or the Python execution
window)
and/or
print arcpy.GetMessages() # retrieves ArcGIS/ArcPy specific messages
Show error or information messages in ArcGIS (if a script is executed as a tool):
AddMessage(Message string) # like the print statement
AddWarning(Message string)
AddError(Message string)
•
Difference in appearance
Display explicit errors in ArcGIS: arcpy.AddMessage(arcpy.GetMessages())
ATTACH A SCRIPT TO A CUSTOM TOOL
General properties
Script location
Parameter properties
MAPPING MODULE
arcpy.mapping
Python scripting library
• Open and manipulate map documents (.mxd), layer files (.lyr)
• Query and alter contents
• Print, export or save the modified document
Automate ArcMap workflows
• Map management, output
• Update or repair data source
• Create a report
• Build a variety of PDF map books
MANIPULATE MAP DOCUMENTS AND LAYERS
Add, remove and rotate data frames
DATA FRAME
Add, remove layers
Referinta spatiala
Extend
Etc.
Set properties
‘Curent’
MANIPULATE MAP DOCUMENTS AND LAYERS
Add, remove and rotate data frames
LAYER
Add, remove layers
Name, Source, Label,
Visibility, Transparency
Etc.
Set properties
SUMAR – GEOPROCESARE FOLOSIND
ARCMAP SI PYTHON
Geoprocessing is for everyone that uses ArcGIS.
Whether you're a beginning user or a pro, geoprocessing will become
an essential part of your day-to-day work with ArcGIS.
The fundamental purposes of geoprocessing are to allow you to
automate your GIS tasks and perform spatial analysis and modeling.
Almost all uses of GIS involve the repetition of work, and this creates
the need for methods to automate, document, and share multiple-step
procedures known as workflows.
SUMAR – GEOPROCESARE FOLOSIND
ARCMAP SI PYTHON
Geoprocessing supports the automation of workflows by providing a
rich set of tools and a mechanism to combine a series of tools in a
sequence of operations using models and scripts.
Geoprocessing is based on a framework of data transformation. A
typical geoprocessing tool performs an operation on an ArcGIS dataset
(such as a feature class, raster, or table) and produces a new dataset as
the result of the tool. Each geoprocessing tool performs a small yet
essential operation on geographic data, such as projecting a dataset
from one map projection to another, adding a field to a table, or
creating a buffer zone around features. ArcGIS includes hundreds of
such geoprocessing tools.
DONE !
MULTUMESC
PENTRU
ATENTIE 