lesson1_introduction to gis modeling and python

40
Published on GEOG 485: GIS Programming and Automation ( https://www.e-education.psu.edu /geog485) Home > LESSONS Lesson 1: Introduction to GIS modeling and Python Log in [1] to post comments Overview Welcome to Geography 485. Over the next ten weeks you'll work through four lessons and a final project dealing with ArcGIS automation in Python. Each lesson will contain readings, examples, and projects. Since the lessons are two weeks long, you should plan between 20 - 24 hours of work to complete them, although this number may vary depending on your prior programming experience. See the Course Schedule section of this syllabus, below, for a schedule of the lessons and course projects. As with GEOG 483 and GEOG 484, the lessons in this course are project-based with key concepts embedded within. However, because of the nature of computer programming, there is no way this course can follow the step-by-step instruction design of the previous courses. You will probably find the course to be more challenging than the others. For that reason, it is more important than ever that you stay on schedule and take advantage of the course message boards and private e-mail. It's quite likely that you will get stuck somewhere during the course, so before getting hopelessly frustrated, please seek help from me or your classmates! I hope that by now that you have reviewed our Orientation and Syllabus for an important course site overview. Before we begin our first project, let me share some important information about the textbook and a related Esri course. Textbook and readings The textbook for this course is Python Scripting for ArcGIS by Paul A. Zandbergen. This book came out in 2012 and has been a hot item among Esri software users; I suggest you order your copy immediately in case of shortages or delays. Back when Geog 485 was rewritten as a Python course, there was no textbook available that tied together ArcGIS and Python scripting. As you read through Zandbergen's book, you'll see material that closely parallels what is in the Geog 485 lessons. This isn't necessarily a bad thing; when you are learning a subject like programming, it can be helpful to have the same concept explained from two angles. My advice about the readings is this: Read the material on the Geog 485 lesson pages first. If you feel like you have a good understanding from the lesson pages, you can skim through some of the more lengthy Zandbergen readings. If you struggled with understanding the lesson pages, you should pay close attention to the Zandbergen readings and try some of the related code snippets and exercises. I suggest you plan about 1 - 2 hours per week of reading if you are going to study the chapters in detail. Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17 1 of 40 9/25/2014 12:31 PM

Upload: swapnilawaghade

Post on 23-Dec-2015

63 views

Category:

Documents


2 download

DESCRIPTION

Lesson1_Introduction to GIS Modeling and PythonPennState_GEOG 485_GIS Programming and Automation

TRANSCRIPT

Page 1: Lesson1_Introduction to GIS Modeling and Python

Published on GEOG 485: GIS Programming and Automation (https://www.e-education.psu.edu/geog485)

Home > LESSONS

Lesson 1: Introduction to GIS modeling andPython

Log in [1] to post comments

Overview

Welcome to Geography 485. Over the next ten weeks you'll work through four lessons and a finalproject dealing with ArcGIS automation in Python. Each lesson will contain readings, examples, andprojects. Since the lessons are two weeks long, you should plan between 20 - 24 hours of work tocomplete them, although this number may vary depending on your prior programming experience.See the Course Schedule section of this syllabus, below, for a schedule of the lessons and courseprojects.

As with GEOG 483 and GEOG 484, the lessons in this course are project-based with key conceptsembedded within. However, because of the nature of computer programming, there is no way thiscourse can follow the step-by-step instruction design of the previous courses. You will probably findthe course to be more challenging than the others. For that reason, it is more important than everthat you stay on schedule and take advantage of the course message boards and private e-mail. It'squite likely that you will get stuck somewhere during the course, so before getting hopelesslyfrustrated, please seek help from me or your classmates!

I hope that by now that you have reviewed our Orientation and Syllabus for an important course siteoverview. Before we begin our first project, let me share some important information about thetextbook and a related Esri course.

Textbook and readings

The textbook for this course is Python Scripting for ArcGIS by Paul A. Zandbergen. This book cameout in 2012 and has been a hot item among Esri software users; I suggest you order your copyimmediately in case of shortages or delays.

Back when Geog 485 was rewritten as a Python course, there was no textbook available that tiedtogether ArcGIS and Python scripting. As you read through Zandbergen's book, you'll see materialthat closely parallels what is in the Geog 485 lessons. This isn't necessarily a bad thing; when youare learning a subject like programming, it can be helpful to have the same concept explained fromtwo angles.

My advice about the readings is this: Read the material on the Geog 485 lesson pages first. If youfeel like you have a good understanding from the lesson pages, you can skim through some of themore lengthy Zandbergen readings. If you struggled with understanding the lesson pages, youshould pay close attention to the Zandbergen readings and try some of the related code snippetsand exercises. I suggest you plan about 1 - 2 hours per week of reading if you are going to study thechapters in detail.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

1 of 40 9/25/2014 12:31 PM

Page 2: Lesson1_Introduction to GIS Modeling and Python

In all cases, you should get a copy of the textbook because it is a relevant and helpful reference.

Esri Virtual Campus Courses Using Python in ArcGIS Desktop 10

There is a free Esri Virtual Campus course, Using Python in ArcGIS Desktop 10 [2], that introduces alot of the same things you'll learn this quarter in Geog 485. The course consists of a one-hourrecorded seminar and a walkthrough exercise. If you want to get a head start, or you feel you wantsome reinforcement of what we're learning from a different point of view, it would be worth your timeto complete this Virtual Campus course.

All you need in order to access this course is an Esri Global Account, which you can create for free.You do not need to obtain an access code from Penn State.

The video moves very quickly and covers a range of concepts that we'll spend 10 weeks studying indepth, so don't worry if you don't understand it all immediately. You might find it helpful to watch thevideo again near the end of Geog 485 to review what you've learned.

Questions?

If you have any questions now or at any point during this week, please feel free to post them to the

Lesson 1 Discussion Forum. (To access the forums, return to ANGEL via the ANGEL link. Once in

ANGEL, you can navigate to the Communicate tab and then scroll down to the Discussion Forumssection.) While you are there, feel free to post your own responses if you, too, are able to help aclassmate.

Now, let's begin Lesson 1.

Lesson 1 Checklist

This lesson is two weeks in length. (See the Calendar in ANGEL for specific due dates.) To finish thislesson, you must complete the actvities listed below. You may find it useful to print this page so thatyou can follow along with the directions.

Download the Lesson 1 data [3] and extract it to C:\WCGIS\Geog485\Lesson1 or a similar paththat is easy to remember.

1.

Work through the online sections of Lesson 1.2. Read Zandbergen chapters 2 - 3 and sections of chapters 4 & 5. In the online lesson pages Ihave inserted instructions about when it is most appropriate to read each of these chapters.

3.

Complete Project 1, Part I and submit the deliverables to the course drop box.4. Complete Project 1, Part II and submit the deliverables to the course drop box.5. Complete the Lesson 1 Quiz.6.

1.1.1 The need for GIS automation

Log in [4] to post comments

A geographic information system (GIS) can manipulate and analyze spatial datasets with thepurpose of solving geographic problems. GIS analysts perform all kinds of operations on data tomake it useful for solving a focused problem. This includes clipping, reprojecting, buffering, merging,

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

2 of 40 9/25/2014 12:31 PM

Page 3: Lesson1_Introduction to GIS Modeling and Python

mosaicking, extracting subsets of the data, and hundreds of other operations. In the ArcGIS softwareused in this course, these operations are known as geoprocessing and they are performed usingtools.

Successful GIS analysis requires selecting the right tools to operate on your data. ArcGIS uses atoolbox metaphor to organize its suite of tools. You pick the tools you need and run them in theproper order to make your finished product.

Suppose you’re responsible for selecting sites for video stores. You might use one tool to select landparcels along a major thoroughfare, another tool to select parcels no smaller than 0.25 acres, andother tools for other selection criteria. If this selection process were limited to a small area, it wouldprobably make sense to perform the work manually.

However, let’s suppose you’re responsible for carrying out the same analysis for several areas aroundthe country. Because this scenario involves running the same sequence of tools for several areas, itis one that lends itself well to automation. There are several major benefits to automating tasks likethis:

Automation makes work easier. Once you automate a process, you don't have to put in asmuch effort remembering which tools to use or the proper sequence in which they should berun.

Automation makes work faster. A computer can open and execute tools in sequence muchfaster than you can accomplish the same task by pointing and clicking.

Automation makes work more accurate. Any time you perform a manual task on a computer,there is a chance for error. The chance multiplies with the number and complexity of the stepsin your analysis. In contrast, once an automated task is configured, a computer can be trustedto perform the same sequence of steps every time.

ArcGIS provides three ways for users to automate their geoprocessing tasks. These three optionsdiffer in the amount of skill required to produce the automated solution and in the range of scenariosthat each can address.

The first option is to construct a model using Model Builder. Model Builder is an interactive programthat allows the user to “chain” tools together, using the output of one tool as input in another.Perhaps the most attractive feature of Model Builder is that users can automate rather complex GISworkflows without the need for programming. You will learn how to use Model Builder early in thiscourse.

Some automation tasks require greater flexibility than is offered by Model Builder, and for thesescenarios it's recommended that you write scripts. The bulk of this course is concerned with scriptwriting. A script is a program that executes a sequential procedure of steps. Within a script, you can run GIStools individually or chain them together. You can insert conditional logic in your script to handlecases where different tools should be run depending on the output of the previous operation. Youcan also include iteration, or loops, in a script to repeat a single action as many times as needed toaccomplish a task.

There are special scripting languages for writing scripts, including Python, JScript, and Perl. Oftenthese languages have more basic syntax and are easier to learn than other languages such as C,Java, or Visual Basic.

Although ArcGIS supports various scripting languages for working with its tools, Esri emphasizesPython in its documentation and includes Python with the ArcGIS install. In this course we’ll be

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

3 of 40 9/25/2014 12:31 PM

Page 4: Lesson1_Introduction to GIS Modeling and Python

working strictly with Python. You’ll learn the basics of the Python language, how to write a script, andhow to manipulate and analyze GIS data using scripts. Finally, you’ll apply your new Pythonknowledge to a final project, where you write a script of your choosing that you may be able to applydirectly to your work.

The third option available to ArcGIS users looking to automate geoprocessing is to build a solutionusing ArcObjects, the programming building blocks used by Esri’s own developers to produce theArcGIS desktop products. With ArcObjects, it is possible to customize the user interface to includespecific commands and tools that either go outside the abilities of the out-of-the-box ArcGIS tools ormodify them to work in a more focused way. ArcObjects programming and interface customizationare outside the scope of this course, but are covered in the GIS Application Development course,GEOG 489. GIS customization with ArcObjects can be an advanced endeavor, and learning ascripting language like Python is a good way to prepare yourself by learning basic programmingconcepts.

The tools that you run in ModelBuilder and Python actually use ArcObjects "under the hood" to runGIS functions; however, the advantage of Python scripting with ArcGIS is that you don't need to learnall the ArcObjects logic behind the tools. Your job is just to learn the tools and how to run them in theappropriate order to accomplish your task.

This first lesson will introduce you to concepts in both model building and script writing. We’ll start byjust getting familiar with how tools run in ArcGIS and how you can use those tools in theModelBuilder interface. Then, we’ll cover some of the basics of Python and see how the tools can berun within scripts.

1.2.1 Exploring the toolbox

The ArcGIS software that you use in this course contains hundreds of tools that you can use tomanipulate and analyze GIS data. Back before ArcGIS had a graphical user interface (GUI), peoplewould access these tools by typing commands. Nowadays, you can point and click your way througha whole hierarchy of toolboxes using ArcCatalog or the Catalog window in ArcMap.

Although you may have seen them before, let’s take a quick look at the toolboxes:

Open ArcMap.1.

If the Catalog window isn't visible, click the Windows menu, then click Catalog. (If you've usedprevious versions of ArcGIS, this is a new window at version 10 that allows you to have a lot ofthe ArcCatalog functionality available in ArcMap.) If you hover over or click the Catalog item onthe right side of your screen, you can make the Catalog window appear. Optionally, you can"pin" it down so that it doesn't hide itself.

2.

In the Catalog, expand the nodes Toolboxes > System Toolboxes and continue expandingthe toolboxes of your choice until you see some of the available tools. Notice that they’reorganized into toolboxes and toolsets. Sometimes it’s faster to use the Search window to findthe tool you need instead of browsing this tree.

3.

Let’s examine a tool. Expand Analysis Tools > Proximity > Buffer, and double-click the

Buffer tool to open it.

At this point, you’re looking at a dialog with many fields. Each geoprocessing tool has requiredinputs and outputs. Those are indicated by the green dots. They represent the minimumamount of information you need to supply in order to run a tool. For the Buffer tool, as inputs,you’re required to supply an input features location (the features that will be buffered) and abuffer distance. You’re also required to indicate an output feature class location (for the new

4.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

4 of 40 9/25/2014 12:31 PM

Page 5: Lesson1_Introduction to GIS Modeling and Python

buffered features).

Many tools also have optional parameters. You can modify these if you want, but if you don’tsupply them, the tool will still run using default values. For the Buffer tool, optional parametersare the Side Type, End Type, Dissolve Type, and Dissolve Fields. Optional parameters aretypically specified after required parameters.

Click the Show Help button in the lower-right corner of the tool (if it says Hide Help then you’realready viewing help). You can now click on any parameter in the dialog to see an explanationof that parameter appear in the right-hand window.

If you’re not sure what a parameter means, this is a good way to learn. For example, with the

help still open, click the Side Type input box on the Buffer tool (right where it says "FULL").The Help explains what the Side Type parameter means and lists the different options: FULL,LEFT, RIGHT, and OUTSIDE_ONLY.

5.

If you need even more help, each tool is fully documented in the ArcGIS Desktop Help. You could go

directly to the Buffer tool help by clicking the Tool Help button in the tool dialog box, but in thiscourse you'll often want to get to these help pages without opening the tool itself. Below are thesteps for doing so.

From the main menu of ArcMap, click Help > ArcGIS Desktop Help. Optionally, for the mostup-to-date help, you can use esri's Web-based help [5]. (All links to the Help in this course willopen the Web Help.)

1.

In the ArcGIS Desktop Help table of contents, expand Professional Library > Geoprocessing

> Geoprocessing tool reference. (If you are using 10.1 or later, browse to Geoprocessing >

Tool Reference instead.) Notice that the help topics in this section are organized into toolboxesand toolsets, paralleling the layout of the ArcGIS System Toolboxes.

2.

Continue navigating the help table of contents to Analysis toolbox > Proximity toolset >

Buffer. Scroll through the entire topic examining all the information that is given about theBuffer tool. Here you get tips about what the Buffer tool does, how to use it, a full list ofparameters, and scripting examples written in Python. These scripting examples will beextremely valuable to you as you complete the assignments in this course and you shouldalways check the Geoprocessing Tool Reference in the Help if you’re having trouble getting atool to run in Python.

3.

1.2.2 Environments for accessing tools

You can access ArcGIS geoprocessing tools in several different ways:

Sometimes you just need to run a tool once, or you want to experiment with a tool and itsparameters. In this case, you can open the tool directly from the Catalog and use the tool’sgraphical user interface (GUI, pronounced gooey) to fill in the parameters.ModelBuilder is also a GUI application where you can set up tools to run in a given sequence,using the output of one tool as input to another tool.If you’re familiar with the tool and want to use it quickly in ArcMap, you may prefer the Pythonwindow approach. You type the tool name and required parameters into a command window.You can use this window to run several tools in a row and declare variables, effectively doingsimple scripting.If you want to run the tool automatically, repeatedly, or as part of a greater logical sequence oftools, you can run it from a script. Running a tool from a script is the most powerful and flexibleoption.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

5 of 40 9/25/2014 12:31 PM

Page 6: Lesson1_Introduction to GIS Modeling and Python

We’ll start with the simplest of these cases, running a tool from its GUI, and work our way up toscripting.

1.2.3 Running a tool from its GUI

Let’s start by opening a tool from the Catalog window and running it using its graphical user interface(GUI).

If by chance you still have the Buffer tool open from the previous section, close it for now soyou can add some data.

1.

Create a folder on your machine at C:\WCGIS\Geog485. If you use a different path, be sure tosubstitute your path in the following examples.

2.

Download the Lesson 1 data [3] and extract Lesson1.zip into your new folder so that the data isunder the path C:\WCGIS\Geog485\Lesson1. This folder contains a variety of datasets you willuse throughout the lesson.

3.

Open ArcMap and create a new empty map.4.

Click the Add Data button and browse to the data you just extracted. Add the

us_boundaries and us_cities shapefiles.

5.

Open the Catalog window if necessary and browse to the Buffer tool as you did in the previoussection.

6.

Double-click the Buffer tool to open it.7.

Examine the first required parameter: Input Features. Click the Browse button andbrowse to the path of your cities dataset C:\WCGIS\Geog485\Lesson1\us_cities.shp. Notice thatonce you do this, a path is automatically supplied for the Output Feature Class. The softwaredoes this for your convenience only and you can change the path if you want.

A more convenient way to supply the Input Features is to just select the cities map layer fromthe dropdown menu. This dropdown automatically contains all the layers in your mapdocument. However, in this example we browsed to the path of the data because it’sconceptually similar to how we’ll provide the paths in the command line and scriptingenvironments.

8.

Now you need to supply the Distance parameter for the buffer. For this run of the tool, set a

Linear unit of 5 miles. When we run the tool from the other environments, we’ll make thebuffer distance slightly larger so we know that we got distinct outputs.

9.

The rest of the parameters are optional. The Side Type and End Type parameters apply only tolines and polygons, so they are not even available for setting in the GUI environment when

working with city points. However, change the Dissolve Type to ALL.

10.

Click OK to run the tool.11. The tool should take just a few seconds to complete. Examine the output that appears on themap, and do a “sanity check” to make sure that buffers appear around the cities and theyappear to be about 5 miles in radius. You may need to zoom in to a single state in order to seethe buffers.

12.

Click the Geoprocessing menu and click Results. This window lists messages aboutsuccesses or failures of all recent tools that you've run.

13.

Expand the Buffer tool until you can see all the messages. They list the tool parameters, thetime of completion, and any problems that occurred when running the tool. (See Figure 1.1.)These messages can be a big help later when you troubleshoot your Python scripts. The text ofthese messages is available whether you run the tool from the GUI, from the Python window inArcMap, or from scripts.

14.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

6 of 40 9/25/2014 12:31 PM

Page 7: Lesson1_Introduction to GIS Modeling and Python

Screen capture showing the Buffer tool and all messages.

1.2.4 Modeling with tools

When you work with geoprocessing, you’ll frequently want to use the output of one tool as the inputinto another tool. For example, suppose you want to find all fire hydrants within 200 meters of abuilding. You would first buffer the building, then use the output buffer as a spatial constraint forselecting fire hydrants. The output from the Buffer tool would be used as an input to the Select byLocation tool.

A set of tools chained together in this way is called a model. Models can be simple, consisting of justa few tools, or complex, consisting of many tools and parameters and occasionally some iterativelogic. Whether big or small, the benefit of a model is that it solves a unique geographic problem thatcannot be addressed by one of the “out-of-the-box” tools.

In ArcGIS, modeling can be done either through the ModelBuilder graphical user interface (GUI) orthrough code, using Python. To keep our terms clear, we’ll refer to anything built in ModelBuilder asa “model” and anything built through Python as a “script.” However, it’s important to remember thatboth things are doing modeling.

1.3.1 Why learn ModelBuilder?

ModelBuilder is Esri’s graphical interface for making models. You can drag and drop tools from theCatalog window into the model and “connect” them, specifying the order in which they should run.

Although this is primarily a programming course, we’ll spend some time in ModelBuilder during thefirst lesson for two reasons:

ModelBuilder is a nice environment for exploring the ArcGIS tools, learning how tool inputs andoutputs are used, and visually understanding how GIS modeling works. When you begin usingPython, you will not have the same visual assistance to see how the tools you’re using areconnected, but you may still want to draw your model on a whiteboard in a similar fashion to whatyou saw in ModelBuilder.

ModelBuilder can frequently reduce the amount of Python coding that you need to do. If your GISproblem does not require advanced conditional and iterative logic, you may be able to get your workdone in ModelBuilder without writing a script. ModelBuilder also allows you to export any model toPython code, so even if you do need to write a script, you may be able to use ModelBuilder to get ahead start.

1.3.2 Opening and exploring ModelBuilder

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

7 of 40 9/25/2014 12:31 PM

Page 8: Lesson1_Introduction to GIS Modeling and Python

Let’s get some practice with ModelBuilder to solve a real scenario. Suppose you are working on a siteselection problem where you need to select all areas that fall within 10 miles of a major highway and10 miles of a major city. The selected area cannot lie in the ocean or outside the United States.Solving the problem requires that you make buffers around both the roads and the cities, intersectthe buffers, then clip to the US outline. Instead of manually opening the Buffer tool twice, followed bythe Intersect tool, then the Clip tool, you can set this up in ModelBuilder to run as one process.

That’s it! You’ve just used ModelBuilder to chain together several tools and solve a GIS problem.

You can double-click this model any time in the Catalog window and run it just as you would a tool. Ifyou do this, you’ll notice that the model has no parameters; you can’t change the buffer distance orinput features. The truth is, our model is useful for solving this particular site-selection problem withthese particular datasets, but it’s not very flexible. In the next section of the lesson, we’ll make thismodel more versatile by configuring some of the variables as input and output parameters.

Create a new map document in ArcMap and add the us_cities, us_roads, and us_boundariesshapefiles from the Lesson 1 data folder that you configured previously in this lesson.Save your map document as C:\WCGIS\Geog485\Lesson1\ModelPractice.mxd.

1.

In ArcGIS, all models are stored in toolboxes. The first thing you need to do is create a toolboxto hold your new model. If the Catalog window is not visible already, display it by clicking the

menu item Windows > Catalog.

2.

In the Catalog window, expand the nodes until you see Toolboxes > My Toolboxes.3.

Right-click My Toolboxes and click New > Toolbox. Name it Lesson 1. (The software may add.tbx, which is fine.)

4.

Right-click the Lesson 1 toolbox and click New > Model. You’ll see ModelBuilder appear.5.

In ModelBuilder, click Model > Model Properties.6.

For the Name, type SuitableLand and for the Label, type Find Suitable Land. The label is whateveryone will see when they open your tool from the Catalog. That’s why it can contain spaces.The name is what people will use if they ever run your model from Python. That’s why it cannotcontain spaces.

7.

Click OK to dismiss the Model Properties dialog.

You now have a blank canvas on which you can drag and drop the tools. When creating amodel (and when writing Python scripts), it’s best to break your problem into manageablepieces. The simple site selection problem here can be thought of as four steps:

Buffer the citiesBuffer the roadsIntersect the buffersClip to the US boundary

Let’s tackle these items one at a time, starting with buffering the cities.

8.

With ModelBuilder still open, go to the Catalog window and browse to Toolboxes > System

Toolboxes > Analysis Tools > Proximity.

9.

Click the Buffer tool and drag it onto the ModelBuilder canvas. You’ll see a white rectangularbox representing the buffer tool and a white oval representing the output buffers. These areconnected with a line, showing that Buffer tool will always produce an output dataset.

In ModelBuilder, tools are represented with boxes and variables are represented with ovals.Right now, the Buffer tool, at center, is white because you have not yet supplied the requiredparameters. Once you do this, the tool and the variable will fill in with color.

10.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

8 of 40 9/25/2014 12:31 PM

Page 9: Lesson1_Introduction to GIS Modeling and Python

In your ModelBuilder window, double-click the Buffer box. The tool dialog here is the same as ifyou had opened the Buffer directly out of ArcToolbox. This is where you can supply parametersfor the tool.

11.

For Input Features, browse to the path of your us_cities shapefile on disk. The Output

Feature Class will populate automatically.

12.

For Distance [value or field] enter 10 miles.13.

For Dissolve Type, select ALL, then click OK to close the Buffer dialog. The model elements(tools and variables) should be filled in with color, and you should see a new element to the leftof the tool representing the input cities feature class.

14.

An important part of working with ModelBuilder is supplying clear labels for all the elements.This way, if you share your model, others can easily understand what will happen when it runs.Supplying clear labels also helps you remember what the model does, especially if you haven’tworked with the model for a while.

In ModelBuilder, right-click the us_cities.shp element (blue oval, at far left) and click Rename.Name this element "US Cities."

15.

Right-click the Buffer tool (yellow-orange box, at center) and click Rename. Name this “Bufferthe cities.”

16.

Right-click the us_citiesBuffer1.shp element (green oval, at far right) and click Rename. Namethis “Buffered cities.” Your model should look like this.

Figure 1.2 The model's appearance following step 17, above.

17.

Save your model (Model > Save). This is the kind of activity where you want to save often.18.

Practice what you just learned by adding another Buffer tool to your model. This time, configurethe tool so that it buffers the us_roads shapefile by 10 miles. Remember to set the Dissolvetype to ALL and to add meaningful labels. Your model should now look like this.

19.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

9 of 40 9/25/2014 12:31 PM

Page 10: Lesson1_Introduction to GIS Modeling and Python

Figure 1.3 The model's appearance following step 19, above.The next task is to intersect the buffers. In the Catalog window's list of toolboxes, browse to

Analysis Tools > Overlay and drag the Intersect tool onto your model. Position it to the rightof your existing Buffer tools.

20.

Here’s the pivotal moment when you chain the tools together, setting the outputs of your Buffer

tools as the inputs of the Intersect tool. Click the Connect tool , then click the Buffered cities

element followed by the Intersect element. If you see a small menu appear, click Input

Features to denote that the buffered cities will act as inputs to the Intersect tool. An arrow willnow point from the Buffered cities element to the Intersect element.

21.

Use the same process to connect the Buffered roads to the Intersect element. Again, if

prompted, click Input Features.

22.

Rename the output of the Intersect operation "Intersected buffers." If the text runs onto multiplelines, you can click and drag the edges of the element to resize it. You can also rearrange theelements on the page however you like. Because models can get large, ModelBuilder containsseveral navigation buttons for zooming in and zooming to the full extent of the model.

Your model should now look like this:

Figure 1.4 The model's appearance following step 23, above.

23.

The final step is to clip the intersected buffers to the outline of the United States. This prevents24.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

10 of 40 9/25/2014 12:31 PM

Page 11: Lesson1_Introduction to GIS Modeling and Python

any of the selected area from falling outside the country or in the ocean. In the Catalog window,

browse to Analysis Tools > Extract and drag the Clip tool into ModelBuilder. Position this toolto the right of your existing tools.

Use the Connect tool again to set the Intersected buffers as an input to the Clip tool, choosing

Input Features when prompted. Notice that even when you do this, the Clip tool is not ready torun (it’s still shown as a white rectangle, located at right). You need to supply the clip features,which is the shape to which the buffers will be clipped.

25.

In ModelBuilder (not in the Catalog window), double-click the Clip tool. Set the Clip Features by

browsing to the path of us_boundaries.shp, then click OK to dismiss the dialog. You’ll noticethat a blue oval appeared representing the Clip Features (US Boundaries).

26.

Set meaningful labels for the remaining tools as shown below. Below is an example of how youcan label and arrange the model elements.

Figure 1.5 The completed model with the clip tool included.

27.

Double click the final output element (named "Suitable land" in the image above) and set thepath to C:\WCGIS\Geog485\Lesson1\suitable_land.shp. This is where you can expect yourmodel output feature class to be written to disk.

28.

Right-click Suitable land and click Add to display.29.

Save your model again.30.

Test the model by clicking the Run button . You’ll see the by-now-familiar geoprocessingmessage window that will report any errors that may occur. ModelBuilder also gives you a visualcue of which tool is running by turning the tool red. (If the model crashes, try closingModelBuilder and running the model by double-clicking it from the Catalog window. You'll get amessage that the model has no parameters. This is okay [and true, as you'll learn below]. Goahead and run the model anyway.)

31.

When the model has finished running (it may take a while), examine the output in ArcMap.Zoom in to Washington state to verify that the has Clip worked on the coastal areas. The outputshould look similar to this.

32.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

11 of 40 9/25/2014 12:31 PM

Page 12: Lesson1_Introduction to GIS Modeling and Python

Figure 1.6 The model's output in ArcMap.

1.3.3 Model parameters

Log in [6] to post comments

Most tools, models, and scripts that you create with ArcGIS have parameters. Input parameters arevalues with which the tool (or model or script) starts its work, and output parameters represent whatthe tool gives you after its work is finished.

A tool, model, or script without parameters is only good in one scenario. Consider the model you justbuilt that used the Buffer, Intersect, and Clip tools. This model was hard-coded to use the us_cities,us_roads, and us_boundaries shapefiles and output a shapefile called suitable_land. If you wantedto run the model with other datasets, you would have to open ModelBuilder, double-click eachelement (US Cities, US Roads, US Boundaries, and Suitable land), and change the paths. Youwould have to follow a similar process if you wanted to change the buffer distances, too, since thosewere hard-coded to 10 miles.

Let’s modify that model to use some parameters, so that you can easily run it with different datasetsand buffer distances.

If it's not open already, open the map document C:\WCGIS\Geog485\Lesson1\ModelPractice.mxd in ArcMap.

1.

In the Catalog window, find the model you created in the previous lesson which should be

under Toolboxes > My Toolboxes > Lesson 1 > Find Suitable Land.

2.

Right-click the model Find Suitable Land and click Copy. Now right-click the Lesson 1 toolbox

and click Paste. This creates a new copy of your model that you can work with to create model

3.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

12 of 40 9/25/2014 12:31 PM

Page 13: Lesson1_Introduction to GIS Modeling and Python

parameters. Using a copy of the model like this allows you to easily start over if you make amistake.

Rename the copy of your model Find Suitable Land With Parameters or something similar.4.

In your Lesson 1 toolbox, right-click Find Suitable Land With Parameters and click Edit. You'llsee the model appear in ModelBuilder.

5.

Right-click the element US Cities (should be a blue oval) and click Model Parameter. Thismeans that whoever runs the model must specify the cities dataset to use before the model canrun.

6.

You need a more general name for this parameter now, so right-click the US Cities element and

click Rename. Change the name to just "Cities."

7.

Even though you "parameterized" the cities, your model still defaults to using the C:\WCGIS\Geog485\Lesson1\us_cities.shp dataset. This isn't going to make much sense if you shareyour model or toolbox with other people because they may not have the same us_citiesshapefile, and even if they do, it probably won't be sitting at the same path on their machines.

To remove the default dataset, double-click the Cities element and delete the path, then click

OK. Some of the elements in your model may turn white. This signifies that a value has to beprovided before the model can successfully run.

8.

Now you need to create a parameter for the distance of the buffer to be created around the

cities. Right-click the element that you named "Buffer the cities" and click Make Variable >

From Parameter > Distance [value or field].

9.

The previous step created a new element Distance [value or field]. Rename this element to"Cities buffer distance" and make it a model parameter. (Review the steps above if you'reunsure about how to rename an element or make it a model parameter.) For this element, youcan leave the default at 10 miles. Your model should look similar to this, although the title bar ofyour window may vary:

Figure 1.7 The "Find Suitable Land With Parameters" model following Step 10, above, andshowing two parameters.

10.

Repeating what you learned above, rename the US Roads element to "Roads," make it a modelparameter, and remove the default value.

11.

Repeating what you learned above, make a parameter for the Roads buffer distance. Leave thedefault at 10 miles.

12.

Repeating what you learned above, rename the US Boundaries element to Boundaries, make ita model parameter, and remove the default value. Your model should look like this (notice thefive parameters indicated by "P"s):

13.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

13 of 40 9/25/2014 12:31 PM

Page 14: Lesson1_Introduction to GIS Modeling and Python

Figure 1.8 The "Find Suitable Land With Parameters" model following Step 13, above, andshowing five parameters.Save your model and close ModelBuilder.14.

Double-click your model Lesson 1 > Find Suitable Land With Parameters and examine thetool dialog. It should look similar to this:

Figure 1.9 The model interface, or tool dialog, for the model "Find Suitable Land WithParameters."

People who run this model will be able to browse to any cities, roads, and boundaries datasets,and will be able to control the buffer distance. The green dots indicate parameters that must besupplied with valid values before the model can run.

15.

Test your model by supplying the us_cities, us_roads, and us_boundaries shapefiles for themodel parameters. If you like, you can try changing the buffer distance.

Note that sometimes the result does not add itself to the display like it should. You should just

16.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

14 of 40 9/25/2014 12:31 PM

Page 15: Lesson1_Introduction to GIS Modeling and Python

be able to add it to the display by using the Add Data button and browsing to thesuitable_land.shp location.

The above exercise demonstrated how you can expose values as parameters using ModelBuilder.You need to decide which values you want the user to be able to change and designate those asparameters. When you write Python scripts, you'll also need to choose parameters in a similar way.

1.3.4 Advanced geoprocessing andModelBuilder concepts

By now you've had some practice with ModelBuilder and you're about ready to get started with

Python. This page of the lesson contains some optional advanced material that you can read aboutModelBuilder. This is particularly helpful if you anticipate using ModelBuilder frequently in youremployment. Some of the items are common to the ArcGIS geoprocessing framework, meaning thatthey also apply when writing Python scripts with ArcGIS.

Managing intermediate data

GIS analysis sometimes gets messy. Most of the tools that you run produce an output dataset, andwhen you chain many tools together those datasets start piling up on disk. Even if you're diligentabout naming your datasets intuitively, it's easy to wind up with a folder full of datasets with nameslike buffers1, clippedbuffers1, intersectedandclippedbuffers1, raster2reclassified, etc.

In most cases, you are concerned with just the final output dataset. The intermediate data is justtemporary; you only need to keep it around for as long as it takes to run the model, and then it canbe deleted.

ModelBuilder can manage your intermediate data for you, placing it in a temporary directory calledthe scratch workspace. By default, the scratch workspace is your operating system's temp directory,but you can configure it to exist in another location.

You can force data to go into the scratch workspace by using the %SCRATCHWORKSPACE%variable in the path. For example: %SCRATCHWORKSPACE%\myOutput.shp

You can also mark any element in ModelBuilder as Intermediate and it will be deleted after the modelis run. By default, all derived data is Intermediate.

The following topics from Esri go into more detail on intermediate data and are important tounderstand as you work with the geoprocessing framework. I suggest reading them once now andreturning to them occasionally throughout the course. Some of the concepts in them are easier tounderstand once you've worked with geoprocessing for a while.

A quick tour of managing intermediate data [7]

Using the current and scratch workspace environments [8]

Setting current and scratch workspace environments [9]

Managing intermediate data in shared models [10] (Skip the section about ArcGIS Server)

Looping in ModelBuilder

Looping, or iteration, is the act of repeating a process. A main benefit of computers is their ability toquickly repeat tasks that would otherwise be mundane, cumbersome, or error-prone for a human to

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

15 of 40 9/25/2014 12:31 PM

Page 16: Lesson1_Introduction to GIS Modeling and Python

repeat and record. Looping is a key concept in computer programming and you will use it often asyou write Python scripts for this course.

ModelBuilder contains a number of elements called Iterators that can do looping in various ways. The

names of these iterators, such as For and While actually mimic the types of looping that you canprogram in Python and other languages. In this course, we'll focus on learning iteration in Python,which may actually be just as easy as learning how to use a ModelBuilder iterator.

To take a peek at how iteration works in ModelBuilder, you can visit the ArcGIS Desktop help book formodel iteration [11]. If you're having trouble understanding looping in later lessons, ModelBuildermight be a good environment to visualize what a loop does. You can come back and visit this book asneeded.

Readings

Read Zandbergen Chapter 2.1 - 2.9 to reinforce what you learned about geoprocessing andModelBuilder.

1.4.1 Introducing Python using the Pythonwindow in ArcGIS

The best way to introduce Python may be to look at a little bit of code. Let’s take the Buffer tool whichyou recently ran from the ArcToolbox GUI and run it in the ArcGIS Python window. This windowallows you to type a simple series of Python commands without writing full permanent scripts. ThePython Window is a great way to get a taste of Python.

This time, we’ll make buffers of 15 miles around the cities.

Open ArcMap to a new empty map.1. Add the us_cities.shp dataset from the Lesson 1 data.2.

On the Standard toolbar, click the Python window button . Once the window appears, dragit over to the side or bottom of the screen to dock it.

3.

Type the following in the Python window (Don't type the >>>. These are just included to showyou where the new lines begin in the Python window.)

>>> import arcpy>>> arcpy.Buffer_analysis("us_cities", "us_cities_buffered", "15 miles", "", "", "ALL")

4.

Zoom in and examine the buffers that were created.5.

You’ve just run your first bit of Python. You don’t have to understand everything about the code youwrote in this window, but here are a few important things to note.

The first line of the script import arcpy tells the Python interpreter (which was installed when youinstalled ArcGIS) that you’re going to work with some special scripting functions and tools includedwith ArcGIS. Without this line of code, Python knows nothing about ArcGIS, so you'll put it at the topof all ArcGIS-related code that you write in this class. You technically don't need this line when youwork with the Python window in ArcMap because arcpy is already imported, but I wanted to show youthis pattern early; you'll use it in all the scripts you write outside the Python window.

The second line of the script actually runs the tool. You can type arcpy, plus a dot, plus any tool

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

16 of 40 9/25/2014 12:31 PM

Page 17: Lesson1_Introduction to GIS Modeling and Python

name to run a tool in Python. Notice here that you also put an underscore followed by the name ofthe toolbox that includes the buffer tool. This is necessary because some tools in different toolboxesactually have the same name (like Clip, which is in both the Data Management and Analysistoolboxes).

After you typed arcpy.Buffer_analysis, you typed all the parameters for the tool. Each parameter wasseparated by a comma, and the whole list of parameters was enclosed in parentheses. Get used tothis pattern, since you'll follow it with every tool you run in this course.

In this code, we also supplied some optional parameters, leaving empty quotes where we wanted totake the default values, and truncating the parameter list at the final optional parameter we wanted toset.

How do you know the syntax, or structure, of the parameters to enter? For example, for the bufferdistance, should you enter 15MILES, ‘15MILES’, 15 Miles, or ’15 Miles’? The best way to answerquestions like these is to return to the Geoprocessing tool reference help topic for the Buffer tool [12].All of the topics in this reference section have a command line usage and example section to helpyou understand how to structure the parameters. All the required parameters are shown inside carets(<>), while the optional parameters are shown inside braces ({}). From the example in this topic, youcan see that the buffer distance should be specified as ’15 miles’. Because there is a space in thistext, or string, you need to surround it with single quotes.

You might have noticed that the Python window helps you by popping up different options you cantype for each parameter. This is called autocompletion, and it can be very helpful if you're trying torun a tool for the first time and you don't know exactly how to type the parameters. When you writecode in PythonWin, you don't get the autocompletion, so you may want to return to the Pythonwindow for tips as you practice writing lines of code. If you can get a line of code to work in thePython window, it will probably work in your script that you're writing in PythonWin.

There are a couple of differences between writing code in the Python window and writing code insome other program, such as Notepad or PythonWin (which we'll use throughout the course). In thePython window, you can reference layers in the map document by their names only, instead of theirfile paths. Thus, we were able to type "us_cities" instead of something like "C:\\data\\us_cities.shp".We were also able to make up the name of a new layer "us_cities_buffered" and get it added to themap by default after the code ran. If you're going to use your code outside the Python window, makesure you use the full paths.

When you write more complex scripts, it will be helpful to use an integrated developmentenvironment (IDE), meaning a program specifically designed to help you write and test Python code.Later in this course we’ll explore the PythonWin IDE.

Earlier in this lesson you saw how tools can be chained together to solve a problem usingModelBuilder. The same can be done in Python, but it’s going to take a little groundwork to get tothat point. For this reason we’ll spend the rest of Lesson 1 covering some of the basics of Python.

Readings

Take a few minutes to read Zandbergen Chapter 3, a fairly short chapter where he explains thePython window and some things you can do with it.

1.4.2 What is Python?

Python is a language that is used to automate computing tasks through programs called scripts. In

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

17 of 40 9/25/2014 12:31 PM

Page 18: Lesson1_Introduction to GIS Modeling and Python

the introduction to this lesson, you learned that automation makes work easier, faster, and moreaccurate. This applies to GIS and many other areas of computer science. Learning Python will makeyou a more effective GIS analyst, but Python programming is a technical skill that can be beneficialto you even outside the field of GIS.

Python is a good language for beginning programming. Python is a high-level language, meaningyou don’t have to understand the “nuts and bolts” of how computers work in order to use it. Pythonsyntax (how the code statements are constructed) is relatively simple to read and understand.Finally, Python requires very little overhead to get a program up and running.

Python is an open-source language and there is no fee to use it or deploy programs with it. Pythoncan run on Windows, Linux, and Unix operating systems.

In ArcGIS, Python can be used for coarse-grained programming, meaning that you can use it toeasily run geoprocessing tools such as the Buffer tool that we just worked with. You could code allthe buffer logic yourself, using more detailed, fine-grained programming with ArcObjects, but thiswould be time consuming and unnecessary in most scenarios; it’s easier just to call the Buffer toolfrom a Python script using one line of code.

1.4.3 Installing Python and PythonWin

If you installed the student version of ArcGIS, you should already have Python on your computer,typically in a folder called C:\Python26\ArcGIS10.0\ (if you are using ArcGIS 10.0) or C:\Python27\ArcGIS10.1\ (if you are using ArcGIS 10.1; in case of ArcGIS 10.2 replace the 10.1 by 10.2). You canwrite Python code at any time in Notepad or other editors and save it as a .py file, but you need tohave Python installed in order for your computer to understand and run the program.

In this course we’ll be working with Python version 2.6.x (if you have ArcGIS 10.0) or version 2.7.x (ifyou have ArcGIS 10.1 or higher). If you check out the download page for Python from its home pageat www.python.org [13], you’ll see that there are actually higher versions of Python available. Pythonversions 3 and above contain some big changes and are going to take some time for the Python usercommunity to adopt. You may see some information about Python 3 in your textbook that will giveyou an idea of the changes coming in that version. You can read this information if you're interested,but it's not applicable to this course.

Python comes with a simple default editor called IDLE; however, in this course you’ll use thePythonWin integrated development environment (IDE) to help you write code. PythonWin is free, hasbasic debugging capabilities, and is included with ArcGIS. The only catch is that it is not installed bydefault with ArcGIS; you have to do it manually by following the steps below. If you are using ArcGIS10.1 (or higher), replace any instances of 2.6 or 26 below with 2.7 or 27, respectively. If you do nothave the DVD you can download PythonWin [14]. Please make sure you use the "win32" version

(either 2.6 or 2.7 depending on your version of ArcGIS / Python) not the "amd64" executables whichare for installing the 64-bit version of PythonWin, which is only compatible with ArcGIS for Server, notArcGIS for Desktop.

Insert the ArcGIS Education Edition DVD into your computer.1.

Dismiss any welcome screens that appear and choose Start > My Computer (or “Computer” onWindows Vista or Windows 7).

2.

Find your DVD drive, right-click it, and click Open. Your goal is to get to the folder structure ofthe DVD, not run the Auto Play that shows the Esri welcome screen.

3.

Once you’ve successfully displayed the folder structure, open the Desktop folder.4. Open the PythonWin folder.5. Start the install by launching pywin32-210.win32-py2.6 (or whatever file is not the PythonWin6.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

18 of 40 9/25/2014 12:31 PM

Page 19: Lesson1_Introduction to GIS Modeling and Python

readme file). If you are using Windows Vista or Windows 7, right-click this file and choose Run

as Administrator and, when prompted, choose to Allow it to run.

Click Next through the wizard to install PythonWin.7. PythonWin doesn't put a Windows shortcut anywhere, so you get to make one yourself. Oncethe install completes, use My Computer (or "Computer") to browse to the location where youinstalled PythonWin. It's probably in C:\Python26\ArcGIS10.0\Lib\site-packages\pythonwin.

8.

Right-click the item Pythonwin and click Create Shortcut. You should see a Windows shortcutappear immediately below the Pythonwin item.

9.

Drag and drop the shortcut onto your Desktop or wherever else you want to put it.10.

On Windows Vista or Windows 7, if you see error messages during install, it’s likely that you did notrun the install as an Administrator. When you launch the install, make sure you right-click and

choose Run as Administrator.

1.4.4 Exploring PythonWin

Here’s a brief explanation of the main parts of PythonWin. Before you begin reading, openPythonWin so you can follow along.

When PythonWin opens, you’ll see what’s known as the Interactive Window. You can type a line ofPython at the >>> prompt and it will immediately execute and print the result, if there is a printableresult. The Interactive Window can be a good place to practice with Python in this course, andwhenever you see some Python code next to the >>> prompt in the lesson materials, this means youcan type it in the Interactive Window to follow along. In these ways, the Interactive Window is verysimilar to the Python window in ArcGIS.

To actually write a new script, click File > New and choose Python Script. Notice a blank pageopens that looks a whole lot like Notepad. However, the nice thing about this interface is that thecode is color-coded and the default font, Courier, is one typically used by programmers. Spacing andindentation, which are important in Python, are also easy to keep track of in this interface.

The Standard toolbar contains tools for

loading, running, and saving scripts. This toolbar is visible by default. Notice the Undo / Redo

buttons , which can be useful to you as a programmer if you start coding something andrealize you’ve gone down the wrong path, or if you delete a line of code and want to get it back. Also

notice the Run button , which looks like a little running person. This is a good way to test yourscripts without having to double-click the file in Windows Explorer.

The Debugging toolbar contains tools for carefully reviewing

your code line-by-line to help you detect errors. This toolbar is visible by clicking View > Toolbars >

Debugging. The Debugging toolbar is extremely valuable to you as a programmer and you’ll learnhow to use it later in this course. This toolbar is one of the main reasons to use an IntegratedDevelopment Environment (IDE) instead of writing your code in a simple text editor like Notepad.

1.5.1 Working with variables

It’s time to get some practice with some beginning programming concepts that will help you writesome simple scripts in Python by the end of Lesson 1. We’ll start by looking at variables.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

19 of 40 9/25/2014 12:31 PM

Page 20: Lesson1_Introduction to GIS Modeling and Python

Remember your first introductory algebra class where you learned that a letter could represent anynumber, like in the statement x + 3? This may have been your first exposure to variables. (Sorry if thememory is traumatic!) In computer science, variables represent values or objects you want thecomputer to store in its memory for use later in the program.

Variables are frequently used to represent not only numbers, but also text and “Boolean” values(‘true’ or ‘false’). A variable might be used to store input from the program’s user, to store valuesreturned from another program, to represent constant values, and so on.

Variables make your code readable and flexible. If you hard-code your values, meaning that youalways use the literal value, your code is useful only in one particular scenario. You could manuallychange the values in your code to fit a different scenario, but this is tedious and exposes you togreater risk of making a mistake (suppose you forget to change a value). Variables, on the otherhand, allow your code to be useful in many scenarios and are easy to parameterize, meaning youcan let users change the values to whatever they need.

To see some variables in action, open PythonWin and type this in the Interactive Window:

>>> x = 2

You’ve just created, or declared, a variable, x, and set its value to 2. In some strongly-typedprogramming languages, such as Java, you would be required to tell the program that you werecreating a numerical variable, but Python assumes this when it sees the 2.

When you hit Enter, nothing happens, but the program now has this variable in memory. To provethis, type:

>>> x + 3

You see the answer of this mathematical expression, 5, appear immediately in the InteractiveWindow, proving that your variable was remembered and used.

You can also use the print command to write the results of operations. We’ll use this a lot whenpracticing and testing code.

>>>print x + 35

Variables can also represent words, or strings, as they are referred to by programmers. Try typingthis in the Interactive Window:

>>>myTeam = "Nittany Lions">>>print myTeamNittany Lions

In this example, the quotation marks tell Python that you are declaring a string variable. Python is apowerful language for working with strings. A very simple example of string manipulation is to add, orconcatenate, two strings, like this:

>>> string1 = "We are ">>> string2 = "Penn State!">>> print string1 + string2We are Penn State!

You can include a number in a string variable by putting it in quotes, but you must thereafter treat itlike a string; you cannot treat it like a number. For example, this results in an error:

>>>myValue = "3"

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

20 of 40 9/25/2014 12:31 PM

Page 21: Lesson1_Introduction to GIS Modeling and Python

>>>print myValue + 2

In these examples you’ve seen the use of the = sign to assign the value of the variable. You canalways reassign the variable. For example:

>>> x = 5>>> x = x - 2>>> print x3

When naming your variables, the following tips will help you avoid errors.

Variable names are case sensitive. myVariable is a different variable than MyVariable.Variable names cannot contain spaces.Variable names cannot begin with a number.A recommended practice for Python variables is to name the variable beginning with alower-case letter, then begin each subsequent word with a capital letter. This is sometimesknown as camel casing. For example: myVariable, mySecondVariable, roadsTable, bufferField1,etc.Variables cannot be any of the special Python reserved words such as "import" or "print."

Make variable names meaningful so that others can easily read your code. This will also help youread your code and avoid making mistakes.

You’ll get plenty of experience working with variables throughout this course and will learn more infuture lessons.

Readings

Read Zandbergen chapter 4.5 (Variables and naming).

Chapter 4 covers the basics of Python syntax, loops, strings and other things which we will lookat in more detail in Lesson 2 but feel free to read ahead a little now if you have time or comeback to it at the end of Lesson 1 to prepare for Lesson 2.

1.5.2 Objects and object-oriented programming

The number and string variables that we worked with above represent data types that are built intoPython. Variables can also represent other things, such as GIS datasets, tables, rows, and thegeoprocessor that we saw earlier that can run tools. All of these things are objects that you use whenyou work with ArcGIS in Python.

In Python, everything is an object. All objects have:

A unique ID, or location in the computer’s memoryA set of properties that describe the objectA set of methods, or things that the object can do

One way to understand objects is to compare performing an operation in a procedural language (likeFORTRAN) to performing the same operation in an object-oriented language. We'll pretend that weare writing a program to make a peanut butter and jelly sandwich. If we were to write the program ina procedural language, it would flow something like this:

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

21 of 40 9/25/2014 12:31 PM

Page 22: Lesson1_Introduction to GIS Modeling and Python

Go to the refrigerator and get the jelly and bread.1. Go to the cupboard and get the peanut butter.2. Take out two slices of bread.3. Open the jars.4. Get a knife.5. Put some peanut butter on the knife.6. etc.7. etc.8.

If we were to write the program in an object-oriented language, it might look like this:

mySandwich = Sandwich.Make1. mySandwich.Bread = Wheat2. mySandwich.Add(PeanutButter)3. mySandwich.Add(Jelly)4.

In the object-oriented example, the bulk of the steps have been eliminated. The sandwich object"knows how" to build itself, given just a few pieces of information. This is an important feature ofobject-oriented languages known as encapsulation.

Notice that you can define the properties of the sandwich (like the bread type) and perform methods(remember that these are actions) on the sandwich, such as adding the peanut butter and jelly.

1.5.3 Classes

The reason it’s so easy to "make a sandwich" in an object-oriented language is that someprogrammer, somewhere, already did the work to define what a sandwich is and what you can dowith it. He or she did this using a class. A class defines how to create an object, the properties andmethods available to that object, how the properties are set and used, and what each method does.

A class may be thought of as a blueprint for creating objects. The blueprint determines whatproperties and methods an object of that class will have. A common analogy is that of a car factory. Acar factory produces thousands of cars of the same model that are all built on the same basicblueprint. In the same way, a class produces objects that have the same predefined properties andmethods.

In Python, classes are grouped together into modules. You import modules into your code to tell yourprogram what objects you’ll be working with. You can write modules yourself, but most likely you'llbring them in from other parties or software packages. For example, the first line of most scripts youwrite in this course will be:

import arcpy

Here you're using the import keyword to tell your script that you’ll be working with the arcpy module,which is provided as part of ArcGIS. After importing this module, you can create objects that leverageArcGIS in your scripts.

Other modules that you may import in this course are os (allows you to work with the operatingsystem), random (allows for generation of random numbers), and math (allows you to work withadvanced math operations). These modules are included with Python, but they aren't imported bydefault. A best practice for keeping your scripts fast is to import only the modules that you need forthat particular script. For example, although it might not cause any errors in your script, you wouldn'tinclude import arcpy in a script not requiring any ArcGIS functions.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

22 of 40 9/25/2014 12:31 PM

Page 23: Lesson1_Introduction to GIS Modeling and Python

Readings

Read Zandbergen chapter 5.8 (Classes) for more information about classes.

1.5.4 Inheritance

Another important feature of object-oriented languages is inheritance. Classes are arranged in ahierarchical relationship such that each class inherits its properties and methods from the classabove it in the hierarchy (its parent class or superclass). A class also passes along its properties andmethods to the class below it (its child class or subclass). A real-world analogy involves theclassification of animal species. As a species, we have many characteristics that are unique tohumans. However, we also inherit many characteristics from classes higher in the class hierarchy. Wehave some characteristics as a result of being vertebrates. We have other characteristics as a resultof being mammals. To illustrate the point, think of the ability of humans to run. Our bodies respond toour command to run not because we belong to the "human" class, but because we inherit that traitfrom some class higher in the class hierarchy.

Back in the programming context, the lesson to be learned is that it pays to know where a class fitsinto the class hierarchy. Without that piece of information, you will be unaware of all of the operationsavailable to you. This information about inheritance can often be found in informational posters calledobject model diagrams.

Here's an example of the object model diagram for ArcGIS Python scripting at 9.3 [15] (unfortunately,there is no poster at ArcGIS 10, but the 9.3 poster still comes in handy for some things like this).Take a look at the green box titled FeatureClass and notice at the bottom it says Dataset properties.This is because FeatureClass inherits all properties from Dataset. Therefore any properties on aDataset object, such as Extent or SpatialReference, can also be obtained if you create aFeatureClass object. Apart from all the properties it inherits from Dataset, the FeatureClass has itsown specialized properties such as FeatureType and ShapeType.

1.5.5 Python syntax

Every programming language has rules about capitalization, white space, how to set apart lines ofcode and procedures, and so on. Here are some basic syntax rules to remember for Python:

Python is case-sensitive both in variable names and reserved words. That means it’s importantwhether you use upper or lower-case. The all lower-case "print" is a reserved word in Pythonthat will print a value, while "Print" is unrecognized by Python and will return an error. Likewisearcpy is very sensitive about case and will return an error if you try to run a tool withoutcapitalizing the tool name.You end a Python statement by pressing Enter and literally beginning a new line. (In someother languages, a special character, such as a semicolon, denotes the end of a statement.) It’sokay to add empty lines to divide your code into logical sections.If you have a long statement that you want to display on multiple lines for readability, you needto use a line continuation character, which in Python is a backslash (\). You can then continuetyping on the line below and Python will interpret the line sequence as one statement. Oneexception is if you’re in the middle of parentheses () or brackets [], Python understands thatyou are continuing lines and no backslash is required.Indentation is required in Python to logically group together certain lines, or blocks, of code.You should indent your code four spaces inside loops, if/then statements, and try/exceptstatements. In most programming languages developers are encouraged to use indentation to

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

23 of 40 9/25/2014 12:31 PM

Page 24: Lesson1_Introduction to GIS Modeling and Python

logically group together blocks of code; however in Python, indentation of these languageconstructs is not only encouraged, but required. Though this requirement may seemburdensome, it does result in greater readability.You can add a comment to your code by beginning the line with a pound (#) sign. Commentsare lines that you include to explain what the code is doing. Comments are ignored by Pythonwhen it runs the script, so you can add them at any place in your code without worrying abouttheir effect. Comments help others who may have to work with your code in the future; and theymay even help you remember what the code does.

1.6.1 Introductory Python examples

Let’s look at a few example scripts to see how these rules are applied. The first example script isaccompanied with a walkthrough video that explains what happens in each line of the code. You canalso review the main points about each script after reading the code.

1.6.2 Example: Printing the spatial reference ofa feature class

This first example script reports the spatial reference (coordinate system) of a feature class stored ina geodatabase:

This may look intimidating at first, so let’s go through what’s happening in this script, line by line.Watch this video to get a visual walkthrough of the code.

123456789101112

# Opens a feature class from a geodatabase and prints the spatial reference import arcpy featureClass = "C:/Data/USA/USA.gdb/StateBoundaries" # Describe the feature class and get its spatial reference desc = arcpy.Describe(featureClass)spatialRef = desc.SpatialReference # Print the spatial reference nameprint spatialRef.Name

?

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

24 of 40 9/25/2014 12:31 PM

Page 25: Lesson1_Introduction to GIS Modeling and Python

Again, notice that:

A comment begins the script to explain what’s going to happen.Case sensitivity is applied in the code. "import" is all lower-case. So is "print". The modulename "arcpy" is always referred to as "arcpy," not "ARCPY" or "Arcpy". Similarly, "Describe" iscapitalized in arcpy.Describe.The variable names featureClass, desc, and spatialRef that the programmer assigned areshort, but intuitive. By looking at the variable name, you can quickly guess what it represents.The script creates objects and uses a combination of properties and methods on those objectsto get the job done. That’s how object-oriented programming works.

Trying the example for yourself

The best way to get familiar with a new programming languages is to look at example code andpractice with it yourself. See if you can modify the script above to report the spatial reference of afeature class on your computer. In my example the feature class is in a file geodatabase; you’ll needto modify the structure of the featureClass path if you are using a shapefile (for example, you'll put.shp at the end of the file name, and you won't have .gdb in your path).

Follow this pattern to try the example:

Open PythonWin and click File > New.1.

Choose to make a Python script and click OK.2. Paste in the code above and modify it to fit your data (change the path).3. Save your script as a .py file.4.

Click the Run button to run the script. Make sure the Interactive Window is visible when you dothis, because this is where you’ll see the output from the print keyword. The print keyword does

5.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

25 of 40 9/25/2014 12:31 PM

Page 26: Lesson1_Introduction to GIS Modeling and Python

not actually cause a hard copy to be printed!

Readings

We'll take a short break and do some reading from another source. If you are new to Python scripting

it can be helpful to see the concepts from another point of view.

Read parts of Zandbergen chapters 4 & 5. This is around 30 pages but will be a valuable chapter

introducing you to Python in ArcGIS and also how to work with tools and toolboxes (very useful for

Project 1) and also some concepts which we'll revisit later in Lesson 2 (don't worry if the bits we skip

over seem daunting - we'll explain those in Lesson 2).

Chapter 4 deals with the fundamentals of Python and we will need a few of these to get startedand we'll revisit this chapter in Lesson 2. For now read sections 4.1-4.7 revising what we read in4.5 earlier. Chapter 5 talks about working with arcpy and functions - read sections 5.1-5.6.

1.6.3 Example: Performing map algebra on araster

Here’s another simple script that finds all cells over 3500 meters in an elevation raster and makes anew raster that codes all those cells as 1. Remaining values in the new raster are coded as 0. Thistype of “map algebra” operation is common in site selection and other GIS scenarios.

Something you may not recognize below is the expression Raster(inRaster). This function just tellsArcGIS that it needs to treat your inRaster variable as a raster dataset so that you can perform mapalgebra on it. If you didn't do this, the script would treat inRaster as just a literal string of characters(the path) instead of a raster dataset.

1234567891011121314151617

# This script uses map algebra to find values in an# elevation raster greater than 3500 (meters). import arcpyfrom arcpy.sa import * # Specify the input rasterinRaster = "C:/Data/Elevation/foxlake"cutoffElevation = 3500 # Check out the Spatial Analyst extensionarcpy.CheckOutExtension("Spatial") # Make a map algebra expression and save the resulting rasteroutRaster = Raster(inRaster) > cutoffElevationoutRaster.save("C:/Data/Elevation/foxlake_hi_10")

?

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

26 of 40 9/25/2014 12:31 PM

Page 27: Lesson1_Introduction to GIS Modeling and Python

Begin by examining this script and trying to figure out as much as you can based on what youremember from the previous scripts you’ve seen.

The main points to remember on this script are:

Notice the lines of code that check out the Spatial Analyst extension before doing any mapalgebra and check it back in after finishing. Because each line of code takes some time to run,avoid putting unnecessary code between checkout and checkin. This allows others in yourorganization to use the extension if licenses are limited. The extension automatically getschecked back in when your script ends, thus some of the Esri code examples you will see donot check it in. However, it is a good practice to explicitly check it in, just in case you have somelong code that needs to execute afterward, or in case your script crashes and against yourintentions "hangs onto" the license.inRaster begins as a string, but is then casted to, or treated as, a Raster object [16]once you runRaster(inRaster). A Raster object is a special object used for working with raster datasets inArcGIS. It's not available in just any Python script: you can use it only if you import the arcpymodule at the top of your script.cutoffElevation is a number variable that you declare early in your script and then use later onwhen you build the map algebra expression for your outRaster.Your expression outRaster = Raster(inRaster) > cutoffElevation is saying, in plain terms, "Makea new raster and call it outRaster. Do this by taking all the cells of the raster dataset at the pathof inRaster that are greater than the number I assigned to the variable cutoffElevation."outRaster is also a Raster object, but you have to call the method outRaster.save() in order tomake it permanent on disk. The save() method takes one argument, which is the path to whichyou want to save.

Now try to run the script yourself using the FoxLake digital elevation model (DEM) in your Lesson 1data folder. If it doesn’t work the first time, verify that:

You have supplied the correct input and output paths.Your path name contains forward slashes (/) or double backslashes (\\), not single backslashes(\).You have the Spatial Analyst Extension installed and enabled. To check this, open ArcMap,

click Customize > Extensions and ensure Spatial Analyst is checked.You do not have any of the datasets open in ArcMap.The output data does not exist yet. If you want to be able to overwrite the output, you need toadd the line arcpy.env.overwriteOutput = True. This line can be placed immediately after importarcpy

You can experiment with this script using different values in the map algebra expression (try 3000 forexample).

Readings

Read the sections of Chapter 5 that talk about environment variables and licenses (5.9 & 5.11) which

we covered in this part of the lesson.

1819

# Check in the Spatial Analyst extension now that you're donearcpy.CheckInExtension("Spatial")

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

27 of 40 9/25/2014 12:31 PM

Page 28: Lesson1_Introduction to GIS Modeling and Python

1.6.4 Example: Creating buffers

Think about the previous example where you ran some map algebra on an elevation raster. If youwanted to change the value of your cutoff elevation to 2500 instead of 3500, you had to open thescript itself and change the value of the cutoffElevation variable in the code.

This third example is a little different. Instead of hard-coding the values needed for the tool (in otherwords, literally including the values in the script) we’ll use some user input variables, or parameters.This allows people to try different values in the script without altering the code itself. Just like inModelBuilder, parameters make your script available to a wider audience.

The simple example below just runs the Buffer tool, but it allows the user to enter the path of theinput and output datasets as well as the distance of the buffer. The user-supplied parameters maketheir way into the script with the arcpy.GetParameterAsText() method.

Examine the script below carefully, but don't try to run it yet. You'll do that in the next part of thelesson.

Again, examine the above code line by line and figure out as much as you can about what the codedoes. If necessary, print the code and write notes next to each line. Here are some of the main pointsto understand:

GetParameterAsText() is a function in the arcpy module. Notice that it takes a zero-basedinteger (0, 1, 2, 3, etc.) as an argument. If you’re going to go ahead and make a tool out of thisscript, as we are going to do in the next page of this lesson, then it’s important you define theparameters in the same order you want them to appear in the tool’s dialog.When we called the Buffer tool in this script, we supplied only three parameters. By notsupplying any more, we accepted the default values for the rest of the tool’s parameter (SideType, End Type, etc.).

123456789101112131415161718192021222324

# This script runs the Buffer tool. The user supplies the input# and output paths, and the buffer distance. import arcpyarcpy.env.overwriteOutput = True try: # Get the input parameters for the Buffer tool inPath = arcpy.GetParameterAsText(0) outPath = arcpy.GetParameterAsText(1) bufferDistance = arcpy.GetParameterAsText(2) # Run the Buffer tool arcpy.Buffer_analysis(inPath, outPath, bufferDistance) # Report a success message arcpy.AddMessage("All done!") except: # Report an error messages arcpy.AddError("Could not complete the buffer") # Report any error messages that the Buffer tool might have generated arcpy.AddMessage(arcpy.GetMessages())

?

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

28 of 40 9/25/2014 12:31 PM

Page 29: Lesson1_Introduction to GIS Modeling and Python

The try and except blocks of code are a way that you can prevent your script from crashing ifthere is an error. Your script attempts to run all of the code in the try block. If the script cannotcontinue for some reason, it jumps down and runs the code in the except block. Insertingtry/except blocks like this is a good practice to do once you think you've gotten all the errors outof your script, or when you want to make sure your code will run a certain line at the end nomatter what happens.

When you are first writing and debugging your script, sometimes it's more useful to leave outtry/except and let the code crash, because the (red) error messages reported in the InteractiveWindow sometimes give you better clues on how to diagnose the problem in your code.Suppose you put a print statement in your except block saying "There was an error. Please tryagain." For the end user of your script, this is nicer than seeing a nasty (red) error message;however, as a programmer debugging the script, you want to see the (red) error message to getany insight you can about what went wrong.

Projects that you submit in this course require error handling using try/except in order to receivefull credit.The arcpy.AddMessage() and arcpy.AddError() methods are ways of adding additionalmessages to the user of the tool. Whenever you run a tool, the geoprocessor prints messages,which you have probably seen before (for example, “Executed (Buffer) successfully. End time:Sat Oct 03 07:37:31 2009”). You have the power to add more messages through thesemethods. The messages have differing levels of severity, hence different methods forAddMessage and AddError. Sometimes people choose to view only the errors instead of all themessages, or they do a quick visual scan of the messages for errors.

When you use arcpy.GetMessages(), you get all the messages generated by the tool itself.These will tell you things such as whether the user entered invalid parameters. Notice in thisscript the somewhat complex syntax you have to use to first get the messages, then add them:arcpy.AddMessage(arcpy.GetMessages()). If this line of code is confusing to understand,remember that the order of functions works like math operations: you start by working insidethe parentheses first to get the messages, then you add them.

The AddError and AddMessage methods are only used when making script tools (which you'lllearn about in the very next section). When you are just running a script in PythonWin (notmaking a script tool), you can still get the messages using a print statement withGetMessages(), like this: print arcpy.GetMessages().

Readings

Read the section of Chapter 5 that talks about working with tool messages (5.10) for another

perspective on handling tool output.

1.7.1 Making a script tool

User input variables that you retrieve through GetParameterAsText() make your script very easy toconvert into a tool in ArcGIS. A few people know how to alter Python code, a few more can run aPython script and supply user input variables, but almost all ArcGIS users know how to openArcToolbox and run a tool. To finish off this lesson, we’ll take the previous script and make it into atool that can easily be run in ArcGIS.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

29 of 40 9/25/2014 12:31 PM

Page 30: Lesson1_Introduction to GIS Modeling and Python

Before you begin this exercise, I strongly recommend that you read the first four topics in the ArcGISDesktop Help section Creating script tools with Python scripts [17]. You likely will not understand allthe parts of this section yet, but it will give you some familiarity with script tools that will be helpfulduring the exercise.

Follow these steps to make a script tool:

Copy the code from Lesson 1.6.4 "Example: Creating Buffers" into a new PythonWin script andsave it as buffer_user_input.py.

1.

Open ArcMap and display the Catalog window.2.

Expand the nodes Toolboxes > My Toolboxes.3.

Right-click My Toolboxes and click New > Toolbox.4. Give your toolbox a name, such as "MyScriptTools".5.

Right-click your new toolbox and click Add > Script.6.

Fill in the Name, Label, and Description properties for your Script tool as shown below:

Figure 1.10 Entering information for your script tool.

7.

Click Next and supply the Script File. To do this, click the folder icon and browse to yourbuffer_user_input.py file.

8.

Click Next and examine the dialog that appears. This is where you can specify the parametersof your script. The parameters are the values for which you used arcpy.GetParameterAsText() inyour script, namely inPath, outPath, and bufferMiles. You will use this dialog to list thoseparameters in the same order, except you can give the parameters names that are easier tounderstand.

9.

In the Display Name column that you see at the top of this wizard, click the first empty cell andtype “Input Feature Class”.

10.

Immediately to the right, click the first empty cell in the Data Type column and choose Feature

Class. Here is one of the huge advantages of making a script tool. Instead of accepting anystring as input (which could contain an error), your tool will now enforce the requirement that a

11.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

30 of 40 9/25/2014 12:31 PM

Page 31: Lesson1_Introduction to GIS Modeling and Python

feature class be used as input. ArcGIS will help you by confirming that the value entered is apath to a valid feature class. It will even supply the users of your tool with a browse button sothey can browse to the feature class.

Figure 1.11 Choosing "Feature Class."Just as you did in the previous steps, add a second parameter named “Output Feature Class”.

The data type should again be Feature Class.

12.

With the Output Feature Class parameter still highlighted, look down at the Parameter

Properties portion of the dialog. Change the Direction property to Output.

13.

Add a third property named “Buffer Distance”. Choose Linear Unit as the data type. This datatype will allow the user of the tool to select both the distance value and the units (for example,miles, kilometers, etc.).

14.

With the Buffer Distance parameter still highlighted, look down at the Parameter Properties

section again. Set the Default property to “5 Miles” (do not include the quotes). Your dialogshould look like what you see below:

Figure 1.11 Choosing "Feature Class."

15.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

31 of 40 9/25/2014 12:31 PM

Page 32: Lesson1_Introduction to GIS Modeling and Python

Figure 1.12 Setting the Defailt property to "5 Miles."

Click Finish and, in the Catalog window, open your new script tool by double-clicking it.16. Try out your tool by buffering any feature class on your computer. Notice that once you supplythe input feature class, an output feature class path is suggested for you. This is because youspecifically set Output Feature Class as an output parameter. Also, when the tool is complete,examine the Results window for the custom message "All done!" that you added in your code.

Figure 1.11 Choosing "Feature Class."

17.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

32 of 40 9/25/2014 12:31 PM

Page 33: Lesson1_Introduction to GIS Modeling and Python

Figure 1.13 The tool is complete.

This is a very simple example and obviously you could just run the out-of-the-box Buffer tool withsimilar results. Normally when you create a script tool, it will be backed with a script that runs acombination of tools and applies some logic that makes those tools uniquely useful.

There’s another benefit to this example, though. Notice the simplicity of our script tool dialogcompared to the main Buffer tool:

Figure 1.14 Comparison of our script tool with the main buffer tool.

At some point you may need to design a set of tools for beginning GIS users where only the mostnecessary parameters are exposed. You may also do this to enforce quality control if you know thatsome of the parameters must always be set to certain defaults and you want to avoid the scenariowhere a beginning user (or a rogue user) might change the required values. A simple script tool iseffective for simplifying the tool dialog in this way.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

33 of 40 9/25/2014 12:31 PM

Page 34: Lesson1_Introduction to GIS Modeling and Python

Readings

Read Zandbergen 2.10 - 2.13 to reinforce what you learned during this lesson about scripts andscript tools.

Lesson 1 Practice Exercises

Each lesson in this course includes some simple practice exercises with Python. These are notsubmitted or graded, but they are highly recommended if you are new to programming or if theproject initially looks challenging. Lessons 1 and 2 contain shorter exercises, while Lessons 3 and 4contain longer, more holistic exercises. Each practice exercise has an accompanying solution thatyou should carefully study.

Remember to choose File > New in PythonWin to create a new script (or click the empty page icon).You can name the scripts something like Practice1, Practice2, etc. To execute a script in PythonWin,click the "running man" icon.

Say helloCreate a string variable called x and assign it the value "Hello". Display the contents of the xvariable in the Interactive Window.

Practice 1 Solution [18]

1.

Concatenate two stringsCreate a string variable called first and assign to it your first name. Likewise, create a stringvariable called last and assign to it your last name. Concatenate (merge) the two stringstogether, making sure to also include a space between them.

Practice 2 Solution [19]

2.

Pass a value to a script as a parameterExample 1.6.4 shows the use of the arcpy.GetParameterAsText() method. This method istypically used in conjunction with an ArcGIS script tool that has been designed to prompt theuser to enter the required parameters. However, you may have noticed that the little dialog thatappears after clicking the Run button in PythonWin also includes a place to supply arguments.

For this exercise, write a script that accepts a single string value using the GetParameterAsTextmethod. The value entered should be a name and that name should be concatenated with theliteral string "Hi, " and displayed in the Interactive Window. Test the script from withinPythonWin, entering a name (in quotes) in the Arguments text box after clicking the Runbutton.

Practice 3 Solution [20]

3.

Report the geometry type of a feature classExample 1.6.2 demonstrates the use of the Describe method to report the spatial reference of afeature class. The Describe method returns an object that has a number of properties that canvary depending on what type of object you Described. A feature class has a spatialReferenceproperty by virtue of the fact that it is a type of Dataset. (Rasters are another type of Datasetand also have a spatialReference property.)

The Describe method's page in the Help [21] lists the types of objects that the method can beused on. Clicking the Dataset link pulls up a list of the properties available when you Describea dataset, spatialReference being just one of several.

4.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

34 of 40 9/25/2014 12:31 PM

Page 35: Lesson1_Introduction to GIS Modeling and Python

For this exercise, use the Describe method again; this time, to determine the type of geometry(point, polyline or polygon) stored in a feature class. I won't tell you the name of the propertythat returns this information. But I will give you the hint that feature classes have this mysteryproperty not because they're a type of Dataset as with the spatialReference property, butbecause they're objects of the type FeatureClass.

Practice 4 Solution [22]

Project 1, Part I: Modeling precipitation zonesin Nebraska

Suppose you're working on a project for the Nebraska Department of Agriculture and you are taskedwith making some maps of precipitation in the state. Members of the department want to see whichparts of the state were relatively dry and wet in the past year, classified in zones. All you have is aseries of weather station readings of cumulative rainfall for 2008 that you've obtained from within

Nebraska and surrounding areas. This is a shapefile of points called Precip2008Readings.shp. It isin your Lesson 1 data folder.

Precip2008Readings.shp is a fictional dataset created for this project. The locations do notcorrespond to actual weather stations. However, the measurements are derived from real 2008precipitation data created by the PRISM Climate Group [23] at Oregon State University, 2009.

You need to do several tasks in order to get this data ready for mapping:

Interpolate a precipitation surface from your points. This creates a raster dataset with estimatedprecipitation values for your entire area of interest. You've already planned for this, knowing thatyou are going to use inverse distance weighted (IDW) interpolation. Click the following link tolearn how the IDW technique works. [24] You've also selected your points to include some areasaround Nebraska to avoid edge effects in the interpolation.Reclassify the interpolated surface into an ordinal classification of precipitation "zones" thatdelineate relatively dry, medium, and wet regions.Create vector polygons from the zones.Clip the zone polygons to the boundary of Nebraska.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

35 of 40 9/25/2014 12:31 PM

Page 36: Lesson1_Introduction to GIS Modeling and Python

Figure 1.15 Mapping the data.

It's very possible that you'll want to repeat the above process in order to test different IDWinterpolation parameters or make similar maps with other datasets (such as next year's precipitation

data). Therefore, the above series of tasks is well-suited to ModelBuilder. Your job is to create a

model that can complete the above series of steps without you having to manually open four

different tools.

Model parameters

Your model should have these (and only these) parameters:

Input precipitation readings- This is the location of your precipitation readings point data. Thisis a model parameter so that the model can be easily re-run with other datasets.

1.

Power- An IDW setting specifying how quickly influence of surrounding points decreases asyou move away from the point to be interpolated.

2.

Search radius- An IDW setting determining how many surrounding points are included in theinterpolation of a point. The search radius can be fixed at a certain distance, including whatevernumber of points happen to fall within, or its distance can vary in order for it to always include aminimum number of points. When you use ModelBuilder, you don't have to set up any of thesechoices; ModelBuilder does it for you when you set the Search Radius as a model parameter.

3.

Zone boundaries- This is a table allowing the user of the model to specify the zoneboundaries. For example, you could configure precipitation values of 0 - 30000 to result in areclassification of 1 (to correspond with Zone 1), 30000 - 60000 could result in a classification of

4.

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

36 of 40 9/25/2014 12:31 PM

Page 37: Lesson1_Introduction to GIS Modeling and Python

2 (to correspond with Zone 2), and so on. The way to get this table is to make a variable from

the Reclassification parameter of the Reclassify tool and set it as a model parameter.

Output precipitation zones- This is the location where you want the output dataset of clippedvector zones to be placed on disk.

5.

As you build your model, you will need to configure some settings that will not be exposed as

parameters. These include the clip feature, which is the state of Nebraska outline Nebraska.shp inyour Lesson 1 data folder. There are many other settings such as "Z Value field" and "Input barrierpolyline features" (for IDW) or "Reclass field" (for Reclassify) that should not be exposed asparameters. You should just set these values once when you build your model. If you ever asksomeone else to run this model, you don't want them to be overwhelmed with choices stemming fromevery tool in the model; you should just expose the essential things they might want to change.

For this particular model, you should assume that any input dataset will conform to the same schemaas your Precip2008Readings.shp feature class. For example, an analyst should be able to submit asimilar Precip2009Readings dataset with the same fields, field names, and data types. However, heor she should not expect to provide any feature class with a different set of fields and field names,etc. As you might discover, handling all types of feature class schemas would make your model morecomplex than we want for this assignment.

When you double-click the model to run it, the interface should look like the following:

Figure 1.16 The model interface.

Running the model with the exact parameters listed above should result in the following (I havesymbolized the zones in ArcMap with different colors to help distinguish them). This is one way youcan check your work:

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

37 of 40 9/25/2014 12:31 PM

Page 38: Lesson1_Introduction to GIS Modeling and Python

Figure 1.17 The completed model output.

Deliverables

The deliverables for this project are:

The .tbx file of the toolbox containing your model. The easiest way to find it is to right-click your

toolbox in the Catalog window, click Properties, and note the Location. If you can't browse tothis path in Windows Explorer, you'll need to enable the Windows option to show hidden filesand folders.A screen capture of the model interface before you run the model (it should look a lot like theabove image, although you can set your own reclassification values, power, etc.)A screen capture of your the model result in ArcMap, with zones symbolized in different colors.You don't have to use the Layout view for this project.

Successful delivery of the above requirements is sufficient to earn 90% on the project. The remaining10% is reserved for efforts that go "over and above" the minimum requirements. This could include(but is not limited to) meaningful labels on and around model elements, analysis of how differentinput values affect the output, substitution of some other interpolation method instead of IDW (forexample Kriging), documentation for your model parameters that appears in the side-panel help, ordemonstration of how your model was successfully run on a different input dataset.

Tips

The following tips may help you as you build your model:

Your model needs to include the following tools in this order: IDW (from the Spatial Analyst

toolbox), Reclassify, Raster to Polygon, Clip (from the Analysis toolbox).

An easy way to find the tools you need in ArcMap is to click Windows > Search and type thename of the tool you want in the search box. Be careful when multiple tools have the samename. You'll typically be using tools from the Spatial Analyst toolbox in this assignment.Once you drag and drop a tool onto the ModelBuilder canvas, double-click it and set all theparameters the way you want. These will be the default settings for your model.If there is a certain parameter for a tool that you want to expose as a model parameter,

right-click the tool in the ModelBuilder canvas, then click Make Variable > From Parameter

and choose the parameter. Once the oval appears for the variable, right-click it and click Model

Parameter.If you receive errors that a tool is not able to run, or that no Spatial Analyst Extension is

installed, you may need to enable the extension. In ArcMap, click Customize > Extensions

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

38 of 40 9/25/2014 12:31 PM

Page 39: Lesson1_Introduction to GIS Modeling and Python

and then check the Spatial Analyst checkbox.

Project 1, Part II: Creating contours for the FoxLake DEM

The second part of Project 1 will help you get some practice with Python. At the end of Lesson 1, yousaw three simple scripting examples; now your task is to write your own script. This script will createvector contour lines from a raster elevation dataset. Don't forget that the ArcGIS Desktop Help [25] canindeed be helpful if you need to figure out the syntax for a particular command.

Earlier in the lesson you were introduced to the Fox Lake DEM in your Lesson 1 data folder.

It represents elevation in the Fox Lake Quadrangle, Utah. Write a script that uses the Contour tool inthe Spatial Analyst toolbox to create contour lines for the quadrangle. The contour interval should be25 meters and the base contour should be 0. Remember that the native units of the DEM are meters,so no unit conversions are required.

Running the script should immediately create a shapefile of contour lines on disk.

Follow these guidelines when writing the script:

The purpose of this exercise is just to get you some practice writing Python code. Therefore,you are not required to use arcpy.GetParameterAsText() to get the input parameters. Go aheadand hard-code the values (such as the path name to the dataset).Consequently, you are not required to create a script tool for this exercise. This will be requiredin Project 2.Your code should run correctly from PythonWin. For full credit, it should also containcomments, attempt to handle errors, and use legal and intuitive variable names.

Deliverables

The deliverables for Project 1, Part II are:

The .py file containing your script.A short writeup (about 300 words) describing what you learned during this project and how youapproached the problem. These writeups will be required on all projects.

Finishing Lesson 1

To complete Lesson 1, please zip all your Project 1 deliverables (for parts I and II) into one file andsubmit them to the Lesson 1 Drop Box in ANGEL. Then take the Lesson 1 Quiz if you haven't taken italready.

Source URL: https://www.e-education.psu.edu/geog485/node/17

Links

[1] https://www.e-education.psu.edu/geog485/user/login?destination=comment/reply/17%23comment-form[2] http://training.esri.com/acb2000/showdetl.cfm?DID=6&amp;Product_ID=971[3] https://www.e-education.psu.edu/geog485/sites/www.e-education.psu.edu.geog485/files/data/Lesson1.zip[4] https://www.e-education.psu.edu/geog485/user/login?destination=comment/reply/30%23comment-form[5] http://resources.arcgis.com/en/help/

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

39 of 40 9/25/2014 12:31 PM

Page 40: Lesson1_Introduction to GIS Modeling and Python

[6] https://www.e-education.psu.edu/geog485/user/login?destination=comment/reply/47%23comment-form[7] http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/A_quick_tour_of_managing_intermediate_data/002w0000000z000000/[8] http://help.arcgis.com/en/arcgisdesktop/10.0/help/0021/002100000037000000.htm[9] http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/Setting_Current_and_Scratch_Workspace_environments/002w00000037000000/[10] http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//00570000000q000000.htm[11] http://help.arcgis.com/en/arcgisdesktop/10.0/help/002w/002w0000001w000000.htm[12] http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//000800000019000000.htm[13] http://www.python.org[14] http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/[15] http://webhelp.esri.com/arcgisdesktop/9.3/pdf/Geoprocessor_93.pdf[16] http://help.arcgis.com/en/arcgisdesktop/10.0/help/00p6/00p60000000r000000.htm[17] http://help.arcgis.com/en/arcgisdesktop/10.0/help/0015/001500000006000000.htm[18] https://www.e-education.psu.edu/geog485/179[19] https://www.e-education.psu.edu/geog485/180[20] https://www.e-education.psu.edu/geog485/181[21] http://help.arcgis.com/en/arcgisdesktop/10.0/help/000v/000v00000026000000.htm[22] https://www.e-education.psu.edu/geog485/182[23] http://www.prismclimate.org[24] http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/How_IDW_works/009z00000075000000/[25] http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html

Lesson 1: Introduction to GIS modeling and Python https://www.e-education.psu.edu/geog485/print/book/export/html/17

40 of 40 9/25/2014 12:31 PM