GEOPROCESARE IN ARCGIS FOLOSIND PYTHON UNIVERSITATEA DE VEST DIN TIMISOARA DEPARTAMENTUL DE GEOGRAFIE SUPORT DE CURS SI APLICATII PRACTICE MASTER: SISTEME

  • View
    215

  • Download
    0

Embed Size (px)

Text of GEOPROCESARE IN ARCGIS FOLOSIND PYTHON UNIVERSITATEA DE VEST DIN TIMISOARA DEPARTAMENTUL DE...

Python in arcgis

GEOPROCESARE IN arcgis FOLOSIND PYTHONUNIVERSITATEA DE VEST DIN TIMISOARADEPARTAMENTUL DE GEOGRAFIESUPORT DE CURS SI APLICATII PRACTICEMASTER: SISTEME INFORMATIONALE GEOGRAFICEAutor:OVIDIU CSILLIKCuprinsINTRODUCEREARCPY SI PYTHONGEOPROCESSING TOOLSREGULI DE SCRIERE A SCRIPTURILORNOTIUNI DE BAZA PYTHONEXERCITIIDEPANAREA UNUI SCRIPTEXEMPLU DE COD PYTHON

FUNCTII SI PROPRIETATI AVANSATEFUNCTII DESCRIPTIVEFUNCTII DE LISTAFUNCTII CURSORFUNCTII DE GEOMETRIECREAREA UNEI UNELTE IN ARCTOOLBOXMAPPING MODULEMANIPULAREA HARTILOR SI A LAYERELOR

CE este arcpy ?!?ArcPy este succesorul modulului arcgisscripting.

Crearea unei baze folositoare si productive pentru:analiza datelor geograficeconversiilor de datemanagementului de dateautomatizarii crearii hartilor cu ajutorul Python.

>>> import arcpy>>> help(arcpy)Arcpy si pythonUnelte de geoprocesare automateCautare in inregistrari, citirea si scrierea valorilor specificeManipularea documentelor de harta si layereCrearea si manipularea geometriei

Unde executam codurile python ?!?

Editorul PythonWinPython 2.6.5 IDLE

Fereastra Python din ArcMapUnde 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 cifraCase sensitive:Variables namesStatementsFunctionsGeoprocessing function and class namesNot case sensitive:PathnamesPENTRU CURIOSI BooksLearning Python, (4th Edition) by Mark LutzLearn to Program Using Python by Alan GauldProgramming Python by Mark LutzWeb siteswww.python.org Tutorials, documentation, forumsdiveintopython.orgOnline tutorial bookhttp://code.activestate.com/recipes/langs/python/ Learn Python functionality, share sample non-GIS Python scripts

Notiuni de baza - PythonTipuri de dateVariabilele pot stoca valori de diferite tipuri

Notiuni de baza - PythonStatementsIndeplinesc o sarcina, dar nu returneaza o valoare

Importarea modulelor in script

Printarea stringurilor in fereastra interactiva

Notiuni de baza - PythonStatementsIndeplinesc 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 workflowCheck for syntax errors

1Run with arguments

2Comment out code

3Use print statements

4Use Debugging Toolbar

5Exemplu python

StatementVariabilaListaBucla 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 deciziilorShape, Raster, Tabele, Workspace etc.

LinieNumele campuluiTipul: integer, string etc.Functii de listaObtinerea unei lista cu shape, rastere sau tabeleAdaugarea intr-o geodatabase prin cautarea de .shp intr-o lista

Geodatabaseos.sep = \# print os.seprstrip returneaza o copie a stringului din care taie .shp# gaseste toate .shpFunctii cursorAcceseaza o colectie de inregistrariCiteste 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

ReadingFunctia 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, rowRow(s)UpdateCursor(parameters)Cursor Task

UpdatingFunctia 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, rowrowNew RowInsertCursor(parameters)Cursor Task

InsertGEOMETRIA obiectelorCreare, stergere, mutare sau remodelarea caracteristicilor

Script toolAdaugarea unui script ca o unealta in ArcToolboxUn tool de geoprocesare care executa un scriptFull membership in geoprocessing frameworkCommunicates with ArcGIS applications:MessagesEnvironmentsOutputs added to mapEtc.

Script toolAvantajeSunt usor de share-uitUtilizabile si de incepatori (creaza automat casute de dialog)Pot fi adaugate in Bara de unelteInserarea 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 toolGeneral propertiesScript locationParameter properties

MAPPING MODULEarcpy.mappingPython scripting libraryOpen and manipulate map documents (.mxd), layer files (.lyr)Query and alter contentsPrint, export or save the modified documentAutomate ArcMap workflowsMap management, outputUpdate or repair data sourceCreate a reportBuild a variety of PDF map booksManipulate map documents and layersAdd, remove and rotate data framesAdd, remove layersSet properties

DATA FRAMEReferinta spatialaExtendEtc.CurentManipulate map documents and layersAdd, remove and rotate data framesAdd, remove layersSet propertiesLAYERName, 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.