Author
elvin-horn
View
219
Download
0
Embed Size (px)
GEOPROCESARE IN ARCGIS FOLOSIND PYTHON
UNIVERSITATEA DE VEST DIN TIMISOARA
DEPARTAMENTUL DE GEOGRAFIE
SUPORT DE CURS SI APLICATII PRACTICE
MASTER: SISTEME INFORMATIONALE GEOGRAFICE
AUTOR:
OVIDIU CSILLIK
CUPRINS
INTRODUCERE
ARCPY SI PYTHON
GEOPROCESSING TOOLS
REGULI DE SCRIERE A SCRIPTURILOR
NOTIUNI DE BAZA PYTHON
EXERCITII
DEPANAREA UNUI SCRIPT
EXEMPLU DE COD PYTHON
FUNCTII SI PROPRIETATI AVANSATE
FUNCTII DESCRIPTIVE
FUNCTII DE LISTA
FUNCTII CURSOR
FUNCTII DE GEOMETRIE
CREAREA UNEI UNELTE IN ARCTOOLBOX
MAPPING MODULE
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 ARCPYEnvironment 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 - PYTHONTipuri de date
• Variabilele pot stoca valori de diferite tipuri
NOTIUNI DE BAZA - PYTHONStatements
• Indeplinesc o sarcina, dar nu returneaza o valoare
• Importarea modulelor in script
• Printarea stringurilor in fereastra interactiva
NOTIUNI DE BAZA - PYTHONStatements
• 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:
Gaseste 4 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'
# This script buffers the Railroads feature class from the# SanDiego.gdb geodatabase. The buffer distance is 500 metersimport arcpyarcpy.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 mathz = 25y = 6x = 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
Check for syntax errors
1
Run with arguments
2
Comment out code
3
Use print statements
4
Use Debugging Toolbar
5
EXEMPLU PYTHON
Statement
VariabilaLista
Bucla FOR
PYTHON – FIELD CALCULATOR
FUNCTII SI PROPRIETATI AVANSATEProprietati si functii suplimentare, ce nu se gasesc in ArcToolbox
FUNCTII SI PROPRIETATI AVANSATEProprietati si functii suplimentare, ce nu se gasesc in ArcToolbox
FUNCTII DESCRIPTIVEExtrag informatii despre date pentru luarea deciziilor
• Shape, Raster, Tabele, Workspace etc.
Linie
Numele campului
Tipul: integer, string etc.
FUNCTII DE LISTAObtinerea 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 CURSORAcceseaza o colectie de inregistrari
• Citeste si scrie valori in timpul iteratiilor fiecarei inregistrari pe rand
FUNCTIA SEARCHCURSORRow(s
)
#Set current workspacearcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
#Create cursor on MajorAttractions feature classcurs = arcpy.SearchCursor("MajorAttractions")
# Iterate through the rows in the cursor# Print the name and Address of each Major Attractionfor row in curs: print row.Name print row.Addrdel curs, row
SearchCursor(parameters)
Cursor Task
Reading
FUNCTIA UPDATECURSOR
#Set current workspacearcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
#Create cursor on MajorAttractions feature classcurs = arcpy.UpdateCursor("MajorAttractions", '"NAME" = \'San Diego Zoo\'')
# Iterate through the rows in the cursor and update the addressfor row in curs: row.Addr = "1900 ZOO PLACE" cur.updateRow(row)del curs, row
Row(s)
UpdateCursor(parameters)
Cursor Task
Updating
FUNCTIA INSERTCURSOR
#Set current workspacearcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
#Create cursor on MajorAttractions feature classcurs = 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
rowNew Row
InsertCursor
(parameters)
Cursor Task
Insert
GEOMETRIA OBIECTELORCreare, stergere, mutare sau remodelarea caracteristicilor
SCRIPT TOOLAdaugarea 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 TOOLAvantaje
• 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 MODULEarcpy.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 LAYERSAdd, remove and rotate data frames
Add, remove layers
Set properties
DATA FRAMEReferinta spatialaExtendEtc.
‘Curent’
MANIPULATE MAP DOCUMENTS AND LAYERSAdd, remove and rotate data frames
Add, remove layers
Set properties
LAYERName, Source, Label,Visibility, TransparencyEtc.
SUMAR – GEOPROCESARE FOLOSIND ARCMAP SI PYTHONGeoprocessing 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 PYTHONGeoprocessing 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.
MULTUMESC PENTRU
ATENTIE
DONE !