Вы находитесь на странице: 1из 381

IntroductiontoGISProgramming

andFundamentalswithPythonand

ArcGIS ®

IntroductiontoGISProgramming

andFundamentalswithPythonand

ArcGIS ®

ChaoweiYang

Withthecollaborationof

ManzhuYu

QunyingHuang

ZhenlongLi

MinSun

KaiLiu

YongyaoJiang

JizheXia

FeiHu

ArcGIS ® ChaoweiYang Withthecollaborationof ManzhuYu QunyingHuang ZhenlongLi MinSun KaiLiu YongyaoJiang JizheXia FeiHu

CRCPress Taylor&FrancisGroup

6000BrokenSoundParkwayNW,Suite300

BocaRaton,FL33487-2742

©2017byTaylor&FrancisGroup,LLC

CRCPressisanimprintofTaylor&FrancisGroup,anInformabusiness

NoclaimtooriginalU.S.Governmentworks

Printedonacid-freepaper

InternationalStandardBookNumber-13:978-1-4665-1008-1(Hardback)

Thisbookcontainsinformationobtainedfromauthenticandhighlyregardedsources.Reasonableeffortshave

beenmadetopublishreliabledataandinformation,buttheauthorandpublishercannotassumeresponsibility

forthevalidityofallmaterialsortheconsequencesoftheiruse.Theauthorsandpublishershaveattemptedto

tracethecopyrightholdersofallmaterialreproducedinthispublicationandapologizetocopyrightholdersif

permissiontopublishinthisformhasnotbeenobtained.Ifanycopyrightmaterialhasnotbeenacknowledged

pleasewriteandletusknowsowemayrectifyinanyfuturereprint.

ExceptaspermittedunderU.S.CopyrightLaw,nopartofthisbookmaybereprinted,reproduced,transmitted, orutilizedinanyformbyanyelectronic,mechanical,orothermeans,now knownorhereafterinvented, includingphotocopying,microfilming,andrecording,orinanyinformationstorageorretrievalsystem,without writtenpermissionfromthepublishers.

Forpermissiontophotocopyorusematerialelectronicallyfromthiswork,pleaseaccesswww.copyright.com

(http://www.copyright.com/)orcontacttheCopyrightClearanceCenter,Inc.(CCC),222RosewoodDrive,

Danvers,MA01923,978-750-8400.CCCisanot-for-profitorganizationthatprovideslicensesandregistration

foravarietyofusers.FororganizationsthathavebeengrantedaphotocopylicensebytheCCC,aseparate

systemofpaymenthasbeenarranged.

TrademarkNotice:Productorcorporatenamesmaybetrademarksorregisteredtrademarks,andareused

onlyforidentificationandexplanationwithoutintenttoinfringe.

LibraryofCongressCataloging-in-PublicationData

Names:Yang,Chaowei,author. Title: Introduction to GIS programming and fundamentals with Python and ArcGIS / ChaoweiYang.

Description:BocaRaton,FL:Taylor&Francis,2017.

Identifiers: LCCN 2016047660| ISBN 9781466510081 (hardback : alk. paper) | ISBN

9781466510098(ebook)

Subjects:LCSH:Geographic informationsystems--Design. | Python(Computer program language)|ArcGIS

Classification:LCCG70.212.Y362017|DDC910.285/53--dc23

LCrecordavailableathttps://lccn.loc.gov/2016047660

VisittheTaylor&FrancisWebsiteat

andtheCRCPressWebsiteat

ForChaoweiYang'sparents,ChaoqingYangandMingjuTang,

forcontinuallyinstillingcuriosityandanexploringspirit

Contents Preface Acknowledgments Editor Contributors SectionI Overview 1. Introduction 1.1 ComputerHardwareandSoftware 1.2

Contents

Preface

Acknowledgments

Editor

Contributors

SectionI Overview

1. Introduction

1.1 ComputerHardwareandSoftware

1.2 GISandProgramming

1.3 Python

1.4 ClassandObject

1.5 GISDataModels

1.6 UML

1.7 Hands-OnExperiencewithPython

1.8 ChapterSummary

Problems

2. Object-OrientedProgramming

2.1 ProgrammingLanguageandPython

2.2 ClassandObject

2.2.1 DefiningClasses

2.2.2 ObjectGeneration

2.2.3 Attributes

2.2.4 Inheritance

2.2.5 Composition

2.3 Point,Polyline,andPolygon

2.4 Hands-OnExperiencewithPython

2.5 ChapterSummary

Problems

SectionII PythonProgramming

3. IntroductiontoPython

3.1 Object-OrientedSupport

3.2 Syntax

3.2.1

CaseSensitivity

3.2.2

SpecialCharacters

3.2.3

Indentation

3.2.4

Keywords

3.2.5

MultipleAssignments

3.2.6

Namespace

3.2.7

Scope

3.3 DataTypes

3.3.1 BasicDataTypes

3.3.2 CompositeDataTypes

3.4 Miscellaneous

3.4.1 Variables

3.4.2 CodeStyle

3.5 Operators

3.6 Statements

3.7 Functions

3.8 Hands-OnExperiencewithPython

3.9 ChapterSummary

Problems

4. PythonLanguageControlStructure,FileInput/Output,and

ExceptionHandling

4.1 MakingDecisions

4.2 Loops

4.3 OtherControlStructures

4.4 FileInput/Output

4.5 Exceptions

4.6 Hands-OnExperiencewithPython

4.6.1 FindtheLongestDistancebetweenAnyTwoPoints

4.6.2 Hands-OnExperience:I/O,CreateandReadaFile

4.6.4

Hands-OnExperience:InputGISPointDatafromTextFile

4.7 ChapterSummary

Problems

5. ProgrammingThinkingandVectorDataVisualization

5.1 Problem:VisualizingGISData

5.2 TransformingCoordinateSystem

5.2.1 HowtoDetermineRatioValue?

5.3 VisualizingVectorData

5.4 Point,Polyline,Polygon

5.5 ProgrammingThinking

5.5.1 ProblemAnalysis

5.5.2 ThinkinProgramming

5.5.3 MatchProgrammingLanguagePatternsandStructure

5.5.4 ImplementProgram

5.6 Hands-OnExperiencewithPython

5.6.1 Reading,Parsing,andAnalyzingTextFileData

5.6.2 CreateGISObjectsandCheckIntersection

5.7 ChapterSummary

Problems

6. ShapefileHandling

6.1 BinaryDataManipulation

6.2 ShapefileIntroduction

6.3 ShapefileStructureandInterpretation

6.3.1 MainFileStructureofaShapefile

6.3.1.1 MainFileHeader

6.3.1.2 FeatureRecord

6.3.2 IndexFileStructure(.shx)

6.3.3 The.dbfFile

6.4 GeneralProgrammingSequenceforHandlingShapefiles

6.5 Hands-OnExperiencewithMini-GIS

6.5.1 VisualizePolylinesandPolygons

6.5.2 InterpretPolylineShapefiles

6.6 ChapterSummary

Problems

7.

PythonProgrammingEnvironment

7.1 GeneralPythonIDE

7.1.1 PythonProgrammingWindows

7.1.1.1 Command-LineGUI

7.1.1.2 InteractiveGUI

7.1.1.3 File-BasedProgramming

7.1.2 PythonIDESettings

7.1.2.1 Highlighting

7.1.2.2 GeneralSettingoftheProgrammingWindow

7.1.2.3 FontsSetupfortheCoding

7.1.3 Debugging

7.1.3.1 SyntaxError

7.1.3.2 Run-TimeExceptions

7.1.3.3 HandlingExceptions

7.1.3.4 AddExceptionHandlesandClean-UpActionsto

FileRead/Write

7.2 PythonModules

7.2.1 ModuleIntroduction

7.2.2 SetUpModules

7.2.3 SystemBuilt-InModules

7.3 PackageManagementandMini-GIS

7.3.1 RegularGISDataOrganization

7.3.2 Mini-GISPackage

7.4 Hands-OnExperiencewithMini-GIS

7.4.1 PackageManagementandMini-GIS

7.4.2 RunandPracticetheMini-GISPackage

7.5 ChapterSummary

Problems

8. VectorDataAlgorithms

8.1 Centroid

8.1.1 CentroidofaTriangle

8.1.2 CentroidofaRectangle

8.1.3 CentroidofaPolygon

8.2 Area

8.2.1 AreaofaSimplePolygon

8.2.2 AreaofaPolygonwithHole(s)

8.3 Length

8.3.1 LengthofaStraightLineSegment

8.3.2 LengthofaPolyline

8.4 LineIntersection

8.4.1 ParallelLines

8.4.2 VerticalLines

8.5 PointinPolygon

8.5.1 ASpecialScenario

8.6 Hands-OnExperiencewithPython

8.6.1 UsingPythontoDrawaPolygonandCalculatethe

Centroid

8.6.2 UsingPythontoDrawPolygonandCalculatetheAreaof

Polygon

8.6.3 UsingPythontoDrawLineSegmentsandCalculatethe

Intersection

8.7 ChapterSummary

Problems

SectionIII AdvancedGISAlgorithmsandTheirProgrammingin ArcGIS

9. ArcGISProgramming

9.1 ArcGISProgramming

9.2 IntroductiontoArcPyPackage

9.2.1 ArcPyFunctions,Classes,andModules

9.2.2 ProgrammingwithArcPyinArcMap

9.2.3 ProgrammingwithArcPyinPythonWindowoutside

ArcMap

9.2.4 UsingHelpDocuments

9.3 AutomatingArcToolswithPython

9.4 AccessingandEditingDatawithCursors

9.4.1 SearchCursor

9.4.2 UpdateCursor

9.4.3 InsertCursor

9.4.4 NumPy

9.5

DescribingandListingObjects

9.5.1 Describe

9.5.2 List

9.6 ManipulatingComplexObjects

9.7 AutomatingMapProduction

9.8 CreatingArcToolsfromScripts

9.9 HandlingErrorsandMessages

9.10 ExternalDocumentandVideoResources

9.11 ImplementingSpatialRelationshipCalculationsUsingArcGIS

9.12 Summary

9.13 Assignment

10. RasterDataAlgorithm

10.1 RasterData

10.2 RasterStorageandCompression

10.2.1 RunLengthCoding

10.2.2 QuadTree

10.3 RasterDataFormats

10.3.1 TIFF

10.3.2 GeoTIFF

10.3.3 IMG

10.3.4 NetCDF

10.3.5 BMP

10.3.6 SVG

10.3.7 JPEG

10.3.8 GIF

10.3.9 PNG

10.4 ColorRepresentationandRasterRendering

10.4.1 ColorRepresentation

10.4.2 RasterRendering

10.5 RasterAnalysis

10.6 Hands-OnExperiencewithArcGIS

10.6.1 Hands-OnPractice10.1:RasterColorRenders

10.6.2 Hands-OnPractice10.2:RasterDataAnalysis:Findthe

AreawiththeElevationRangebetween60and100and

theLandCoverTypeas“Forest”

10.6.3

Hands-OnPractice10.3.AccesstheAttributeInformation

ofRasterDatasetandCalculatetheArea

10.7 ChapterSummary

Problems

11. NetworkDataAlgorithms

11.1 NetworkRepresentation

11.1.1 BasicsNetworkRepresentation

11.1.2 DirectedandUndirectedNetworks

11.1.3 TheAdjacencyMatrix

11.1.4 NetworkRepresentationinGIS

11.2 FindingtheShortestPath

11.2.1 ProblemStatement

11.2.2 ABruteForceApproachfortheShortestPathAlgorithm

11.2.3 DijkstraAlgorithm

11.3 TypesofNetworkAnalysis

11.3.1 Routing

11.3.2 ClosestFacility

11.3.3 ServiceAreas

11.3.4 ODCostMatrix

11.3.5 VehicleRoutingProblem

11.3.6 Location-Allocation

11.4 Hands-OnExperiencewithArcGIS

11.5 ChapterSummary

Problems

12. SurfaceDataAlgorithms

12.1 3DSurfaceandDataModel

12.1.1 SurfaceData

12.1.2 SurfaceDataModel

12.1.2.1 DiscreteData

12.1.2.2 ContinuousData

12.2 CreateSurfaceModelData

12.2.1 CreateGridSurfaceModel

12.2.2 CreatingTINSurfaceModel

12.3

SurfaceDataAnalysis

12.3.1 Elevation

12.3.2 Slope

12.3.3 Aspect

12.3.4 HydrologicAnalysis

12.4 Hands-OnExperiencewithArcGIS

12.4.1 Hands-OnPractice12.1:ConversionamongDEM,TIN,

andContours

12.4.2 Hands-OnPractice12.2:GenerateSlopeandAspect

12.4.3 Hands-OnPractice12.3:FlowDirection

12.5 ChapterSummary

Problems

SectionIV AdvancedTopics

13. Performance-ImprovingTechniques

13.1 Problems

13.2 DiskAccessandMemoryManagement

13.2.1 FileManagement

13.2.2 ComprehensiveConsideration

13.3 ParallelProcessingandMultithreading

13.3.1 SequentialandConcurrentExecution

13.3.2 Multithreading

13.3.3 LoadMultipleShapefilesConcurrentlyUsing

Multithreading

13.3.4 ParallelProcessingandCluster,Grid,andCloud

Computing

13.4 RelationshipCalculationandSpatialIndex

13.4.1 BoundingBoxinGIS

13.4.2 SpatialIndex

13.5 Hands-OnExperiencewithMini-GIS

13.5.1 DataLoadingwithRAMasFileBuffer

13.5.2 DataLoadingwithMultithreading

13.5.3 BoundingBoxCheckingtoSpeedUpIntersection

13.5.4 LineIntersectionUsingR-TreeIndex

Problems

14. AdvancedTopics

14.1 SpatialDataStructure

14.1.1 RasterDataStructureinNetCDF/HDF

14.1.2 ApplicationofNetCDF/HDFonClimateStudy

14.2 GISAlgorithmsandModeling

14.2.1 Data

14.2.2 DensityAnalysis

14.2.3 RegressionAnalysis(OLSandGWR)

14.3 DistributedGIS

14.3.1 SystemArchitecture

14.3.2 UserInterface

14.4 SpatiotemporalThinkingandComputing

14.4.1 Problem:DustSimulationandComputingChallenges

14.4.2 Methodology1:UtilizingHigh-PerformanceComputingto

SupportDustSimulation

14.4.3 Methodology2:UtilizingSpatiotemporalThinkingto

OptimizeHigh-PerformanceComputing

14.4.3.1 DustStorms’ClusteredCharacteristics:

SchedulingMethods

14.4.3.2 DustStorms’Space–TimeContinuity:

DecompositionMethod

14.4.3.3 DustStormEventsAreIsolated:NestedModel

14.4.4 Methodology3:UtilizingCloudComputingtoSupport

DustStormForecasting

14.5 ChapterSummary

Problems

References

Index

Preface WhyAnotherGISProgrammingText? Geographicalinformationsystem(GIS)hasbecomeapopulartoolunderpinning many aspects of

Preface

Preface WhyAnotherGISProgrammingText? Geographicalinformationsystem(GIS)hasbecomeapopulartoolunderpinning many aspects of
Preface WhyAnotherGISProgrammingText? Geographicalinformationsystem(GIS)hasbecomeapopulartoolunderpinning many aspects of
Preface WhyAnotherGISProgrammingText? Geographicalinformationsystem(GIS)hasbecomeapopulartoolunderpinning many aspects of
Preface WhyAnotherGISProgrammingText? Geographicalinformationsystem(GIS)hasbecomeapopulartoolunderpinning many aspects of

WhyAnotherGISProgrammingText?

Geographicalinformationsystem(GIS)hasbecomeapopulartoolunderpinning many aspects of our daily life from routing for transportation to finding a restauranttorespondingtoemergencies.ConvenientGIStoolsaredevelopedwith different levels of programming fromscripting, using python for ArcGIS, to craftingnewsuitesoftoolsfromscratch.Howmuchprogrammingisneededfor projects largely depends on the GIS software, types of applications, and knowledgestructureandbackgroundoftheapplicationdesigneranddeveloper. For example, simple scripting integrates online mapping applications using Google maps. Customized spatial analyses applications are routinely using ArcGISwithminimumprogramming. Manydevelop anapplicationleveraging open-sourcesoftwareformanagingbigdata,modelingcomplexphenomena,or respondingtoconcurrentusersforpopularonlinesystems.Thebestdesignand developmentofsuchapplications requiredesigners anddevelopers tohavea thoroughunderstandingofGISprinciplesaswellastheskilltochoosebetween commercialandopen-sourcesoftwareoptions.FormostGISprofessionals,thisis achallengebecausemostareeitherGIStoolendusersorinformationtechnology (IT)professionalswithalimitedunderstandingofGIS. Tofillthisgap,overthelastdecade,ChaoweiYanglaunchedanintroductory GISprogrammingcoursethatwaswellreceived.Enrollmentcontinuestoriseand students report positive feedback once they are in the workplace and use knowledgedevelopedfromtheclass.Tobenefitabroaderspectrumofstudents and professionals looking for training materials to build GIS programming capabilities,thisbookiswrittentointegrateandrefinetheauthors’knowledge accumulatedthroughcoursesandassociatedresearchprojects. TheaudienceforthisbookisbothITprofessionalstolearntheGISprinciples andGISuserstodevelopprogrammingskills.Ontheonehand,thisbookprovides abridgeforGISstudentsandprofessionalstolearnandpracticeprogramming.On

theotherhand,italsohelpsITprofessionalswithprogrammingexperienceto acquirethefundamentalsofGIStobetterhonetheirprogrammingskillsforGIS development. Rather thantryto compete withthe currentGISprogrammingliterature, the authors endeavor to interpret GIS froma different angle by integrating GIS algorithms and programming. As a result, this book provides a practical knowledgethatincludesfundamentalGISprinciples,basicprogrammingskills, open-source GIS development, ArcGIS development, and advanced topics. StructuredfordevelopingGISfunctions,applications,andsystems,thisbookis expectedtohelpGIS/ITstudentsandprofessionalstobecomemorecompetitivein thejobmarketofGISandITindustrywithneededprogrammingskills.

thejobmarketofGISandITindustrywithneededprogrammingskills. WhatIsIncludedintheText? Thisbookhasfoursections. SectionI (
thejobmarketofGISandITindustrywithneededprogrammingskills. WhatIsIncludedintheText? Thisbookhasfoursections. SectionI (
thejobmarketofGISandITindustrywithneededprogrammingskills. WhatIsIncludedintheText? Thisbookhasfoursections. SectionI (
thejobmarketofGISandITindustrywithneededprogrammingskills. WhatIsIncludedintheText? Thisbookhasfoursections. SectionI (

WhatIsIncludedintheText?

Thisbookhasfoursections.SectionI(Chapters1and2)isanoverviewofGIS

programming and introduces computer and programming from a practical perspective.Python(integralprogramminglanguageforArcGIS)programmingis

extensivelypresented in SectionII (Chapters 3 through 8) in the context of designing and developing a Mini-GIS using hands-on experience following

explanationsoffundamentalconceptsofGIS.SectionIII(Chapters9through12)

focusesonadvancedGISalgorithmsandinformationonhowtoinvokethemfor programming in ArcGIS. Advanced topics and performance optimization are

introducedinSectionIV(Chapters13and14)usingtheMini-GISdeveloped.

Chapter1introducescomputer,computerprogramming,andGIS.Inaddition,the

Unified Markup Language (UML) is discussed for capturing GIS models

implementedthroughsimplePythonprogramming.Chapter2introducesobject-

orientedprogrammingandcharacteristicswithexamplesofbasicGISvectordata typesofPoint,Polyline,andPolygon. Chapter 3 introduces Python syntax, operators, statements, miscellaneous featuresoffunctions,andPythonsupportforobject-orientedprogramming.Using GIS examples, Chapter 4 introduces Python language control structures, file input/output,andexceptionhandling.Chapter 5presents programmingthinking usingthe visualizationofvector data as anexample ofthe workflow ofthis

critical process in programming. Chapter 6 introduces the Python integrated

programmingenvironment(IDE),modules,packagemanagement,andtheMini-

GISpackage.Chapter7discussesshapefileformatsandstepsonhowtohandle

shapefiles withinthe Mini-GIS. Chapter 8 introduces vector data processing algorithms and includes line intersection, centroid, area, length, and point in polygon. This presentation includes how Mini-GIS/ArcGIS supports these algorithms.

Chapter9bridgesSectionsIIandIIIbyintroducingArcGISprogrammingin

Python using ArcPy, ArcGIS programming environment, automating tools,

accessingdata,describingobjects,andfixingerrors.Chapter10introducesraster

data algorithms, including raster data format, storage, and compression with

hands-onexperienceusingArcGIS.Chapter11addressesnetworkdataalgorithms

forrepresentingnetworksandcalculatingtheshortestpathinprinciplesandusing ArcGIS. Chapter 12 explores surface or 3D data representation of 3D data,

convertingdataformatsand3Danalysesforelevation,slope,aspect,andflow

directionwithexamplesinArcGISprogramming.

Chapter13introducesperformance-improvingtechniquesandincludesstorage

accessandmanagement,parallelprocessingandmultithreading,spatialindex,and othertechniquesforacceleratingGISasdemonstratedinMini-GIS.Advanced topics,includingGISalgorithmsandmodeling,spatialdatastructure,distributed

GIS,spatiotemporalthinking,andcomputing,arepresentedinChapter14.

Chapter14 . Hands-OnExperience Asapractical
Chapter14 . Hands-OnExperience Asapractical
Chapter14 . Hands-OnExperience Asapractical
Chapter14 . Hands-OnExperience Asapractical

Hands-OnExperience

Asapractical textfordevelopingprogrammingskills,thisbookmakesevery

efforttoensurethecontentisasfunctionalaspossible.ForeveryintroducedGIS

fundamentalprinciple,algorithmandelement,anexampleisexploredasahands-

on experience using Mini-GIS and/or ArcGIS with Python. This learning workflowhelpsbuildathoroughunderstandingofthefundamentalsandnaturally mapstothefundamentalsandprogrammingskills. For systemand open-source development, a step-by-step development of a python-based Mini-GIS is presented. For applicationdevelopment, ArcGIS is adoptedforillustration. TheMini-GISisanopen-sourcesoftwaredevelopedforthistextandcanbe adoptedforbuildingotherGISapplications.ArcGIS,acommercialproductfrom ESRI,isusedtoexperiencestate-of-the-artcommercialsoftware.Forlearning purpose,ArcGISisavailableforfreefromESRI.

OnlineMaterials Thisbookcomeswiththefollowingonlinematerials: •
OnlineMaterials Thisbookcomeswiththefollowingonlinematerials: •
OnlineMaterials Thisbookcomeswiththefollowingonlinematerials: •
OnlineMaterials Thisbookcomeswiththefollowingonlinematerials: •

OnlineMaterials

Thisbookcomeswiththefollowingonlinematerials:

• Instructionalslidesforinstructorsusingthistextforclassroomeducation

andprofessionalstoassistinlearningGISprogramming.

• Pythoncodesforclassexercisesandhands-onexperiencesandstructured

andlabeledbychaptertocodethechapter’ssequence.

• Mini-GISasanopen-sourcepackageforlearningtheGISfundamentalsand

forexemplifyingGISprinciplesandalgorithms.

• Answerstoproblemsforinstructorstochecktheirsolutions.

• Answerstoproblemsforinstructorstochecktheirsolutions. TheAudienceforandHowtoUseThisText
• Answerstoproblemsforinstructorstochecktheirsolutions. TheAudienceforandHowtoUseThisText
• Answerstoproblemsforinstructorstochecktheirsolutions. TheAudienceforandHowtoUseThisText
• Answerstoproblemsforinstructorstochecktheirsolutions. TheAudienceforandHowtoUseThisText

TheAudienceforandHowtoUseThisText

Thistextservestwofunctions:atextforsystematicbuildingGISprogramming skillsandareferenceforidentifyingapythonsolutionforspecificGISalgorithms or function fromscratch and/or ArcGIS. The text is intended to assist four categoriesofreaders:

• Professors teaching GIS programming or GIS students learning with a specificfocusonhands-onexperienceinclassroomsettings.

• Programmers wanting to learn GIS programming by scanning through

SectionIandChapters3and4,followedbyastep-by-stepstudyofthe

remainingchapters.

• GISsystemdesignersmostinterestedinalgorithmdescriptions,algorithms implementationfrombothscratchand ArcGIS to assemble a practical knowledge about GIS programing to aid in GIS choice for future development.

• ITprofessionalswithacuriosityofGISforGISprinciplesbutskippingthe programmingexercises.

Theintentoftheauthorsforsuchabroadaudienceisbasedonthedesireto

cultivateacompetitiveprofessionalworkforceinGISdevelopment,enhancethe

literatureofGIS,andserveasapracticalintroductiontoGISresearch.

HowDidWeDevelopThisText? ThetextmaterialwasfirstdevelopedbyProfessorChaoweiYangin2004and
HowDidWeDevelopThisText? ThetextmaterialwasfirstdevelopedbyProfessorChaoweiYangin2004and
HowDidWeDevelopThisText? ThetextmaterialwasfirstdevelopedbyProfessorChaoweiYangin2004and
HowDidWeDevelopThisText? ThetextmaterialwasfirstdevelopedbyProfessorChaoweiYangin2004and

HowDidWeDevelopThisText?

ThetextmaterialwasfirstdevelopedbyProfessorChaoweiYangin2004and

offeredannuallyinaclassroomsettingduringthepastdecade.Duringthattime span, manystudents developed and advanced their programmingskills. Some becameprofessorsandlecturersincollegesandwereinvitedtowritespecific bookchapters.Keepingtheaudienceinmind,severalprofessorswhoteachGIS programmingindifferentculturalbackgroundsanduniversitysettingswereinvited toreviewthebookchapters. Thefollowingisthebookdevelopmentworkflow:

• Usinghiscoursematerials,ProfessorYangstructuredthisbookwithIrma Shagla’shelp,andthetext’sstructurewascontractedtobepublishedasa book. Assistant Professor Qunying Huang, University of Wisconsin, Madison, explored using the earlier versions of the text’s materials. AssistantProfessorsHuangandZhenlongLi,UniversityofSouthCarolina, developedSectionIIofthetextincollaborationwithProfessorYang.

• Dr. Min Sun, Ms. Manzhu Yu, Mr. Yongyao Jiang, and Mr. Jizhe Xia developedSectionIIIincollaborationwithProfessorYang.

• ProfessorYangeditedandrevisedallchapterstoassureacommonstructure andcomposition.

• Ms.ManzhuYuandProfessorYangeditedthecourseslides.

• AssistantProfessor Li,Mr.Kai Liu,Mrs.JosephGeorge,andMs.Zifu WangeditedMini-GISasthesoftwareforthetext.

• Aftertheabovetextandcoursematerialswerecompleted,fourprofessors andtwodeveloperswereinvitedtoreviewthetext’scontent.

• The assembled materials for the textwere finallyreviewed byseveral professionals, including Ms. Alena Deveau, Mr. Rob Culbertson, and ProfessorGeorgeTaylor.

• ThetextwasformattedbyMs.MinniSong.

• Ms. Manzhu Yu and Professor Yang completed a final review of the chapters,slides,codes,data,andallrelevantmaterials.

Acknowledgments Thistextisalong-termprojectevolvingfromthecourse“IntroductiontoGIS Programming” developed and refined

Acknowledgments

Thistextisalong-termprojectevolvingfromthecourse“IntroductiontoGIS Programming” developed and refined over the pastdecade atGeorge Mason University.Manystudentsandprofessorsprovidedconstructivesuggestionsabout whattoinclude,howbesttocommunicateandchallengethestudents,andwho shouldbeconsideredasaudienceofthetext. The outcome reflects Professor Yang’s programming career since his undergraduatethesesatChina’sNortheasternUniversityunderthementoringof ProfessorJinxingWang.ProfessorYangwasfurthermentoredinprogrammingin theGISdomainbyProfessorsQiLiandJichengChen.Hisacademicmentorsin theUnitedStates,ProfessorsDavidWongandMenasKafatos,providedsupport overmanydecades,givinghimthechancetoteachthecoursethateventuallyled tothistext. ProfessorYangthanksthebrilliantandenthusiasticstudentsinhisclassesat GeorgeMasonUniversity.Theirquestionsandcritiqueshonedhisteachingskills, improvedthecontent,andpromptedthiseffortofdevelopingatext. Professor Yangthanks his belovedwife,YanXiang,andchildren—Andrew, Christopher,andHannah—foraccommodatinghimwhenstealingvaluablefamily timetocompletethetext. Ms. ManzhuYuextends her gratitude to the manycolleagues who provided support,andread,wrote,commented,andassistedintheediting,proofreading, andformattingofthetext. AssistantProfessorHuangthanksherwonderfulhusband,YunfengJiang,and lovelydaughter,AlicaJiang. Dr.MinSunthanksherPhDsupervisor,ProfessorDavidWong,foreducating her.ShealsothanksDavidWynne,hersupervisorinESRIwheresheworkedas anintern, and her other coworkers who collectivelyhelped her gaina more completeunderstandingofprogrammingwithESRIproducts.Lastbutnotleast, shethanksherparentsandlovelydogwhoaccompaniedherwhenshewaswriting thetext. YongyaoJiangthankhiswifeRuiDong,hisdaughterLaura,andhisparentsLixia

YaoandYanqingJiang.

Editor ChaoweiYang isaprofessorofgeographicinformationscienceatGeorgeMason

Editor

ChaoweiYangisaprofessorofgeographicinformationscienceatGeorgeMason University(GMU).Hisresearchinterestisonutilizingspatiotemporalprinciples tooptimizecomputinginfrastructuretosupportsciencediscoveries.Hefounded the Center for Intelligent Spatial Computing and the NSF Spatiotemporal

InnovationCenter.HeservedasPIorCo-Iforprojectstotalingmorethan$40M

and funded bymore than15 agencies, organizations, and companies. He has published150+articlesanddevelopedanumber ofGIScoursesandtraining programs. He has advised 20+ postdoctoral and PhD students who serve as professorsandscientistsinhighlyacclaimedU.S.andChineseinstitutions.He receivedmanynationalandinternationalawards,suchastheU.S.Presidential

EnvironmentProtectionStewardshipAwardin2009.Allhisachievementsare

basedonhispracticalknowledgeofGISandgeospatialinformationsystems.This bookisacollectionofsuchpracticalknowledgeonhowtodevelopGIStools fromaprogrammingperspective.Thecontentwasofferedinhisprogrammingand GIS algorithmclasses duringthe past 10+ years (2004–2016) and has been adoptedbyhisstudentsandcolleaguesservingasprofessorsatmanyuniversities intheUnitedStatesandinternationally.

Contributors FeiHu isaPhDcandidateattheNSFSpatiotemporalInnovationCenter,George

Contributors

FeiHuisaPhDcandidateattheNSFSpatiotemporalInnovationCenter,George

MasonUniversity.Heisinterestedinutilizinghigh-performancecloudcomputing

technologiestomanageandminebigspatiotemporaldata.Morespecifically,he

hasoptimizedthedistributedstoragesystem(e.g.,HDFS)andparallelcomputing

framework(e.g.,Spark,MapReduce)toefficientlymanage,query,andanalyzebig

multiple-dimensionalarray-baseddatasets(e.g.,climatedataandremotesensing

data).Heaimstoprovidescientistswithon-demanddataanalyticalcapabilitiesto

relievethemfromtime-consumingcomputationaltasks.

QunyingHuangisanassistantprofessorintheDepartmentofGeographyatthe UniversityofWisconsin,Madison.Her fields ofexpertise include geographic informationscience (GIScience), cyber infrastructure, spatiotemporal bigdata mining, and large-scale environmental modeling and simulation. She is very interestedinapplyingdifferentcomputingmodels,suchascluster,grid,GPU, citizencomputing,andespeciallycloudcomputing,toaddresscontemporarybig dataandcomputingchallengesintheGIScience.Mostrecently,sheisleveraging and mining social media data for various applications, such as emergency

response,disastermitigation,andhumanmobility.Shehaspublishedmorethan50

scientificarticlesandeditedtwobooks.

YongyaoJiangisaPhDcandidateinEarthsystemsandgeoinformationsciences at the NSF Spatiotemporal Innovation Center, George Mason University. He

earnedanMS(2014)inGIScienceatClarkUniversityandaBE(2012)inremote

sensingatWuhanUniversity.Hisresearchfocusesondatadiscovery,datamining, semantics,andcloudcomputing.JianghasreceivedtheNSFEarthCubeVisiting

GraduateStudentEarly-CareerScientistAward(2016),theMicrosoftAzurefor

ResearchAward(2015),andfirstprizeintheRobertRaskinCyberGISStudent

Competition(2015).HeservesasthetechnicalleadforMUDROD,asemantic

discoveryandsearchengineprojectfundedbyNASA’sAISTProgram.

ZhenlongLiis anassistantprofessor inthe DepartmentofGeographyatthe

University of South Carolina. Dr. Li’s research focuses on spatial high- performance computing, big data processing/mining, and geospatial cyberinfrastructureintheareaofdataandcomputationalintensiveGISciences.Dr. Li’s researchaims to optimize spatial computinginfrastructure byintegrating cutting-edge computingtechnologies and spatial principles to support domain applicationssuchasclimatechangeandhazardmanagement.

KaiLiuisagraduatestudentintheDepartmentofGeographyandGeoInformation Sciences (GGS) in the College of Science at George Mason University. Previously,hewasavisitingscholarattheCenterofIntelligentSpatialComputing

forWater/EnergyScience(CISC)andworkedfor4yearsatHeilongjiangBureau

ofSurveyingandmappinginChina.HeearnedaBAingeographicinformation scienceatWuhanUniversity,China.Hisresearchfocusesongeospatialsemantics, geospatial metadata management, spatiotemporal cloud computing, and citizen science.

MinSunisaresearchassistantprofessorintheDepartmentofGeographyand Geoinformation Science at George Mason University. Her research interests includemeasuringattributeuncertaintyinspatialdata,developingvisualanalytics tosupportdataexploration,WebGIS,andcloudcomputing.Sheisanexpertin ArcGISprogrammingandalsoservesastheassistantdirectorfortheU.S.NSF SpatiotemporalInnovationCenter.

Jizhe Xia is a researchassistant professor at George MasonUniversity. He earnedaPhDinEarthsystemsandgeoinformationsciencesattheGeorgeMason

Universityinthespringof2015.Dr.Xia’sresearchinterestsarespatiotemporal

computing,cloudcomputing,andtheirapplicationsingeographicalsciences.He

proposedavarietyofmethodstoutilizespatiotemporalpatternstooptimizebig

dataaccess,servicequality(QoS)evaluation,andcloudcomputingapplication.

Manzhu Yu is a PhD candidate in the Department of Geography and GeoinformationScience,GeorgeMasonUniversity.Herresearchinterestsinclude spatiotemporalmethodology,patterndetection,andspatiotemporalapplications

onnaturaldisasters.ShereceivedaPresidentialScholarshipfrom2012to2015.

Shehaspublishedapproximately10articlesinrenownedjournals,suchasPLoS

ONEandIJGIS,andcontributedasamajorauthorinseveralbookchapters.

SectionI

Overview

1

1 Introduction Thischapterintroducesthebasi cconceptsofcomputer,hardware,software,and programming,andsetsupthecon
1 Introduction Thischapterintroducesthebasi cconceptsofcomputer,hardware,software,and programming,andsetsupthecon
1 Introduction Thischapterintroducesthebasi cconceptsofcomputer,hardware,software,and programming,andsetsupthecon
1 Introduction Thischapterintroducesthebasi cconceptsofcomputer,hardware,software,and programming,andsetsupthecon

Introduction

Thischapterintroducesthebasicconceptsofcomputer,hardware,software,and

programming,andsetsupthecontextforGISprogramming.

programming,andsetsupthecon textforGISprogramming. 1.1 ComputerHardware andSoftware A computer is a device
programming,andsetsupthecon textforGISprogramming. 1.1 ComputerHardware andSoftware A computer is a device
programming,andsetsupthecon textforGISprogramming. 1.1 ComputerHardware andSoftware A computer is a device
programming,andsetsupthecon textforGISprogramming. 1.1 ComputerHardware andSoftware A computer is a device

1.1 ComputerHardwareandSoftware

computersoccupyingabuildingtomobiledevicesinpockets(Figure1.1).The

userinteractionsrangefromtypingpunchedcards(earlycomputers)tohuman–

computerinteraction,suchasspeakingtoinvokeanactionortask.

computerinteraction,suchasspe akingtoinvokeanactionortask. FIGURE1.1 at http://www.nas.nasa.gov/hecc/resources/plei

FIGURE1.1

at

(a)

NASA

supercomputer.

computers.)

Therearetwoimportantcomponentsofacomputer(HwangandFaye1984):(1)

thephysicaldevicethatcanconductautomatedprocessing,and(2)instruction

packagesthatcanbeconfiguredtoprovidespecificfunctionality,suchasword processing or geographic information processing. The first component of a computer, the hardware, is touchable as physical machines. The second component,thesoftware,maybepurchasedwiththehardwareintheformofan operatingsystem,orinstalledbydownloadingonline.Computerhardwarecanbe configuredorprogrammedtoperformdifferenttasks;thus,acomputermayalso becalledageneral-purposedevice.Thesoftwarevariesgreatly,whetheritis providing document-processing capability, financial management, tax return processing, or scientific simulations suchas climate change or the spread of disease. Depending on the type of software, it is either procured publicly (freeware)orproprietary(requiringpurchaseandlicensing).Dependingonthe usage,softwarecanbecategorizedassystemsoftware,applicationsoftware,or

embeddedsoftware(Figure1.2).Systemsoftwarereferstothebasicsoftwarethat

mustbeinstalledforacomputertooperate.WindowsandLinuxareexamplesof operating system (OS) software, an essential component of a computer. Applicationsoftwaresupportsspecificgroupsoftasks,suchasMicrosoftWord fordocumentprocessingandMicrosoftOutlookforemails.Embeddedsoftwareis a type of firmware that is burned onto hardware and becomes part of that hardware. Embedded software exists longer on a computer than any other software.Thefirmwarewillalwayscomewiththehardwarewhenyoupurchasea computer,sothefirmwarewillnothavetobechangedasfrequently,especially whenupdatingawebbrowserorTurboTaxReturnroutinely.

FIGURE1.2 Differenttypesofsoftware. Geographicinformationsystem (GIS)isonetypeofapplicationsoftwarethat

FIGURE1.2

Differenttypesofsoftware.

Geographicinformationsystem(GIS)isonetypeofapplicationsoftwarethat

dealsprimarilywithgeographicinformation(Longleyetal.2001).Theglobal

positioningsystem(GPS,MisraandEnge2006)isusedforlocatinggeographic

places, and canbe installed inbothcars and smart phones for routing. GIS software includes two categories: professional GIS and lightweight GIS. ProfessionalGISsoftware,suchasArcGIS,providesthemostcompletesetof GISfunctionalitiesforprofessionalsintheGISdomain.Lessintense,butpopular, GISsoftwareusedtoviewthegeographicenvironmentaretheonlinemapping application,suchasGoogleMapsandGoogleEarth.

application,suchasGoogleMapsandGoogleEarth. 1.2 GISandProgramming
application,suchasGoogleMapsandGoogleEarth. 1.2 GISandProgramming
application,suchasGoogleMapsandGoogleEarth. 1.2 GISandProgramming
application,suchasGoogleMapsandGoogleEarth. 1.2 GISandProgramming

1.2 GISandProgramming

GISoriginatesfromseveraldomainsandreferstothesystemdesignedtocapture, observe,collect,store,andmanagegeographicdata,andtoprovidetoolsfor spatial analyses and visualization(Longleyetal. 2001). GIScanhelp obtain geographic data to be used for decisionmaking, suchas choosingroutes for emergencyresponse.GISis knowntohavestartedfromtheCanadiannatural

resourceinventorycomputerprogramledbyRogerTomlinsoninthe1960s.GIS

is becomingincreasinglypopular onmobile devices as a means ofanalyzing informationandpatternsrelatedtotrafficandweather.

Coined by Mike Goodchild, the term“GIS” can also refer to the field of

geographic information science or GIScience—the study of the scientifically

appliedGISprinciplesandtechnologies(Goodchild1992).AccordingtoGIS

scientists,GIScienceinvolvesremotesensing,globalnavigationsatellitesystems, andGIS.Additionally,invariousdomains,GeoInformaticsmaybeappliedto remotesensing,globalnavigationsatellitesystem,andGISinformation.These topics,however,willnotbeexploredinthisbook. GIS is the system comprising hardware (computer, mobile devices, GPS), software(ArcGISoronlinemapping),anddata(geographicinformation)thatcan beutilizedtoaccomplishasetoffunctionalitiesforagroupofusers.Allthree componentsmustbeutilizedforGIStoworkeffectively.Asignificantdifference between GIS and other software applications is its ability to manage and manipulatethelargevolumeandcomplexityofgeographicdata,whichcomprises embeddedspatiotemporalandattributeinformation.ThecomplexcharacterofGIS data demands a specific suite ofsoftware to extractinformationfor decision

making.Maturesoftwarepackagesarepubliclyavailable,includingthemostup-

to-date set of ArcGIS software and the latest edition of Google Maps web mappingsoftware. The process of developing software is called programming. Programming instructsthecomputertoaccomplishataskbasedontheorders.Therearemany different types of programming levels (Mitchell 1996). The lowest level to programarebasedonthespecifichardwareinstructionssupportedbythecentral processingunits(CPU),andusedbysmart-instrumentdevelopers.BecauseCPU

instructionsareprocessedasasequenceof0sand1s,assemblinglanguageis

developedtoassistdeveloperstorememberthoseinstructions.Bothlanguagesare consideredlowlevelandarespecifictothehardware.Advancedlanguageshave beendevelopedtofacilitatehumanunderstanding,butarestillrestrictedbythe hardwareinstructions.Forexample,Cprogramminglanguageiscommonlyused

todevelopsoftware(KernighanandRitchie2006).Tomaketheprogramming

organizationmore similar tohow we view the world, C++was proposed to

supportobject-orientedprogrammingbasedonC(Stroustrup1995).Sincethen,

manydifferentprogramminglanguageshavebeendevelopedandareusedinGIS programming. For instance, Java is a language for cross-platformapplication

developmentproposedbySunMicrosystems(Arnoldetal.2000).JavaScriptis

usedtoconductscripting(simpler)programmingformanipulatingobjectswithina

webbrowser.InadditiontoJavaandJavaScript,ArcGIShasrecentlyadded

Pythontoitslistofprogramminglanguages(VanRossum2007).

Why do we need GIS programming? Mature GIS software and application templatesprovidemanytoolstoaccomplishourdailytasks;however,inorderto understandthefundamentalsofhowGISworksandtocustomizesoftwarefor specific problems, programming is required. The following list gives programmingexamples:

Customizing software for application: The National Park Service is developingasimplewebmappingapplicationtoallowthegeneralpublic tointeractivelyselectandviewinformationforaparticularNationalPark. UsinganonlinemappingtoolsuchasGoogleMapsandselectingapark withyourmousewilltriggeraqueryoftheselectedinformationforthat park.Inthisscenario,weneedgeographicinformationabouttheparks,a programforfront-enduserinteraction,andadatabasequerylanguagethat willgenerateresultfortheselectedpark.

Automatingaprocess:Supposethereare100geographicdatasetscollected

intextfileformatandweneedtoconvertthemintoashapefile,anative data file formatused byArcView and ArcGIS, for further processing. ArcGIScanperformtheconversiononebyone,butdoingthismanually 100 times is monotonous. Therefore, a simple scripting tool to

automaticallyreadandprocessthe100datasetsintoshapefileswouldbe

beneficial.UsingPythonscriptsinArcGISprovidesthecapabilitytodoso.

SatisfyingsimpleGISneeds:Supposethereisatransportationcompany

thatneedstotracktheircompanyvehicles’positionsbasedon5-minute

intervals.However,thecompanycannotaffordtopurchaseaprofessional GISsoftwarelicense.Toresolvetheissue,thecompanycanusePythonto createamaptoshowthecompany’sserviceregionandvehiclelocations every 5 minutes. This programming may include Zoom In/Out, and Move/Panfeatures,animationsbasedonlocations,andaselectionofone ormanyvehicles.

CultivatingadvancedGISprofessionals:Supposeagroupofstudentsare askedtoinventaroutingalgorithmbasedonpredictedtrafficconditions andreal-timetrafficinformation.Thestudentswillneedtoorganizethe road network information comparing real-time and predicted network speed.Itisessentialtousethemostaccuratepredictedinformationinthe

routingprocess.Programmingisneededthroughouttheentireprocessfor networkmanagementandrouting,andfor reconstructingtheresultsinto mapformorwrittendirections.

Geographic information has become increasingly important in all walks of humanlife,whetheritisforscientificdiscovery,forecastingnaturaldisasters, advancing technologies of observations, or creating public awareness about locationandrouting.WhilesomeapplicationsrequirecompleteGIStechnologies

to produce valuable results, manygeographic informationapplications do not

requiresophisticatedgeographicinformationsystems.Forthelattercase,open-

sourceorsmallgeospatialinformationsoftwareisutilized,whilecommercialGIS systemssuchasArcGIS,areavailablefortheformercase.Tobetteraddressboth needs,itisessentialtounderstandthefundamentalsofhowGISworksandits basicgeographicinformationprocessing.Thischapterintroducesthebackground structureforbuildingsuchcapabilities:computerhardwareandsoftware,GISand programming, GIS data models and Unified Markup Language (UML, Fowler 2004), and Python. Hands-on programming experience is needed for understandingtheconceptsanddevelopingtheessential skillsutilizedbyGIS professionalsintheirworkandresearch.BasedonGISfundamentals,thisbook will help you develop and improve systematic programming skills and will provide a more in-depth understanding of GIS fundamentals. Owing to its popularitywithintheGIScommunity,Pythonwillbetheprimaryprogramming languageusedinthisbook.

languageusedinthisbook. 1.3 Python
languageusedinthisbook. 1.3 Python
languageusedinthisbook. 1.3 Python
languageusedinthisbook. 1.3 Python

1.3 Python

PythonwasoriginallydevelopedbyaDutchprogrammer,GuidovanRossum,in

1990.VanRossumwasreportedlyafanoftheBritishcomedyseries,Monty

Python’s Flying Circus, and upon developing the open-source programming language,heborrowedtothename“Python”forthelanguageandhisnonprofit institution,thePythonSoftwareFoundation. SimilartoprogramminglanguagesC++andJava,Pythonisanobject-oriented andinteractivelanguage.Pythonisdynamicinthatitusesanautomaticmemory management mechanismto allocate and release memoryfor data (variables). PythonandArcGISregularlyreleasenewversionsoftheirprograms;thisbookis

basedonPythonrelease2.7andArcGIS10.1.

TherearemanyreasonsforchoosingPython,includingthefollowing: *

• Itisexcellentforprogrammingbeginners,yetsuperbforexperts.

• ThesyntaxofPythonisverysimpleandeasytolearn.Whenyoubecome familiarwiththem,youwillfeelthatitisreallyveryhandy.

• Itishighlyscalableandwellsuitedforbothlargeandsmallprojects.

• Itisinarapiddevelopmentphase.Almosteveryhalfyear,thereisanew majorrelease.

• Itisportablecross-platform.ThismeansthataprogramwritteninWindows canberunusingtheLinuxorMacoperatingsystems.

• Itiseasilyextensible.Youcanalwaysaddmoreclassfunctionstoyour currentproject.

• Ithaspowerfulstandardlibraries.

• Many third parties also provide highly functional packages for you to utilize.InsteadofdevelopingGISfunctionsfromscratch,youcansimply downloadthesourcecodeandintegratethemintoyourproject.

• Itisafullyobject-orientedlanguage,simpleyetelegant,andstableand mature.

ThereareseveralstepstolearningPythonforGISprogramming:

• Getfamiliarwiththeconceptofclassandobject(Chapters1and2).

• Learn the syntax of Python, including variables, data types, structures,

controls,statements,andotherprogrammingstructures(Chapters1through

4).

• BuildPythonprogramsfromscratchandintegrateopen-sourcelibrariesto

facilitateprogramming(Chapter5).

• Become comfortable withthe Pythonprogrammingenvironment (Python

interpreterorPythonTexteditor,Chapter6).

• Solve GIS problems by writing code for GIS algorithms (Chapters 7

through13).

Thesecomponentsareintroducedintheaboveorderthroughoutthisbook.This chapter introduces important concepts such as object-oriented programming,

UML,andGISmodels.

UML,andGISmodels. 1.4 ClassandObject Withinthissection,wewilldiscusstwotypesoffundamentalconcepts:classand
UML,andGISmodels. 1.4 ClassandObject Withinthissection,wewilldiscusstwotypesoffundamentalconcepts:classand
UML,andGISmodels. 1.4 ClassandObject Withinthissection,wewilldiscusstwotypesoffundamentalconcepts:classand
UML,andGISmodels. 1.4 ClassandObject Withinthissection,wewilldiscusstwotypesoffundamentalconcepts:classand

1.4 ClassandObject

Withinthissection,wewilldiscusstwotypesoffundamentalconcepts:classand

object(Rumbaughetal.1991).Classusesasetofattributesandbehaviorsto

representacategoryofreal-worldphenomena.Forexample,Figure1.3shows

howtoextractthestudentattributesandbehaviors.

shows howtoextractthestudentattributesandbehaviors. FIGURE1.3

FIGURE1.3

AnexampleofrepresentingstudentswiththeStudentclass.

AnotherexampleisonlineshoppingonAmazonoreBay.Boththecustomersand

onlineproductsmustbeabstractedintoclasses:

• Customers would have a customer ID, shipping address, and billing address.Customerbehaviorwouldincludeaddingordeletingaproductto theshoppingcart. • Products would have a product ID, product name, and product price. Productbehaviorwouldincludesettingtheprice,andtotalingtheproduct quantity/amount.

Anobjectisaspecificinstanceofaclass.Wecanconsiderobjectsasinstances ofclasses byassigningvalues to their attributes. Specifically, a class is the abstractionofacategoryorcollectionofreal-worldentitieswhileanobjectisa specific real-world entitywithinthe class. Withina computer, a class is the templateandanobjectisthespecificentitythatoccupiesthecomputermemory. Thecomputercanoperateonboththeattributesandbehaviorsofanobject.For

example,whenastudentlogsintotheircollegewebsystemwithausernameand password,thesystemwillcreateanewstudentobject.Thecomputerreadseach studentasanindependentobjectwithseveraldifferentattributes(e.g.,username, password,andstudentID).Afterloggingin,astudentisabletosearch,register,or add/dropclasses usingthe objectinthe system,whichrepresents himor her

specifically.Chapter2willintroducehowtodefineclassesandobjectsusing

Python.

willintroducehowtodefineclassesandobjectsusing Python. 1.5 GISDataModels
willintroducehowtodefineclassesandobjectsusing Python. 1.5 GISDataModels
willintroducehowtodefineclassesandobjectsusing Python. 1.5 GISDataModels
willintroducehowtodefineclassesandobjectsusing Python. 1.5 GISDataModels

1.5 GISDataModels

GISdatamodelsareusedtocaptureessentialgeospatialelementsofaspecific

problem(Longleyetal.2001).Therearethreetypesofdatamodels:vectordata,

rasterdata,andspecialdata.Vectordatamodelsconsistofpoint,polyline,and polygonmodeltypes.Rasterdataincludesequallysplitcellsofdigitalelevation modelsandimages.Specialdataarecomposedofnetworkandlineardata.This bookhighlights differenttypes ofGIS data models, butwill focus mainlyon vectordatamodels. Apoint can refer to a class of vector data represented by a pair of x, y

coordinatesinatwo-dimensional(2D)spaceoratupleofx,y,andzcoordinates

inathree-dimensional(3D)space.Forexample,acityisrepresentedasapoint

onaworldmap.Eachcityhasagroupofattributes,whichwouldincludethecity name,population,averagehouseholdincome,andacro-names.Anotherexample usingpoints is a mapdepictingall the restaurants withina certainregion.In addition to its point location, each restaurant will contain other relevant information,includingitsname,roomcapacity,cuisine,andtheyearitopened.In thesecases,thepointisageneralclassification,whereasthecityortherestaurant isamorespecifictypeofclasscontainingdifferentattributes.Whendesigning,

eachpointoftherectanglecanrepresentaclass(Figure1.4).Thisdiagramisalso

referredtoasaUMLclassdiagram.Thefirstrowreferstothenameoftheclass:

City; the second row refers to the attributes of the class: name and averageIncome; the third row refers to a set of methods: getName, getAverageIncome,andsetName.

FIGURE1.4 AUMLdiagramfortheCityclass. Polylinesareaclassofvectordatarepresentedbyalistofpoints.Forinstance,

FIGURE1.4

AUMLdiagramfortheCityclass.

Polylinesareaclassofvectordatarepresentedbyalistofpoints.Forinstance, arivercanberepresentedasapolylineonamap,whichthencanbecategorized as a type of polyline class. Apolyline class mayinclude point coordinates, relevantattributes,andasetofmethods.Anotherpolylinedatasetexamplecanbe roads, highways, and interstates. Both examples are categories of polylines.

RiverscanberepresentedusingUML(Figure1.5).ThefirstrowoftheUMLis

thesubjectoftheclass:River;thesecondrow includestheriver’sattributes:

nameandcoordinates;andthethirdrowreferstothemethodstheprogrammer

willuse:getName,setCoordinates,andsetName.

willuse: getName , setCoordinates ,and setName . FIGURE1.5 TheRiverclassincludesthreeparts.

FIGURE1.5

TheRiverclassincludesthreeparts.

Polygonsareanotherclassofvectordatathatarealsorepresentedbyalistof points; however, with polygons, the first and last points are the same. For example,onthemapofthestateofVirginia,aspecificcounty,likeFairfaxCounty, canberepresentedasapolygon.Thecountyisatypeofpolygonclass,which includesalistofpoints,relevantattributes,andasetofmethods.Countriesona worldmapmayalsoberepresentedaspolygons.Ineithercase,boththecounty

andcountryaretypesofpolygons.AsshowninFigure1.6,thefirstrowisthe

subject name: County; the second row is the subject’s attributes: name and population;andthethirdrowreferstothemethods:getName,setPopulation,and setName.

getName , setPopulation ,and setName . FIGURE1.6 TheCountyclassincludesthreeparts.

FIGURE1.6

TheCountyclassincludesthreeparts.

Developingmoremethodswillrequireaddingmoremethodsandattributesto eachclasstocapturetheevolutionofthedatamodelsandthefunctionalityof software;UMLdiagramsareusedtostandardizetheirrepresentation.Thissection uses class diagrams and relevantUMLstandards for the point, polyline, and polygonclasses.

for the point, polyline, and polygonclasses. 1.6 UML In1997,theObjectManagementGroup(OMG) *
for the point, polyline, and polygonclasses. 1.6 UML In1997,theObjectManagementGroup(OMG) *
for the point, polyline, and polygonclasses. 1.6 UML In1997,theObjectManagementGroup(OMG) *
for the point, polyline, and polygonclasses. 1.6 UML In1997,theObjectManagementGroup(OMG) *

1.6 UML

In1997,theObjectManagementGroup(OMG) * createdtheUMLtorecordthe softwaredesignforprogramming.SoftwaredesignersandprogrammersuseUML tocommunicateandsharethedesign.SimilartotheEnglishlanguageinwhichwe communicatethroughsharingourideasviatalkingorwriting,UMLisusedfor modelinganapplicationorprobleminanobject-orientedfashion.UMLmodeling canbeusedtofacilitatetheentiredesignanddevelopmentofsoftware. TheUMLdiagramisusedtocapturetheprogramminglogic.Therearetwotypes ofdiagramsthatwewillspecificallydiscuss:classdiagramsandobjectdiagrams

(Figure1.7).

FIGURE1.7 Theclassdiagramandobjectdiagramusedinthisbook.

FIGURE1.7

Theclassdiagramandobjectdiagramusedinthisbook.

TheUMLclassdiagramcanrepresentaclassusingthreeparts:name,attributes, and methods. The attributes and methods have three different accessibilities:

public(+),private(-),andprotected(#).Attributesandmethodsarenormally

representedinthefollowingformat:

• Attributes:accessibilityattributeName:Attributedatatype,forexample, +name:String

• Methods: accessibilitymethodName (methodarguments): methodreturn type,forexample,+setName(name:String):void

Publicrefers tothemethod/attributes thatcanbeaccessedbyother classes. Privatemethods/attributescannotbeaccessedbyanyotherclasses. Protectedmethods/attributescannotbeaccessedbyotherclassesexceptthose classesinheritedfromthisclass(explainedbelow). There are several fundamental relationships among different classes:

dependency, inheritance, composition, and aggregation. Dependencyrepresents oneclassdependentonanother.Inheritanceisanimportantrelationshipinwhicha

classisasubtypeofanotherclass.Figure1.8illustratesthedependencybetween

geometryandcoordinatesystemsinthattheexistenceofgeometrydependsona

coordinatesystem.Thisrelationshipisrepresentedbyadashedlineandanarrow

fromthegeometrytothecoordinatesystemclass.Therelationshipbetweena

point,line,andpolygonareclassifiedwithinthegeometryclass.

point,line,andpolygonareclassifiedwithinthegeometryclass. FIGURE1.8 Inheritanceanddependency.

FIGURE1.8

Inheritanceanddependency.

Aggregationandcompositionare twoother importantrelationships inUML. Aggregationrepresents“hasa”relationshipinUML.Forexample,astateisan

aggregationofanumberofcounties(Figure1.9a).Compositionrepresents,or

“owns”relationship.Forexample,amultipointclassmaybecomposedoftwoor

morepoints(Figure1.9b).

morepoints( Figure1.9b ). FIGURE1.9

FIGURE1.9

(a)Aggregationand(b)compositionaretwopolarrelationshipsamongclasses.

Therelationshipcanbequantifiedbythenumber ofelements involved.For

example,alineincludes2+pointsandastateincludes0+counties.Therearesix

different types of this multiplicityrelationship (Figure 1.10). Amultipoint is

composedoftwoormorepoints(Figure1.9b)andastateisaggregatedbyzeroor

morecounties.

FIGURE1.10 Multicityrelationshipamongclasses. Anobjectisan instantiation ofaclass.Theobjectdiagramshowsacomplete

FIGURE1.10

Multicityrelationshipamongclasses.

Anobjectisaninstantiationofaclass.Theobjectdiagramshowsacomplete orpartialviewofthemodelsystemstructureataspecifictime.So,thestateofan

objectcanbechanged.Figure1.11’sclassnameisworldMap,anditsobjectisthe

coordinatesystemthatchangedfromWGS1972toWGS1984afterperforming

reprojection.

reprojection. FIGURE1.11

FIGURE1.11

worldMapisanobjectoftheMapclassandthestateischangingwithdifferentoperations.

1.7 Hands-OnExperiencewithPython
1.7 Hands-OnExperiencewithPython
1.7 Hands-OnExperiencewithPython
1.7 Hands-OnExperiencewithPython

1.7 Hands-OnExperiencewithPython

ApointisthebasicdatamodelwithinGIS.Thissectionwillexaminehowto create a point class, including coordinates and calculations of the distances betweenpoints.Youwilllearnhowtocreatepointobjectsfrompointclass.

1. Opentheprogram(Figure1.12):

Windows→AllPrograms→ArcGIS→Python2.7

or

Windows→AllPrograms→Python2.7→IDLE(PythonGUI)

Windows→AllPrograms→Python2.7→IDLE(PythonGUI) FIGURE1.12 LaunchthePythonprogrammingwindow(GUI). 2.

FIGURE1.12

LaunchthePythonprogrammingwindow(GUI).

2. TypeinthepointclasscodesasshowninCode1.1.

CODE1.1 Creatingapointclassandgeneratingtwopoints,thencalculatingthedistancebetweenthetwopoints. Programmingtips: 1.

CODE1.1

Creatingapointclassandgeneratingtwopoints,thencalculatingthedistancebetweenthetwopoints.

Programmingtips:

1. Codingshouldbeexactlythesameasthefigureshows.

2. Theinitmethodisdefinedwithfourunderscores:two“_”beforeandtwo after“init.”

3. Pythoniscasesensitive,solower-anduppercaseofthesameletterwill makeadifference.

4. Thereisnoneedtounderstandeverystatementfor now;theywill be graduallyexplainedinthefollowingchapters.

now;theywill be graduallyexplainedinthefollowingchapters. 1.8 ChapterSummary
now;theywill be graduallyexplainedinthefollowingchapters. 1.8 ChapterSummary
now;theywill be graduallyexplainedinthefollowingchapters. 1.8 ChapterSummary
now;theywill be graduallyexplainedinthefollowingchapters. 1.8 ChapterSummary

1.8 ChapterSummary

ThischapterbrieflyintroducedGISprogrammingandincluded

• Ageneralintroductiontocomputerhardwareandsoftware

• DefinitionsofGISandprogramming

• Pythoninapracticalcontext

• PracticalknowledgeaboutseveralGISdatamodels

• Theunifiedmodelinglanguageformodelingobject-orientedGISdata

• Relevanthands-onexperience

PROBLEMS

• Definecomputer,programming,software,andGIS.

• Whatarethedifferentmethodstocategorizesoftware?

• WhatarethethreeGISdatamodelsfoundontheUMLdiagram?

• ExplainwhyweneedtolearnGISprogramming.

• UsetheUMLdiagramtomodeltherelationshipbetweenpolylines.

• UsetheUMLdiagramtomodeltherelationshipbetweenpolygons.

• Practice

Python’s

Chapter

3

tutorial:

• UsePythontocalculatethedistancebetweenPoint(1,2)andPoint(2,2).

• DiscusshowtoidentifyclassesusedonaworldmapandhowtouseUML

tocapturethoseclasses.

* SeeOMGathttp://www.omg.org/.

2

2 Object-OrientedProgramming This chapter introduces object-oriented programming in regard to Python’s
2 Object-OrientedProgramming This chapter introduces object-oriented programming in regard to Python’s
2 Object-OrientedProgramming This chapter introduces object-oriented programming in regard to Python’s
2 Object-OrientedProgramming This chapter introduces object-oriented programming in regard to Python’s

Object-OrientedProgramming

This chapter introduces object-oriented programming in regard to Python’s programminglanguage,classesandobjects,objectgeneration,inheritance,GIS classesandobjects,andageneralprogrammingexperience.

classesandobjects,andageneralprogrammingexperience. 2.1 ProgrammingLanguageandPython Programming language is
classesandobjects,andageneralprogrammingexperience. 2.1 ProgrammingLanguageandPython Programming language is
classesandobjects,andageneralprogrammingexperience. 2.1 ProgrammingLanguageandPython Programming language is
classesandobjects,andageneralprogrammingexperience. 2.1 ProgrammingLanguageandPython Programming language is

2.1 ProgrammingLanguageandPython

Programming language is defined as an artificial language used to write instructionsthatcanbetranslatedintomachinelanguageandthenexecutedbya

computer.Thisdefinitionincludesfourimportantaspects:(1)artificiallanguage,

atypeofprogramminglanguagecreatedsolelyforcomputercommunication;(2)

instructionbased,aprogramminglanguagewithlimitedinstructionssupportedby a specific computer or CPU; (3) translation, the conversion from human

instructionstoatechnicalcomputerprogram,orCPU;and(4)translator,ofwhich

therearetwotypes:interpreterandcompiler(AhoandUllman1972).

Therearetwodifferentmethodscomputerprogrammersusetoconvertlanguages into a legible format on the computer. One method requires a computer programmertocompileagroupofstatementswritteninaspecificlanguageand convertthemintoamachine-readableformatpriortorunningtheprogram.The other methodentails simultaneouslytranslatingthe language while runningthe program.Forexample,inCprogramming,weneedtouseCcompilertotranslate theprogramintomachinecodesbeforeexecution.Similarly,C++andJavaare compiling-type programing languages. BASIC programming language is an interpreter language (Lien 1981), in which the interpreter will translate the programwhile itis running.Likewise,Python,Perl,andPHPare considered interpreter languages. Therefore, in order to successfully use Python on a computer,aPythoninterpretermustalsobeinstalled. Programminglanguageshaveevolvedconsiderablyfrommachineandassembly languages to intermediate and advanced languages (Rawen 2016). Machine

languageinstructionsarerepresentedinaspecificsequenceusing0sand1s.One

singledigit,ornumber,iscalledabit.Acombinationofthreebitsiscalledan

octal number (aneight digit combinationusingthe numbers 0–7), whereas a

combinationoffourbitsiscalledahexnumber(a16digitcombinationusingthe

numbers0–15).Assemblylanguagesdepictthemachinebitoperationswitheasy-

to-remember text representations. Intermediate languages are typically more powerful and easy to code. Advanced languages are more similar to human language,donothaveaccesstospecifichardwarefunctions,andareexecutedon severaldifferenthardwaretypes. Theexampleusesdifferentrepresentationsfor the“printletter ‘A’for 1000

times”(Figure2.1).

the“printletter ‘A’for 1000 times”( Figure2.1 ). FIGURE2.1

FIGURE2.1

Print‘A’1000timesusingdifferenttypesoflanguages.

Machinelanguagesbecomeincreasinglydifficulttounderstandbyhumans,so

onlyspecificCPUsareabletoreadthelanguageaccurately(Hutchins1986).

Therefore,inGISprogramming,wenormallyuseadvancedlanguagessuchasC, Java,orPythoninsteadofmachineorassemblylanguage.

Cisatypicalprocedurallanguagethatwasdevelopedaround1969–1973and

became available to the general public around 1977–1979. It was officially

standardizedbytheANSIX3J11committeeinthemid-1980sandhasbecomeone

ofthemostcommonlyusedlanguagesinthecomputerindustry.Theearlyeditions

ofGRASS(GeographicResourceAnalysisSupportSystem,NetelerandMitasova

2013)GIS * open-sourcesoftwareandArcGISweredevelopedusingC.Bjarne

StroustrupofBellLaboratoriesexpandedCtoC++inordertosupportobject-

orientedfeatures.C++supportsCfeaturesinfunctioncallsandobject-oriented

classes/objectsfashion.BothCandC++arecomplexforbeginningprogrammers.

Since1999,ISO/ANSIhasstandardizedC++toimproveandmaintainstate-of-

the-artqualitywithintheindustry.CandC++arecommonlyusedinLinuxand haveinfluencedotherlanguagessuchasC#andJava. Developed bySunatSunWorld’95, Java is a pure object-oriented language developedtotargetInternetandcross-platformapplications.Overtime,Javahas become increasingly popular among IT companies such as Microsoft, Borland/Eclipse, IBM, and Sun. The official Java resource can be found at java.sun.com and an open-source compiler/programming environment can be foundontheEclipseFoundationwebsiteatwww.eclipse.com. PythonisaninteractivelanguageprogrammingsystemcreatedbyGuidovan Rossumin 1990. Python is dynamically written and uses automatic memory management.ThenonprofitPythonSoftwareFoundationconsistentlyupdatesand managesthisopen-sourceproject.Pythonisfullydevelopedinthatitcanwrite once and runmanytimes ondifferentplatforms. This bookwill analyze and

explain Python as it is applied to GIS and ArcGIS * programming. You can download any version from Python’s website; however, not all versions interactivelyworkwithArcGIS.Pythoniseasytolearnanduse,andissupported byArcGIS,whichiswhywehavechosenittobetheprogramminglanguagefor thisbook.

thisbook. 2.2 ClassandObject Classes and objects
thisbook. 2.2 ClassandObject Classes and objects
thisbook. 2.2 ClassandObject Classes and objects
thisbook. 2.2 ClassandObject Classes and objects

2.2 ClassandObject

ClassesandobjectsarewidelyusedinPython.Classdefinesthetemplatefora

categoryofobjectswithname,attributes,andmethods.Objectsareinstancesof

classeswithattributesandmethods.Theattributesandmethodscanbereferredto

usinga‘.’.Forexample,thecoordinateattributesandcalDismethodofapoint

objectcreatedfromaPointclasscanbereferredtousingpoint.x,point.y,and

point.calDis().

2.2.1 DefiningClasses

Pythonprovidesthemechanismtodefineaclassusingthekeywordclasswiththe

syntaxof‘classclassName:’,forexample,‘classPoint:’,‘classPolyline:’,or ‘classPolygon:’.Theattributesandmethodscanbedefinedforaclassusingthe

‘def’keyword.Figure2.2showsthePythoncodefordefiningaPointclasswith

attributesname,x,ydefinedandthemethodsetName()defined.Inthe

method,“0,0”waspassedinasvalueforx,y,andname.

init

method,“0,0”waspassedinasvalueforx,y,andname. init FIGURE2.2 AnexampleofdefiningaPointclasswithPython. to

FIGURE2.2

AnexampleofdefiningaPointclasswithPython.

to create/construct

objects.Themethodwillbecalledwhenwecreateanobjectusingtheclass(such

init methodhasfour‘_’—twobeforeandtwoafter

‘init’—tomakeittheconstructionmethodthatwill beusedwhencreatingan

object.Forallmethodsdefinedbyaclass,thefirstparameterisalways‘self’,

whichreferstotheobjectitself.Thiscanbeusedtorefertotheattributesand

createapoint

methodsoftheobjects.For example,the

objectwithselfasthefirstparameterandx,y,nameinitialvaluesfortheobject.

asPointclasshere).The

Many classes define a special method named

init ()

init

methodwill

Bydefault(withoutspecifyingthevalues),thevaluesforx,y,andnamewillbe0,

0,andblankstring,respectively.ThefirsttwostatementsofCode2.1createtwo

pointobjects(point0andpoint1).Theobjectpoint0iscreatedwithdefaultvalues

andpoint1iscreatedwithargumentsof1,1,and‘firstpoint’.Ifnoparametersare

givenwhencreatingpoint0,thedefaultvalues0,0,and’’willbeused.When

methodwillassign

thevaluespassedintotheattributesofpoint1.

values(1,1,’firstpoint’)aregivenparameters,the

init

values(1,1,’firstpoint’)aregivenparameters,the init CODE2.1

CODE2.1

Creatingapointmaypassinvaluetotheobjectthroughparameters.

2.2.2 ObjectGeneration

To create anobject, type objectName =className() withnone or multiple

parameters, whichwill be passed to the attributes declared inthe methods.

init ()

objectName=className(value1,value2,…)

InCode2.1, we generated two objects, point0 and point1. While declaring

objectpoint0,noparameterispassedwhilethreevalues(1,1,’firstpoint’)are

usedtogeneratepoint1.

To refer to anobject’s attribute or method, we start withthe objectName, followedbyaperiodandthenendwiththeattributenameormethodname.

objectName.attributeName

objectName.methodName()

Code2.1uses.x,.y,and.namefollowingtheobjectspoint0andpoint1torefer

totheattributesx,y,andname.Theinstructionpoint1.setName() iscalledto

changethenameofpoint1to‘secondpoint’.

2.2.3 Attributes

Eachclassmayhaveoneormoreattributes.Section1.4explainshowattributes

canbepublic,private,orprotectedtoindicatedifferentaccessibilitybyother

objects.Howdoyouexplicitlyspecifythepublicandprivateattributeswhile

declaringaclass?

Public:AttributesinPythonare,bydefault,“public”allthetime.

Private: Attributes that begin with a double underscore (“_”). Such attributes can be protected as private because it cannot be directly accessed. However, they can be accessed by object ClassName _attributeName,forexample,test Test_foobar,wheretestisanobjectof

Testclass,and_foobarisaprivateattribute(Code2.2).

Testclass,and_foobarisaprivateattribute( Code2.2 ). CODE2.2 Declarepublic,private,andprotectattributes. •

CODE2.2

Declarepublic,private,andprotectattributes.

Protect: Attributes prefix with a single underscore “_” by convention.

However,theystillcanbeaccessedoutsideoftheclassinPython.

AnotherimportantattributeinPythonisthestaticattribute,whichisusedtohold

datathatispersistentandindependentofanyobjectoftheclass(Code2.3).For

example,wecancreateamapincludingdifferentlayers,andthelayerscalecan

bestaticandthesametoalllayerobjects.

bestaticandthesametoalllayerobjects. CODE2.3 Declarestaticattributes.

CODE2.3

Declarestaticattributes.

Aclass(andinstantiatedobject)canhavespecialbuilt-inattributes.Thespecial

classattributesincludeaclassnameanddescriptionoftheclass(Code2.4).

CODE2.4 Specialclassattributes. • _name_:classname • _doc_:description • _bases_:parentclasses • _dict_:attributes

CODE2.4

Specialclassattributes.

• _name_:classname

• _doc_:description

• _bases_:parentclasses

• _dict_:attributes

• _module_:modulewhereclassisdefined

Thespecial objectattributesincludeaclassnameandanobject’sattributes

(Code2.5).

( Code2.5 ). CODE2.5 Specialobjectattributes. •

CODE2.5

Specialobjectattributes.

• _class_:classfromwhichobjectisinstantiated

• _dict_:attributesofobject

2.2.4 Inheritance

Chapter 1 introduces three important relationships among objects in object- orientedprogramming:inheritance,encapsulation,andpolymorphism.Inheritance isanefficientwaytohelpreuseadevelopedclass.Whileprivateattributesand methodscannotbeinherited,allotherpublicandprotectedattributesandmethods canbeautomaticallyinheritedbysubclasses. ToinheritasuperclassinPython,includethesuperclassnameinapairof parenthesesaftertheclassname.

classDerivedClassName(SuperClass1)

WecanalsoinheritmultipleclassesinPythonbyenteringmorethanoneclass

nameintheparentheses.

classDerivedClassName(SuperClass1,SuperClass2,SuperClass3)

Figure2.3showsanexampleofinheritance.AssumingwehaveaclassFeature,

whichincludesamethoddraw(),thentheclassPolygonwillinheritfromtheclass Feature.Withthisinheritance,thePolygonclasswillhavethemethoddraw()as well. When we define the ParkingLot class with the inheritance from the Polygon,theParkingLotwillhaveattributesofxandycoordinatesaswellasthe method draw(). The Polygon and ParkingLot may have different drawing implementations;however,youcanusethedraw()featureforboththePolygon and ParkingLot. This particular method using different implementations for differentsubclassesiscalledpolymorphism.

FIGURE2.3 An example of inheritance ( ParkingLot class inherits from class Polygon , and Polygon

FIGURE2.3

An example of inheritance (ParkingLot class inherits from class Polygon, and Polygon inherits from Feature).

2.2.5 Composition

Compositionisanefficientwaytohelpusreusecreatedobjects,andtomaintain the part-to-whole relationship between objects. To maintain the composition relationship,youmustdefineaclasswithanattributethatcanincludeanumberof otherclassobjects. Figure2.4showsanexampleofcomposition.TheclassPoint andtheclass PolygoninheritfromtheclassFeature.TheclassPolygonborderisdefinedbya sequenceofpointsformedinaringandiscapturedbypointattributes.Thepoints’ coordinatesarekeptinthepointobjects.NotonlydoesthisshowhowaPolygon objectrequiresanumberofPointobjects,butalsothecompositionrelationship betweenPointandPolygon.

FIGURE2.4 Compositionexample(a Polygon classincludesattributepointsasobjectsgeneratedfromclass Point ). 2.3

FIGURE2.4

Compositionexample(aPolygonclassincludesattributepointsasobjectsgeneratedfromclassPoint).

Point ). 2.3 Point,Polyline,andPolygon
Point ). 2.3 Point,Polyline,andPolygon
Point ). 2.3 Point,Polyline,andPolygon
Point ). 2.3 Point,Polyline,andPolygon

2.3 Point,Polyline,andPolygon

InGIS,therearethreebasicvectordatatypes,whichincludePoint,Polyline,and

Polygon(Chang2006).Wecanabstractthosefeaturesanddefineaclassforeach

ofthemtobereused.WecanalsodefineaFeatureclassasasuperclassforPoint,

Polyline,andPolygon.Thefollowingareexamplesofthefourclasses:

Feature:Normally,aFeatureclass(Figure2.5)hasanametokeepthe featurenameandamethoddraw()todrawthefeatureonamap.Thedraw methodshouldincludeatleasttwoparameters,selfandmap.Selfrefersto theobjectaccessingfeatureobjectdatawhiledrawing,whereasamap referstothebackgroundthatwewilldrawthefeatureon.

referstothebackgroundthatwewilldrawthefeatureon. FIGURE2.5 UMLdesignfor Feature

FIGURE2.5

UMLdesignforFeatureclasstodefinecommonattributesandmethodsofPoint,Polyline,andPolygon.

Forexample,Code2.6isanexampleofdefiningFeatureasaclassin

Python:

Point:APointclass(Figure2.6)shouldhaveatleasttwospatialattributes, xandy,torepresentthecoordinatesofapoint.Anothernonspatialattribute couldincludethename.APointclasscouldalsousecalDis()tocalculate thedistancebetweentwopoints.TheargumentforthecalDismethodis currentpointobject“self,”andanotherpointobject“point.”Thereturn valueforthedistancebetweentwopointsisdesignatedasfloat.

valueforthedistancebetweentwopointsisdesignatedasfloat. CODE2.6

CODE2.6

DefineaFeatureclassasasuperclassforPoint,Polyline,andPolygon.

FIGURE2.6 UMLdesignfor Point classtokeeppointvectordata.

FIGURE2.6

UMLdesignforPointclasstokeeppointvectordata.

Forexample,Code2.7isanexampleofdefiningPointasaclassin

Python:

AfterdeclaringaPointclass,wecaninitiateobjects.Forexample,we

canpopulatetwopointswithdata(1,2),(2,2),andthencalculatethe

distancebetweenthetwopoints(Code2.8).

canpopulatetwopointswithdata(1,2),(2,2),andthencalculatethe distancebetweenthetwopoints( Code2.8 ).

CODE2.7

DefineaPointclassinPython.

CODE2.7 DefineaPointclassinPython. CODE2.8 Calculatethedistancebetween(1,2)and(2,2). • Polyline:

CODE2.8

Calculatethedistancebetween(1,2)and(2,2).

Polyline:Definingapolylineclassrequiresdifferentattributestokeepthe dataofpolylinesandmethodsbypolylines.Forexample,twolistsofx,y coordinatesoralistofpointscanbeusedtokeepthex,ycoordinates dependingonthedesign.For object-orientedpurposes,wecanusethe

secondapproach(Figure2.7a).Forbettersystemperformance,datapoints

inpolylinesaredifferentfromreal objectsinGIS,soweusethefirst

approach(Figure2.7b).

objectsinGIS,soweusethefirst approach( Figure2.7b ). FIGURE2.7

FIGURE2.7

(a)UMLPolylineclassusespointobjectlisttokeepcoordinatesforpolylines.(b)UMLPolylinesclassusesx

andyliststokeepcoordinatesdataforPolylines.

Polygon:APolygonclass(Figure2.8)couldhaveoneattribute,“points,”

torepresentthelistofallpointsusedtodefinetheborderortwolists—the

xandycoordinatesforallsuchpoints.APolygonclassmayalsohavea

methodgetLength()tocalculatetheborderlengthofthePolygonwithout

arguments.Thereturnvaluefortheborderlengthofpolygonisdesignated

asfloat.

FIGURE2.8 UMLdesignfor Polygon classtokeeppolygonvectordata. 2.4 Hands-OnExperiencewithPython The Code2.9

FIGURE2.8

UMLdesignforPolygonclasstokeeppolygonvectordata.

FIGURE2.8 UMLdesignfor Polygon classtokeeppolygonvectordata. 2.4 Hands-OnExperiencewithPython The Code2.9
FIGURE2.8 UMLdesignfor Polygon classtokeeppolygonvectordata. 2.4 Hands-OnExperiencewithPython The Code2.9
FIGURE2.8 UMLdesignfor Polygon classtokeeppolygonvectordata. 2.4 Hands-OnExperiencewithPython The Code2.9
FIGURE2.8 UMLdesignfor Polygon classtokeeppolygonvectordata. 2.4 Hands-OnExperiencewithPython The Code2.9

2.4 Hands-OnExperiencewithPython

TheCode2.9definesaPolylineclassandcreatesapolylineobject.Typethe

exampleontoyourcomputeranddescribewhateachlinedefinesandwhyitis

includedinthecode.

includedinthecode. CODE2.9 APolylineclasshasoneattribute(points),twomethods(

CODE2.9

APolylineclasshasoneattribute(points),twomethods(setPoints(),andgetLength()).

setPoints (),and getLength ()). 2.5 ChapterSummary
setPoints (),and getLength ()). 2.5 ChapterSummary
setPoints (),and getLength ()). 2.5 ChapterSummary
setPoints (),and getLength ()). 2.5 ChapterSummary

2.5 ChapterSummary

Thischapterdiscussesobject-orientedprogrammingaswellashowtoprogram

objects,classes,andrelationships.Afterreading,youshouldbeabletodothe

following:

• Understandobject-orientedprogrammingusingPython.

• DefineaclassandknowhowtocreateobjectsusingPoint,Polyline,and

Polygon.

• Practiceinheritingsuperclasses.

• Knowhowtoreusethecodeanditsnecessaryfunctions.

PROBLEMS

1. Pickthreepoints,forexample,(1,100),(25,60),and(1,1).Couldyou

formapolylineorpolygonusingthesethreepoints?

2. Create analgorithmto calculate the distance betweentwo points, for example,(x 1 ,y 1 ),(x 2 ,y 2 ).

3. ReadPythonTutorial6.2and6.3.(UsePythoncommandlinewindowfor

6.2).

4. DefineandprogramthreeclassesforPoint,Polyline,andPolygon.

5. Adddistancecalculationin-betweeneverytwopoints,andprogramto calculatethedistanceamongthethreepointsgiven.

6. AddthegetLength()methodinPolylineandPolygon;createapolyline and polygon using the three points given; calculate the length of the polylineandperimeterofthepolygon.

SectionII

PythonProgramming

3

3 IntroductiontoPython Learningaprogramminglanguageisapracticalandprogressivejourney.Youwill
3 IntroductiontoPython Learningaprogramminglanguageisapracticalandprogressivejourney.Youwill
3 IntroductiontoPython Learningaprogramminglanguageisapracticalandprogressivejourney.Youwill
3 IntroductiontoPython Learningaprogramminglanguageisapracticalandprogressivejourney.Youwill

IntroductiontoPython

Learningaprogramminglanguageisapracticalandprogressivejourney.Youwill beginwiththebasics,andgraduallyincreaseyourskillsatcomplexcoding.This chapter will introduce fundamental Pythoncomponents, includingclasses and objects, syntax, data types, operators, functions, flow control, exceptions, input/output, and modules. A number of libraries are available for specific development,includinggraphical user interfaces,databases,Internet,andweb programming. To facilitate the learning process, you will utilize your understandingofGIStostartbuildinga mini-GISpackage while learningthe programminglanguage.

mini-GISpackage while learningthe programminglanguage. 3.1 Object-OrientedSupport One of Python’s most important
mini-GISpackage while learningthe programminglanguage. 3.1 Object-OrientedSupport One of Python’s most important
mini-GISpackage while learningthe programminglanguage. 3.1 Object-OrientedSupport One of Python’s most important
mini-GISpackage while learningthe programminglanguage. 3.1 Object-OrientedSupport One of Python’s most important

3.1 Object-OrientedSupport

One of Python’s most important characteristics is object-oriented structure. FoundationalPythonprogrammingrequiresunderstandingconceptsaboutclasses and objects, inheritance, composition, package, and class sharing. Python providesthemechanismtodefineaclassandcreateobjectsfromthatclass. Classes and objects are widely used in Python. Objects are instances of classes. Objects have attributes and methods. Dot(.) refers to attributes and

methodsofanobject.InChapter2,thisbookdefinedPointclassandcreatedp1

as a pointobject.Youcanuse p1.xandp1.calDis() to call the attribute and methodoftheobject.Inheritancehelpsyoureusetheattributesandmethodsofa class(superclass)byusingthesuperclasstodefinenewclassesintheformat ‘classsubclass(superclass)’.Allpublicandprotectedattributesandmethodsare inheritedbysubclassesautomatically.Privateattributesandmethodswillnotbe inherited.Forexample,threevectorclasses(Point,Polyline,andPolygon)are

definedbyinheritingtheFeatureclass’smethoddraw()asdetailedinChapter2.

Compositionhelpsmaintainthepart–wholerelationship,whereoneobjectofa

classincludesobjectsofotherclasses.Pythonusesobjectreferencetoimplement

thecompositionrelationship.AsdiscussedinChapter2,alistofpointsareused

tokeepthecoordinatesofapolylineorpolygonborder. Whenclassesandmethodsaredevelopedforsoftware,similarclasses/methods aregroupedintothesamemoduleforeasierorganization.So,allGISdataclasses canbeputintoonebigmodule.Submodulesincludeclasses/methodsforvector, raster,andspecialdatatypes.Ifotherclassesneedtoaccesstheclasses/methods inamodule,themodulemustbeimportedfirst.Forexample,themathmodulein

Code2.5andCode2.6areimportedtoaccessallmathmethods(e.g.,math.sqrt).

Code2.6 areimportedtoaccessallmathmethods(e.g.,math.sqrt). 3.2 Syntax 3.2.1 CaseSensitivity Pythonis casesensitive
Code2.6 areimportedtoaccessallmathmethods(e.g.,math.sqrt). 3.2 Syntax 3.2.1 CaseSensitivity Pythonis casesensitive
Code2.6 areimportedtoaccessallmathmethods(e.g.,math.sqrt). 3.2 Syntax 3.2.1 CaseSensitivity Pythonis casesensitive
Code2.6 areimportedtoaccessallmathmethods(e.g.,math.sqrt). 3.2 Syntax 3.2.1 CaseSensitivity Pythonis casesensitive

3.2 Syntax

3.2.1 CaseSensitivity

Pythoniscasesensitive,meaningcapitalandlowercaselettersrepresentdifferent identifiers.YoucandefineavariablemyListwithanuppercaseL,andstorethe

listofitems“1,2,3,and4.”Ifyougetthefirstvalueofthelistusingmylist[0]

withalowercasel,youwillseeaNameError,whichshowsthatmylistisnot

definedbecauseyoudefinedmyListusingacapitalL(Code3.1).

definedbecauseyoudefinedmyListusingacapitalL( Code3.1 ). CODE3.1 Casesensitive. 3.2.2 SpecialCharacters

CODE3.1

Casesensitive.

3.2.2 SpecialCharacters

Pythonhasalistofspecialcharacterswithspecialmeanings.Table3.1listssome

commonspecialcharactersandtheirrespectivefunctions.

TABLE3.1

SpecialCharactersinPython

Symbols

Function

Example

\

Escapecharactersthathavea

>>> print ''test'' test >>> print '\'test\'' 'test' >>> print '\\test' \test

 
specialmeaning
specialmeaning

specialmeaning

specialmeaning

\n

\ n

Newline

>>> print 'first line\nsecond line' first line second line

\ n N e w l i n e >>> print 'first line\nsecond line' first line

\t

\ t
\ t

Tab

>>> print 'str1\tstr2' str1 str2

\ t T a b >>> print 'str1\tstr2' str1 str2

:

Gotonextlevelofstatements

>>> class Polyline:

 

def getLength():

pass

pass

pass

#

#

IndicatePythoncomments

>>> # this is a comment

# IndicatePythoncomments >>> # this is a comment

;

Joinmultiplestatementsonasingle

>>> import math; x = math.pow(2,3) >>> import math y = math.pow(2,3) SyntaxError: invalid syntax

 

line

3.2.3 Indentation

InPython, indentationis important for groupingcode. Indented lines start at different positions or column; numbers are not allowed, theywill trigger an IndentationError.Youmayuseadifferentnumberofspacesorcolumnstoindent different levels of statements; however, 4 or 8 spaces are recommended. Therefore,spaceandtabsplaysignificantrolesinorganizingcodes.Different programeditors (e.g., command line and PythonGUI) use “tab” indifferent manners.Dependingonyourtexteditor,itmayrepresentdifferentnumbersof spaces.

3.2.4 Keywords

Keywords,suchasdefanddel,arereservedwordsandcannotbeusedforany otherpurpose(e.g.,asthenamesofvariables,classes,andobjects);otherwise,a

SyntaxErrorwilloccur(Code3.2).Table3.2liststhekeywordsinPython.

SyntaxError willoccur( Code3.2 ). Table3.2 liststhekeywordsinPython.

CODE3.2

KeywordsSyntaxErrorexample.

TABLE3.2

PythonKeywords

and

and

elif

global

or

and elif global or

assert

assert

else

if

pass

assert else if pass

break

break

except

import

print

break except import print

class

class

exec

in

raise

class exec in raise

continue

continue

finally

is

return

continue finally is return

Def

Def

for

lambda

try

Def for lambda try

Del

from

not

while

3.2.5 MultipleAssignments

Multipleassignmentsareusefulindeclaringvariablessimultaneously.

InCode3.3,

In Code3.3 , CODE3.3 Multipleassignments. •

CODE3.3

Multipleassignments.

• Thefirstlineofcodeassignsthesamevaluetomultiplevariablesbyusing “a=b=c=value.”

• The second and third lines of code assigndifferent values to different

variablesbyusing“a1,b1,c1=v1,v2,v3,”or“(a2,b2,c2)=(v1,v2,

v3).”

3.2.6 Namespace

Anamespaceisaplaceinwhichanameresides.Variableswithinanamespace are distinctfromvariables havingthe same names butlocated outside ofthe namespace.Itisveryeasytoconfusenamesindifferentnamespaces.Namespace

layeringiscalledscope.Anameisplacedwithinanamespacewhenthatnameis given a value. Use dir to show the available names within an indicated namespace.Forexample,dir()canfindcurrentnamespacenames,dir(sys)will findallnamesavailablefromsys,anddir(math)willfindallnamesavailable

frommath.Aprogramtypicallyincludesthreelayersofscope(Figure3.1):

• Thetoplayerisasystembuilt-innamespace,whichincludesnamesdefined within Python itself; these are always available in your programming environment.

• Themiddlelayerisglobalnamespacedefinedwithinafileormodule.

• Thebottomlayerislocalnamespace,whichincludesnamesdefinedwithin afunctionoraclassmethod.

afunctionoraclassmethod. FIGURE3.1 Hierarchyofnamespaces. 3.2.7 Scope Scope

FIGURE3.1

Hierarchyofnamespaces.

3.2.7 Scope

Scopereferstoaportionofcodeandisusedtoidentifytheeffectivenessof variables.Scopeisimportantinfunctions,modules,classes,objects,andreturned data.Moduleswithfunctionanddataactsimilartoobjects.Forexample,when

definingPointclass,usep1asavariablewithinthecalDis()functionoftheclass;

orusep1torefertoanobjectlaterwhencreatingapointobject.Thefirstp1is

onlyeffectiveinthescopeofthePointclass’calDis()function.Thesecondp1is

onlyeffectiveatthesamelevelastheoverallprogramwithoutindentation.

Variablescanbelocalorglobal:

• Local variablesaredeclaredwithinafunction,andareonlyaccessible withinthefunction.Oncethefunctionisexecuted,thevariablewillgoout ofscope.

• Globalvariablesarenonlocalandcanbeaccessibleinsideoroutsideof functions.

IntheexampleofFigure3.2,global_xisaglobalvariableandlocal_yisalocal

variable.Ifyouuselocal_yvariableoutsidethefunction,youwillgetanerror. For more information about namespaces and scope, please refer to Raschka

(2014).

about namespaces and scope, please refer to Raschka (2014). FIGURE3.2 Localandglobalvariables. 3.3 DataTypes Inpython,

FIGURE3.2

Localandglobalvariables.

refer to Raschka (2014). FIGURE3.2 Localandglobalvariables. 3.3 DataTypes Inpython, datatypes
refer to Raschka (2014). FIGURE3.2 Localandglobalvariables. 3.3 DataTypes Inpython, datatypes
refer to Raschka (2014). FIGURE3.2 Localandglobalvariables. 3.3 DataTypes Inpython, datatypes
refer to Raschka (2014). FIGURE3.2 Localandglobalvariables. 3.3 DataTypes Inpython, datatypes

3.3 DataTypes

Inpython,datatypesaredynamicsothatyoudonothavetodefineavariable’s

datatype.Thetypeofvariablewillbeassignedwhenavalueisassigned.The

changeinvalueswillchangethetypeofvariables.Therearetwocategoriesof

datatypes:basicdatatypes(integer,floating,long,complex,strings,type,and

function)andcompositedatatypes(lists,tuples,anddictionaries).

3.3.1 BasicDataTypes

Thebasicdatatypesincludenumberandstringcategories.Thenumbercategory

includesintegers,longintegers,andfloat(Table3.3).

TABLE3.3

 

BasicDataTypes

BasicVariable

 

Conversion

Types

Range

Description

Examples

(Typecast)

Number Integer 2 31 ~2 32

decimal,octal,and

20,−20,010,

int(),e.g.,int(2.0),

hexadecimalformat ox80 int(‘2’),int(2L)
hexadecimalformat ox80 int(‘2’),int(2L)
hexadecimalformat ox80 int(‘2’),int(2L)

hexadecimalformat ox80

hexadecimalformat ox80

int(‘2’),int(2L)

int(‘2’),int(2L)

Long

Limitedonlybymemory

Denotedby(L)or

20L,−20L,

long(),e.g.,

integer (l). 010L,ox80L long(2),long(‘2’)

integer

integer
integer (l). 010L,ox80L long(2),long(‘2’)

(l).

integer (l). 010L,ox80L long(2),long(‘2’)

010L,ox80L

long(2),long(‘2’)

long(2),long(‘2’)

float Dependsonmachine architectureandpython interpreter

float Dependsonmachine architectureandpython interpreter
float Dependsonmachine architectureandpython interpreter
float Dependsonmachine architectureandpython interpreter

Denotedbya

0.0,−77.0,1.6, float(),e.g.,

decimalpoint (.) 2.3e25,4.3e-2 float(2),

decimalpoint(.)

decimalpoint (.) 2.3e25,4.3e-2 float(2),

2.3e25,4.3e-2

float(2),

float(2),

String

N/A

Denotedby(‘’),

‘test’,“test”

str(),e.g.,str(2.0)

 

(“”)

• Integers

IntegersareequivalenttointegersinCprogramminglanguage.Therange

ofanintegerislimitedasfollows:

−2 31 ~2 32 (−2147483648~4294967296) The integer value can be represented by a decimal, octal, and

hexadecimalformat.Forexample,010isanoctalrepresentationof8and

ox80isahexadecimalof8.

• Longintegersofnonlimitedlength

Therangeoflongintegerisonlylimitedbycomputermemory.Along

integerisdenotedbyappendinganupper-orlowercase“L.”Itcanalsobe

representedindecimaloctalandhexadecimalformats.

• Float

FloatingnumbersareequivalenttodoublesinClanguage.Afloatvalueis

denotedbyadecimalpoint(.)intheappropriateplaceandanoptional“e”

suffix(eitherlowercaseoruppercase)representingscientificnotation.The

precision,orrangeofthefloat,dependsonthearchitectureofamachineas

wellasthePythoninterpreterused.

• Conversionofnumbers Theint(),long(),float()built-infunctionsareusedtoconvertfromany

numerictypetoanother(Code3.4).

numerictypetoanother( Code3.4 ). CODE3.4 Datatypeconversion. Tips Typecast: Convertdata

CODE3.4

Datatypeconversion.

Tips

Typecast: Convertdata fromone type to another, for example, float(‘3.14’), whichcastsastringdatatypetofloat.

Typeconversedassignmentmayresultinlostprecision,forexample

y=3.14

x=int(y)

wherexwilllosetheprecisionvaluesandhasavalueof3asaresult.

• Strings Stringdataaredenotedbysinglequotes‘’ordoublequotes“”.

• Otherbuilt-intypes Thereareseveralotherbuilt-indatatypes,suchastype,None,function,

andfile.Code3.5illustratesthefollowingtypes:

Functiontype()takesanobjectasanargumentandreturnsthedata typeoftheobject. Noneisthenullobjectandhasnoattribute. bool objecthas two potential values: True and False. Conditional expressionswillresultinBooleanvalueaseitherTrueorFalse.

CODE3.5 Functiontype,Nonetype,andbooltype. Tips DifferentfromCorJavalanguage,PythondoesnotsupportByte,Boolean,Char,

CODE3.5

Functiontype,Nonetype,andbooltype.

Tips

DifferentfromCorJavalanguage,PythondoesnotsupportByte,Boolean,Char,

Pointerdatatypes.

3.3.2 CompositeDataTypes

Anothercategoryofbuilt-invariabledatatypesiscalledacompositedatatype

(Table3.4).Compositedatatypesareorderedandsequentiallyaccessiblevia

indexoffsetsintheset.Thisgroup,alsoknownassequences,typicallyincludes list, tuple, dictionary, and set. Alist is different types of data separated by

commas,andareincludedinapairofbrackets,forexample,[1,2,3,4].Tuples

arelistsofdifferenttypesofdata,suchas(1,“thefirstratedproducts,”“milk”)

setoffbyparentheses.Dictionariesarelistsofkeysandvaluepairs,asshownin

thefollowingexample{‘john’:‘3-1111’,‘phil’:’3-4742’,‘david’:‘3-1212’}

• List Themostcommonlyusedandimportantcompositedatatypeislist,which canbeusedtogroupdifferentvaluestogether.Uselisttokeepaseriesof points,polylines,andpolygonsinGISprograms. Define: A list object can be created from: [v1, v2, v3, ….], where

elementsaresurroundedbyasquarebracket(e.g.,asinCode3.6).

CODE3.6 Listexample. Operators: Composite data types are good for expressing complex operationsinasinglestatement.

CODE3.6

Listexample.

Operators: Composite data types are good for expressing complex

operationsinasinglestatement.Table3.4listscommonoperatorsshared

bycomplexdatatypes.

TABLE3.4

CompositeDataTypesandCommonOperators

Container

Define

Feature

Examples

CommonOperators

List

Delimitedby mutable [‘a’,‘b’,‘c’] [];

seq[index],seq[index1:index2],seq*expr,

seq1+seq2,objinseq,objnotinseq,

  Tuple Denotedby immutable (‘a’,‘b’,‘c’)   parenthesis ()
  Tuple Denotedby immutable (‘a’,‘b’,‘c’)   parenthesis ()
 

Tuple

Denotedby

immutable (‘a’,‘b’,‘c’)

 

parenthesis

()

()

()

len(seq)etc

dictionary {key:value,

mutable {‘Alice’:

key:value,

‘7039931234’,

…}

‘Beth’:

‘7033801235’}

• seq[index]:getsavalueforaspecificelement.Thestartingindexofall

sequencedatais0,andtheendindexisonefewerthanthenumberof

elementsninthesequence(i.e.,n-1)(Code3.6a).

elements n inthesequence(i.e., n -1)( Code3.6a ). CODE3.6a AListoperation.

CODE3.6a

AListoperation.

Ifyoutrytoaccessanelementwithanindexthatislargerthanthenumber ofthetotalelements,thenyouwillgetanIndexError,indicatingtheindexis

outofrange(Code3.6b).

IndexError ,indicatingtheindexis outofrange( Code3.6b ). CODE3.6b Listoperationoutofrange. •

CODE3.6b

Listoperationoutofrange.

• len[list]:getsthelengthoftheelements(calculatesthetotalnumberofthe

element)(Code3.6c).

CODE3.6c Listlength. • seq[index1:index2]:generatesanewsequenceofdatatypewithelements sequencedfromindex1toindex2(

CODE3.6c

Listlength.

• seq[index1:index2]:generatesanewsequenceofdatatypewithelements

sequencedfromindex1toindex2(Code3.6d).

sequencedfromindex1toindex2( Code3.6d ). CODE3.6d SubsetaList. • del

CODE3.6d

SubsetaList.

delseq[index]:deletestheelementssequencedasindex(Code3.6e).

seq[index]:deletestheelementssequencedas index ( Code3.6e ). CODE3.6e DeleteanelementfromaList. • seq*expr( Code3.6f )

CODE3.6e

DeleteanelementfromaList.

• seq*expr(Code3.6f)

CODE3.6e DeleteanelementfromaList. • seq*expr( Code3.6f ) CODE3.6f Listmultipliesaninteger. •

CODE3.6f

Listmultipliesaninteger.

• seq1+seq2:unionstwosequenceobjects(Code3.6g)

) CODE3.6f Listmultipliesaninteger. • seq1+seq2:unionstwosequenceobjects( Code3.6g ) CODE3.6g Uniontwosequenceobjects.

CODE3.6g

Uniontwosequenceobjects.

• objinseq(objnotinseq):loopsthrougheachobjectinthecomplexdata andperformsanoperationwitheachelement.Theexamplegoesthrough eachobjectinthelista,andaddsthevalueofeachobjecttothesumobj

(Code3.6h).

( Code3.6h ). CODE3.6h Loopeachobjectinthecomplexdata.

CODE3.6h

Loopeachobjectinthecomplexdata.

Stringdatatypealsobelongstothesequencedatatype,andthoseoperatorscan beappliedtoastringobject. Methods:Asseenintheclassescreatedinthepreviouschapters,alistisa systembuilt-inclass.Theobjectscreatedfromlisthavemanymethods.Themost important methods include append(), insert(), remove(), pop(), sort(), and

reverse()(Code3.7).

, remove() , pop() , sort() , and reverse() ( Code3.7 ). CODE3.7 Listmethods. Built-infunctions:

CODE3.7

Listmethods.

Built-infunctions:Therearethreecommonbuilt-infunctionsforhandlingalist,

whicharehandyinGISprogramming(Khalid2016):

filter(func,list):Filterisusedtoextractatargetlistfromtheoriginallist. For example, youcanuse the filter functionto selectall cities within Virginia,orselecttherestaurantsandhotelswithinFairfaxcity.

map(func,list):Mapisusedtoconverttheoriginallisttoanewlistusing thefunction.Forexample,youcanconvertitfromdegreestometers.

reduce(func,list):Reduceisanothermethodthatisusefulforreal-world GISproblems.TocalculatethetotalstreetorroadlengthofFairfaxCounty, reducecaninvokeafunctionfunciterativelyovereachelementofthelist, returningasinglecumulativevalue.

• Tuple Similartolists,tupleisanothercomplexdatatype.Oneobviousdifference betweentuple and listis thatitis denoted bythe use ofparentheses. Another difference is that tuple data type is immutable (Table 3.4), meaningthattheelementcannotbealteredonceitisdefined.Anerrorwill

occurifthevalueofatupleelementisaltered(Code3.8).

occurifthevalueofa tuple elementisaltered( Code3.8 ). CODE3.8 Tupleoperation. • Dictionary

CODE3.8

Tupleoperation.

• Dictionary

AdictionaryismutableandacontainerdatatypethatcanstoreanyPython

objects,includingothercontainertypes.Adictionarydiffersfromsequence

typecontainers(listsandtuples)inhowthedataarestoredandaccessed.

Define:Thesyntaxusedtodefineadictionaryentryis{key:value,key:value,

all elements are enclosed inbraces.Itis convenientfor storing

spatialfeatureobjectssoeachobjectwillincludeauniqueobjectID,spatial attributes(coordinates),andnonspatialattributes(e.g.,Name).WhereuniqueIDs canbeusedaskey,allattributescanbeusedasavalue.Thekeysareintegersor

stringswhilevaluescanbeanydatatype,suchaslistordictionary(Code3.9).

… },where

list or dictionary ( Code3.9 ). … },where CODE3.9 Dictionaryoperation. In Code3.9 , parkingLots

CODE3.9

Dictionaryoperation.

InCode3.9,parkingLotsisdeclaredasadictionarydatatypethatincludestwo

elements.TheuniqueIDandparkinglotsequence‘A’and‘B’areusedasthekeys,

andtheattributeinformationofeachkeyisheldinadistinctlist.

• Set Set is used to constructand manipulate unsorted collections ofunique

elements.Asetobjectcaneitherbecreatedfrom{v1,v2,v3,….}where

elementsaresurroundedbybraces,orfromaset(list)wheretheargument

isalist(Code3.10).

}where elementsaresurroundedbybraces,orfroma set(list) wheretheargument isa list ( Code3.10 ). CODE3.10 Setoperation.

CODE3.10

Setoperation.

Operations: Setsupports several operations (Table 3.5), includingunion(|),

intersection(&),difference(-),andsymmetricdifference(^)(Linuxtopia2016).

TABLE3.5

OperationsbetweenTwoSetObjects,sandt

Operation Operator

Function

Usage

 

difference

Createanewsetwith

elementsin s butnotin t

elementsinsbutnotint

elementsin s butnotin t
 

intersection

&

Createanewsetwith

Getspatialobjectswithbothconditionsmatched,such

 

elementscommontos

asfindingtherestaurantswithinFairfax,aswellas

and t withFrenchstyle

andt

withFrenchstyle

and t withFrenchstyle
 

symmetric

^

Createanewsetwith

difference

elementsineithersort

butnotboth
butnotboth

butnotboth

butnotboth
butnotboth
 

union

|

Createanewsetwith

Combinetwostates’citiestogetcollection

elementsinbothsandt

Methods:Setisasystembuilt-inclass.Severalimportantmethodsaresupported by a set object, including add(), remove(), and pop(). It also supports four methods:difference(),intersection(),symmetric_difference(),andunion()(Code

3.11).

Code 3.11 ). CODE3.11 Setoperations. 3.4 Miscellaneous

CODE3.11

Setoperations.

Code 3.11 ). CODE3.11 Setoperations. 3.4 Miscellaneous
Code 3.11 ). CODE3.11 Setoperations. 3.4 Miscellaneous
Code 3.11 ). CODE3.11 Setoperations. 3.4 Miscellaneous
Code 3.11 ). CODE3.11 Setoperations. 3.4 Miscellaneous

3.4 Miscellaneous

3.4.1

Variables

Avariableisamemoryspacereservedforstoringdataandreferredtobyits name.Beforeuse,avariableshouldbeassignedavalue.Variableshavedifferent typesofvalues.Thebasicvariablevaluetypesincludebyte,short,int,long,text, float,anddouble, as introducedinSection3.4.1. Some types ofdata canbe convertedusingtypecast.For example,float(“3.14”) will converttexts intoa

floatingnumber3.14.

InPython,variabletypesaredynamic,withthetypeonlydefinedwhenitsvalue is assigned. This means a variable canchange to a different data type. For

example(Figure3.3),x=float(1)willassignxasfloat,butx=‘xhasadynamic

type’willchangethevariablexfromafloattypetoastringtype.Here,weuse

‘p1’asanobjectvariablename.

‘p1’asanobjectvariablename. FIGURE3.3 Dynamicdatatype. Anameis requiredfor

FIGURE3.3

Dynamicdatatype.

Anameis requiredfor eachvariable.Thevariable’s namemustbealegal identifier,whichisalimitedcombinationseriesofalphabetletters,digits,and underscores.Thenamemustbeginwithacharacterorunderscore,butitmaynot

startwithadigit.Therefore,‘point1’isalegalname,but‘1point’isillegal.In

addition,blanksarenotallowedinvariablename.Pythonreservedwords(Table

3.2)cannotbeusedasvariablename.

3.4.2 CodeStyle

ThereareseveralguidelinestoPythonprogrammingstyle.

Meaningful names: Use meaningful names for variables, classes, and packages.Ifthemeaningisnotclear,addacommenttoidentifywhatthe namemeans. Whitespaceinexpressionsandstatements:Alwayssurroundoperatorswith asinglespaceonbothsides. Indentation: Indented codes are used to organize code, as introduced in

Section3.2.3.

Comments:Commentsareusedfordocumentingorexplainingcode.Python

supportstwokindsofcomments:

#comments

Thecompilerignoreseverythingfromthe#totheendoftheline.

"""commentsline1

commentsline2

"""

This comment style indicates documentation strings (a.k.a. "docstrings"). A docstringisthefirststatementinamodule,function,class,ormethoddefinition. Allmodulesshouldhavedocstrings,andallfunctionsandclassesexportedbya

moduleshouldhavedocstrings(Figure3.4).

moduleshouldhavedocstrings( Figure3.4 ). FIGURE3.4 Codingstyle. 3.5 Operators

FIGURE3.4

Codingstyle.

moduleshouldhavedocstrings( Figure3.4 ). FIGURE3.4 Codingstyle. 3.5 Operators
moduleshouldhavedocstrings( Figure3.4 ). FIGURE3.4 Codingstyle. 3.5 Operators
moduleshouldhavedocstrings( Figure3.4 ). FIGURE3.4 Codingstyle. 3.5 Operators
moduleshouldhavedocstrings( Figure3.4 ). FIGURE3.4 Codingstyle. 3.5 Operators

3.5 Operators

Operators include basic characters, division and type conversion, modulo, negation, augmented assignment, and Booleanoperations. These operators are categorizedintoseveraltypes:

• ArithmeticOperators(Table3.6)

TABLE3.6

ArithmeticOperators(AssumeVariableaHolds5andVariablebHolds2)

Arithmetic

 

Operators

Description

Example

+

Addition

>>>a+b

7

7

7

Subtraction

>>>a−b

3

3

3

*

Multiplication

>>>a*b

10

10

10

/

Division

>>>a/b

2.5

2.5

2.5

**

Exponentiation:Performsexponential(power)calculationonoperators

>>>a**

 

b