You are on page 1of 11

Programming in GIS

Commenting in code important to know objective
Python GUI = Graphical User Interface
*.py (save as py file)
Inputs/parameters -> Function - > Output
Input: Points/polygons
Function: Python
Output: Raster
Model Building in Arc of kernel density
>>> arcpy.mapping.MapDocument("Current")
Variables text to access(string), integer & float, list
Keywords -
Statements -
Case sensitive
One = sign is an assignment
Two == signs is checking if, is x equal to
Raw inputs only works with strings and inputs works with numbers

Programming in GIS
getcwd is get currently working directory
os.chdir is OS Currently Working Directory
Loop -> while loop
Text input, output
Two loops (for, or while) to calculate distance between points
def Distance(from[x,y], to[x,y])
Xa, Ya, Xb, Yb
To calculate distance: sqrt[(xb-xa)^2+(Yb-Ya)^2)]

Have function going to define, Function is a procedure
Function takes on inputs and produces output
Inputs(coordinates, function arguments/parameters)->function->output(is return)


Programming in GIS
Dictionaries: associated arrays
,x:42, y:3.14,z:7- 3 Items string
{1:2,3:4} 2 Items, intenger keys
dict(x=42, y=3.14, z=7) each item in dictionary is unique, not duplicated
Text Input/Output
Tree DBH
1 15
2 14
3 12
4 17
Must specify input location
InFile=open (C:\\temp\\input.txt,r)
outFile =open(C:\\temp\\output.txt,w)
outFile.close() Write to text file and closes file to save
Columns called as separated by: , space and \t
\n means go to new line/next line
Use two functions: split (removes \t) and strip (removes \n)
1,\t, 15\n
2,\t ,14\n
Programming in GIS
Midterm is Feb 28 openbook

2/14/13 Review
Variables one to another type
Types: integer, string/text, float 0.0 decimal, list*+ inside could have different types, dictionary{}
In text file values are string
Assignments variables can take different values
Assign certain values to define a= 5
(however, a==5 checks if a is equal to five)
Modules import: toolbox of math, sys, os, arcpy, numpy(statistics)
Pseudocode (flowchart) steps to solve problem GET, SET, REPEAT
Increment to shift one position at time, i =0
Start->setCounter->End of list?, if not do something;check values, repeat action,->Increment, End? >End
Multiple if statement
do something
If Statements -
Loops (while, for)
While i< :
While j< :

Programming in GIS
Functions -
def functionName(radius , shp):
define what function does
return value
Textfiles (input, output) -
Input: open(___,r )
Output: open(___,w)
For i in input f:
Split(,), (\t)

For radius from 100m to 1000m, compute kde, save kde surface as kde_radius, increment radius

School buffers of students within 100 meters, 200, 300 to 2km (20 times)
Functions needed - Select by location: tool for proximity
Output of how many students live within each buffer

Write to textfile

Programming in GIS
Arcpy data shp, raster
Import arcpy
Define variable desc =arcpy.Describe(C:\\Schools.shp)
List data
Cursors -term for accessing records in table, open shp file table and link with dbf attributes
Three types of cursors: SEARCH, UPDATE, INSERT
Search cursor view values in database, read
Update- change values in database, read and rewrite
Insert add element like new line, new data elements
If adding new point then not just ID, attributes for table, but also specify spatial information for shp
Search Cursor-
GDB can contain FC, Raster, FDatabase(FClasses, Raster, Network with similar projection extent)
outputFile =csv.writer(open(File,w))
outputFile = open(File,w)
csvOutput=csv.writer(output File)
Reading and Writing Geometries spatial data
Point (0 dimension), Line(1 dimension, length), Polygon(2 dimension, length and area)
Geometry coordinates:
Line segments: vertices and nodes
Polygon: repeated coordinate enforces the closure
Spider maps

Coordinates: add field, calculate geometry, x and y coordinates
Create fields Xbegin, Ybegin,Xend, Yend, simply add x and y coordinates to populate

Programming in GIS
SQL- access (extract) data based on a query
<WHERE_CLAUSE> has a condition that must be met
Select from Hospital
WHERE zipcode = 14%%% (<-criteria)

3/21/13 Writing Geometries
Lines: origin to destination
Array([Xori, Yori],[Xdest,Ydest])
Insert cursor to create feature class
Define projection system
Read coordinates into array
Insert information into a cursor

1. Create Feature Class
2. Set projection
3. Cursor
4. Define coordinates setting data from
5. Insert cursor

3/26/13 Writing Geometries

Graduated symbols: Add attribute information

Read line by line, create spider line

Programming in GIS

Elements in list

Homework 5

1. Create new table
2. Create empty polyline shp +7 fields
3. For each threshold
a. Get busstop
b. For each busstop
i. Get ID, X, Y
ii. Select all points in students layer within threshold
1. Get count
2. Add in empty table
4. Get students layer
5. For each Student
a. Get x,y
b. Calculate distance bus->student
c. Add line between bus>student
d. Insert in polyline shape

ToolBox Script -Kernel Density Script

Pop Field
Output Raster
Output cell size
Search Radius with
1. Start Radius
2. Stop Radius
3. Increment
Area units
Add toolbox
Add script
Add description, title
Enter Display name and type:
InputFeature (.shp) | Feature Class
Minimum Radius (meters) | Double
For multiple radius use string with specified parameters
Programming in GIS
%s makes string within __
print Hi%s % (Class)
Hi Class

distance =2054.3867
Print %f.1 %(distance)
f.1 Restricts to one decimal place

at beginning of loop set a counter for demand, outside of loop add new field in Origin(BusStops) as
counting demand
For i in range (__values must be integers) - range function has difficulty with decimals
But if have list, a = {3.33,42.4,33.56) __ For i in a:
4/9/13 Mapping in Arcpy
Used arcpy in gis environment to access elements of mxd
(mxd does not contain data but display, projection, toolbox, chosen elements)
Creates layer as container (data frame) of shp, want to access elements (each layer) of mxd in python
View data, Map Layout, TOC (Table of Contents)
arcpy.mapping 1. Manipulate and access contents of existing map document
2. Suite of functions for exporting and printing
3. Automatic map production
Features of arcpy.mapping (automation, access layer)
- Projection of layers
- Symbology
Objective for today: Export mxd to pdf
- List different layers
- Export to pdf function

- >>> arcpy.mapping.MapDocument("Current")
- <MapDocument object at 0x1ecf41b0[0x20df2560]>
- >>> Calls = arcpy.mapping.MapDocument("Current")
- >>> Calls
Main tree is mxd, branch is dataframe, layers are leaves
Programming in GIS
4/11/13 UNCC DEM in Week 9a
Layers Properties (dem raster, shapefile)
Scales, map unites, names, symbology,


4/16/13 Network analyst and how to automate network modeling from python
Network Route, optimization, closest facility, OD cost matrix
Network created already in GIS: find shortest route, calculate time origin to desination
Students who live within 150, 500, 750, 1000, 1500, 2000 meters from busStops
Origin ID Closest to Stop ID Distance
Not Euclidean distance,=

Spatial KDE, krieging, IDW

ArcGIS Env
SA (KDE, Interpolation)-(IDW(parameters), Kriging, Spline)
Spatial Analyst Inverse Distance Weighted
If two parameters, think two for loops
Rain measurements of Idaho using Inverse Distance Weighted
Create Prediction map of variable using, raster map. Objective, produce map of places with no data.
Generate raster surface, surface of raster cell interpolated by nearby values (parameter: radius)
Greater radius, less constraint = smoother raster
Power (weight of values
searchRadius =
for searchRadius from 10km to 100km:
for power from .1 to 3
compute IDW , outRaster_radius_power = IDW
Programming in GIS

Network by topology

Def process(x):
Ta = time.time()

Print time.time()-ta

Time Date
Video from raster


Farmer Market Proximity excel to csv, created network, created centroids census groups
Kriging for Missing Data- calculate amt and frequency variables create raster, write to table
Wetlands Codes- automate classification hydrogeomorphic system
Medicaid Clinics- Distance on network from input location
Summarizing Landscapes Surrounding data points
Video Animation of Raster