forked from GeoScripting-WUR/PythonWeek
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.Rmd
434 lines (316 loc) · 10.1 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
---
title: "Lesson 14 and 15: Python for geo-scripting"
author: "Jan Verbesselt, Jorge Mendes de Jesus, Aldo Bergsma, Eliakim Hamunyela"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
theme: cosmo
toc: true
toc_depth: 4
number_sections: true
highlight: pygments
---
# To do
## Morning: Self-study
Reminder: Self-study is critical for the completion of the excercises at the end of the tutorial!
- Optional (!!!): if you have not followed the "Python course", it is highly recommended to follow the Python Refresher via: http://www.codecademy.com/tracks/python
- Follow and complete:
* Thursday morning: the Python intro below and https://geoscripting-wur.github.io/PythonWeek/VectorPython.html
* Friday morning: https://geoscripting-wur.github.io/PythonWeek/RasterPython.html
## Afternoon: Feedback and discussion
Slides for during the lesson:
https://geoscripting-wur.github.io/PythonWeek/Slides.html
# Learning outcomes
* knowing how to handle spatial data using Python
* vector data handling
* creating a point, writing and modifying a shape file
* raster data handling
* reading and writing raster data
* calculating indices
* projection raster data
# Intro
Using Python within OSGEO Linux
- Wide user community and support
- Free
- Flexiblility
- Open-source
How?! via:
- GDAL/OGR
- GEOS
Have a look at this question on GIS StackExchange:
- https://gis.stackexchange.com/questions/34509/alternatives-to-using-arcpy
- https://gis.stackexchange.com/questions/16657/clipping-raster-with-vector-layer-using-gdal
# Getting started with Python within a Linux OS
- Launch [OS-GEO live](http://live.osgeo.org/en/index.html) from the VMware player and login.
** Question: Do you know wat OS-GEO is?
- Open the Terminal and type the following to check the installed GDAL version:
```{r, eval = FALSE, engine='bash'}
## from R: system("gdal-config --version")
## From the terminal:
gdal-config --version
```
- type the following to start python and find out what the python version is:
```{r, eval=FALSE}
python # type this in the terminal to start the python interpreter
```
An example script to find out what the installed Python version is ([more info in question asked on stackoverflow](https://stackoverflow.com/questions/1093322/how-do-i-check-what-version-of-python-is-running-my-script))
```{r, engine='python'}
import sys
print sys.version #parentheses necessary in python 3.
```
To exit python:
```{r, eval=FALSE}
exit()
```
- Open the python script within a Python editor
# A short Python refresher
## IPython and IPython notebook
See here for a simple IPython notebook example:
http://nbviewer.ipython.org/github/GeoScripting-WUR/PythonWeek/blob/gh-pages/A%20simple%20notebook.ipynb
## Finding help
```{r, engine='python', eval=FALSE}
import sys
help(sys)
help(1)
```
**Question**: What does this mean `___ ___` around words: e.g: `___doc___`
Try out the following!!!
```{r, engine='python'}
help('hamster')
```
see also:
* http://www.rafekettler.com/magicmethods.html
* https://stackoverflow.com/questions/1090620/special-magic-methods-in-python
## Finding information via Pydoc
Go to: https://docs.python.org/2/library/pydoc.html
```{r, engine='bash', eval=FALSE}
pydoc -p 1234
echo "pydoc server ready at http://localhost:1234/"
```
Then go to `http://localhost:1234/` via your preferred browser.
## Numbers and variables
*Question*: What is the difference between 10 and 10.0 when dealing with datatypes in Python???
```{r, eval=FALSE, message=FALSE, echo=FALSE}
# 10 -> Integer -> Natural + negative numbers
## Int
# 10.0 -> Floating point -> Real number() -> "digits before and after the decimal point"
## Float
```
```{r, engine='python'}
print(int(10.6))
```
Variable is a storage location or symbolic name to a value e.g.
```{r, engine='python'}
building = 'Gaia'
buildingNumber = 101
'Gaia'
"doesn't"
'Gaia' + 'is in Wageningen'
```
There is no need to say or define the datatype, `python` has a loose type variable declaration.
*Walk like a duck and swims like a duck and quacks like a duck I call it a duck*
Python is basically a list of objects:
List are organised with indexes. E.g.
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(engine = 'python')
```
## Lists
```{r campus, engine='python'}
campus = ['Gaia','Lumen', 'Radix', 'Forum']
# how to can we print Forum?
print(campus[3])
# how to access the end of the list (while having no idea how big it is)
print(campus[-1])
# how to access the first 3 items
print(campus[0:3])
```
Appending, inserting, extending and steps:
```{r, engine='python'}
campus = ['Gaia','Lumen', 'Radix', 'Forum']
campus.append("Atlas")
campus.insert(1,"SoilMuseum")
campus.extend(["Action","Vitae", "Zodiac"])
print campus
print campus[::2]
## list[start:end:step]
```
*Question?*: What are the major differences between Append/Extend?
**Question:** What building is campus[-2]?
## Dictionaries, loops, if/else
Let there be Dictionaries... Dictionary is an unordered set of key:value pairs. Like in the dictionary, 'food':'voedsel'.
```{r, engine='python'}
# dictionary
campusDic = {101:'Gaia',
100:'Lumen',
107:'Radix',
102:'Forum',
104:'Altas'}
print campusDic[102]
```
Loops: watch out here with code intendation. Python uses Intendation to define code block and not `{}` like other languages.
Print building has to be *intended* normally 1 tab or 4 spaces (recommended).
```{r, engine='python'}
campus = ['Gaia','Lumen', 'Radix', 'Forum']
for building in campus:
print building
```
Here, `building` is a variable that will contain any item in the campus list.
Generic loops in python have to interact over a sequence of objects e.g.
```{r, engine='python'}
range(5)
for number in range(5):
print number
```
Object interaction and functional programming is an important part of python programming and its tools are extensive.
If/else:
```{r, engine='python'}
x = 3
if x < 3:
print "below 3"
else:
print "above 3"
```
```{r, engine='python'}
x = 3
if x == 1:
print "it is one"
elif x==2:
print "it is two"
elif x==3:
print "it is three"
else:
print "above 3"
```
## Functions
A function is a section of code that does something specific that you want use multipletimes without having to type the full function again but just call the function by its name.
```{r}
def printPotato():
print "potato"
printPotato()
```
Functions accept arguments and return variables e.g.:
```{r}
def printPotato(something):
print something
printPotato("test")
```
`return` is used to indicate what you want to obtain from the function, and you can `return` multiple items.
```{r}
def times3(number):
tmp = number*3
return tmp, number
print times3(4)
```
## Importing modules
Try this!
```{r, engine='python', eval=FALSE}
import this
```
```{r, engine='python', eval=FALSE}
from __future__ import braces
```
```{r}
import math
print dir(math)
```
- The best way is to check documentation: https://docs.python.org/2/.
- Modules are Python's butter and bread.
- A module contains code that can be used or excuted.
Basically 2 ways to load a module:
```{r}
import math
print math.pi
from math import pi
print pi
```
Why is `import math` the best way to import modules?
```{r, eval=FALSE, echo=FALSE}
from numy import pi
from math import pi
```
## Some important internal modules:
- `os`: Access to operating system features
- `os.path`: Manipulating of file names
- `sys`: System specific configuration
- `glob`: Filename pattern matching
- `math`: Mathametical functions
- `datetime`: Date/Time manipulation
*Question*: What is the difference between `os` and `os.path`?
Some examples:
```{r, eval=FALSE}
import glob
glob.glob("*")
```
```{r}
from datetime import timedelta,date
delta = timedelta(days=7)
print date.today()
print date.today()+delta
```
## File access
Very simple for 99% of the cases
Write something to file:
```{r, engine='python'}
fileObj = open('test.txt','w')
fileObj.write('some simple text')
fileObj.close()
```
```{r}
fileObj = open('test.txt','r')
a = fileObj.read()
print a
fileObj.close()
```
**Question**: What does `r` and `w` mean?
## Error handling
Sometime problems occur... Errors detected during execution are called *exceptions*
Good code deals with exceptions:
```{r, eval=FALSE}
>>> >>> open("/foo0")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '/foo0'
```
The file doesn't exist, so the script stops and outputs an ugly msg
How to deal with this I/O error??? Good progamming!!!
```{r, engine='python'}
try:
open("foo")
except IOError:
print "no file"
## we can be more precise:
try:
open("/foo")
except IOError:
print "no file"
```
## Python statements
- `if`
- `for`
- `while`
- `try`
- `class` which executes a block of code and attaches its local names to a `class`, for use in object oriented programming
- `def` which defines a function or statement
- `with` which encloses a code block within a context manager
- `pass` statement, which serves as a `NOP` (no operation)
- `assert`, used during debugging to check for conditions that ought to apply
- `yield`
- `import`
# Handling Vector data with Python
Go to [Vector Data handling in Python](https://geoscripting-wur.github.io/PythonWeek/VectorPython.html)
# Raster data with Python
Go to [Raster Data handling in Python](https://geoscripting-wur.github.io/PythonWeek/RasterPython.html)
# R from Python
A very simple example using the Python Rpy2 module (only possible on Mac/Linux). This is working with your OS-GEO live linux virtual machine. Try it out! :smile:
```{r, engine='python', eval =FALSE}
import rpy2.robjects as robjects
pi = robjects.r['pi']
print(pi[0])
```
# More info
- A great book: [Python Geospatial Development](http://www.amazon.com/Python-Geospatial-Development-Second-Edition/dp/178216152X)
- [The official python tutorial](https://docs.python.org/2/tutorial/)
- [Python Tutorial](http://www.tutorialspoint.com/python/)
- [Stack OverFlow Python](https://stackoverflow.com/questions/tagged/python)
- [GIS Stack Exchange](https://gis.stackexchange.com/)