Skip to content

Commit cda6894

Browse files
SwinkelsSwinkels
authored andcommitted
Update to Python3
1 parent 4780231 commit cda6894

File tree

4 files changed

+282
-299
lines changed

4 files changed

+282
-299
lines changed

.ipynb_checkpoints/Raster data handling-checkpoint.ipynb

Lines changed: 82 additions & 85 deletions
Large diffs are not rendered by default.

Raster data handling.ipynb

Lines changed: 82 additions & 85 deletions
Large diffs are not rendered by default.

VectorPython.Rmd

Lines changed: 57 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,12 @@ OGR supports many different vector formats:
4242
**OGR Data drivers:** A driver is an object that knows how to interact with a certain data type (e.g. a shapefile).
4343
You need to know the right driver to read or write data. Some drivers might only be able to read content, but the majority can read and write.
4444

45-
```{r, engine='python'}
45+
Start a terminal and see if you can load osgeo in Python.
46+
```{r, engine='bash', eval = FALSE}
47+
python
48+
```
49+
50+
```{r, engine='python', eval = FALSE}
4651
try:
4752
from osgeo import ogr
4853
except:
@@ -57,17 +62,42 @@ ogrinfo --formats
5762

5863
[More info about the different OGR formats](http://www.gdal.org/ogr_formats.html).
5964

60-
## Points
65+
## Setting up environment
66+
Before we continue with scripting, you need to setup your Python environment. In the previous Python lesson you learned about Conda and Jupyter Notebooks. We will use both again today. Check if you have made any conda environment named geoscripting.
67+
68+
```{r, eval=FALSE,engine='bash'}
69+
## Display all your conda environments
70+
conda info --envs
71+
```
72+
73+
If you don't have a conda environment called 'geoscripting', create it first.
74+
75+
```{r, eval=FALSE,engine='bash'}
76+
## Create conda environment called geoscripting
77+
conda create --name geoscripting python=3 numpy jupyter
78+
```
79+
80+
Then install todays modules in your conda environment and start your Jupyter Notebook.
81+
82+
```{r, eval=FALSE,engine='bash'}
83+
## Install gdal and folium
84+
conda install --name geoscripting --channel conda-forge gdal folium
85+
source activate geoscripting
86+
jupyter notebook
87+
```
88+
89+
Open a new Ipython Notebook in an appropriate location. Output of the Python scripts from Jupyter Notebook will be saved in the repository where the .ipynb is stored.
6190

62-
What does "WKT" mean?
91+
## Points
92+
Now we continue with the tutorial. Try the script below and find out what "WKT" means.
6393

6494
```{r, engine='python'}
6595
from osgeo import ogr
6696
# Create a point geometry
6797
wkt = "POINT (173914.00 441864.00)"
6898
pt = ogr.CreateGeometryFromWkt(wkt)
6999
print(pt)
70-
# print help(osgeo.ogr)
100+
# print(help(osgeo.ogr))
71101
```
72102

73103
WKT (Well Known Text) is a sort of markup language that describes spatial information in a clean text format, there is an equivalent in binary format (easier for computers to process and more efficient for data transfer).
@@ -104,9 +134,9 @@ target.ImportFromEPSG(28992)
104134
105135
# transform from lat/long to Dutch coord. system
106136
transform = osr.CoordinateTransformation(source, target)
107-
point = ogr.CreateGeometryFromWkt("POINT (5.6660 51.9872)")
137+
point = ogr.CreateGeometryFromWkt("POINT (5.6660 51.9872)") #ogr uses lon, lat
108138
point.Transform(transform)
109-
print point.ExportToWkt()
139+
print(point.ExportToWkt())
110140
```
111141

112142
Are you still keeping track of your data and coordinate system?
@@ -133,16 +163,7 @@ Driver
133163
Point
134164
```
135165

136-
Start a new Python script within the `Python` console of QGIS (recommended for today!). Open QGIS Desktop, go to plugins and start python console (or use short ctrl + alt + p).
137-
138-
You can set the working directory using:
139-
```{python, eval=FALSE}
140-
import os
141-
os.chdir('pathtoyourworkingdirectory')
142-
print os.getcwd()
143-
```
144-
145-
Now you can continue (you do not need to repeat the `import ` if you have already done so!):
166+
Now we know how a file is made, you can continue to make a file:
146167

147168
* Set spatial reference
148169
* Create shape file
@@ -153,18 +174,13 @@ Now you can continue (you do not need to repeat the `import ` if you have alread
153174
* Flush
154175

155176
```{r, engine = 'python', eval=FALSE}
156-
## Loading the modules
157-
#from osgeo import ogr,osr
158-
#import os
159-
#os.chdir('./data')
160-
161177
## Is the ESRI Shapefile driver available?
162178
driverName = "ESRI Shapefile"
163-
drv = ogr.GetDriverByName( driverName )
179+
drv = ogr.GetDriverByName(driverName)
164180
if drv is None:
165-
print "%s driver not available.\n" % driverName
181+
print("%s driver not available.\n" % driverName)
166182
else:
167-
print "%s driver IS available.\n" % driverName
183+
print("%s driver IS available.\n" % driverName)
168184
```
169185

170186
After loading modules and setting the correct driver, we can create a new data source for a shapefile. Have a look that the layer does not exist in your data folder.
@@ -176,7 +192,7 @@ layername = "anewlayer"
176192
177193
## Create shape file
178194
ds = drv.CreateDataSource(fn)
179-
print ds.GetRefCount()
195+
print(ds.GetRefCount())
180196
```
181197

182198
We created the datasource, but didn't make the file yet. Let's continue to add information to the shapefile. First add a coordinate reference system (CRS) or spatial reference.
@@ -239,8 +255,8 @@ Now that we created features with geometry, we can store the features in the lay
239255
layer.CreateFeature(feature1)
240256
layer.CreateFeature(feature2)
241257
242-
print "Extent of layer"
243-
print layer.GetExtent()
258+
print("Extent of layer")
259+
print(layer.GetExtent())
244260
```
245261

246262
It has an extent now and it might seem we are finished now. We created geometry, features and a layer and assigned the `Esri Shapefile` driver to the layer. However the file still has to be saved. OGR doesn't have a Save() option. The shapefile is updated with the object structure when the script finished or when it is destroyed, if necessary SyncToDisk() maybe used.
@@ -254,42 +270,23 @@ Okay nice. You created a shapefile in Python from scratch. This is just a start.
254270

255271
```{r, engine = 'python', eval=FALSE}
256272
## Export to other formats/representations:
257-
print "KML file export"
258-
print point2.ExportToKML()
273+
print("KML file export")
274+
print(point2.ExportToKML())
259275
```
260276

261277
Spatial operations are possible to. Buffer around the point and export the buffer to a GML file.
262278

263279
```{r, engine = 'python', eval=FALSE}
264280
## Buffering
265281
buffer = point2.Buffer(1,1)
266-
print buffer.Intersects(point1)
282+
print(buffer.Intersects(point1))
267283
268284
## More exports:
269285
buffer.ExportToGML()
270286
```
271287

272288
More spatial methods are available from the OGR module. If you are interested have a look at the methods section of this [tutorial](http://www2.geog.ucl.ac.uk/~plewis/geogg122/_build/html/Chapter4_GDAL/OGR_Python.html).
273289

274-
Let's open and visualize our files in QGIS. Files can even be opened from the `Python Console` in QGIS. Try the code below:
275-
276-
```{r, engine='python', eval=FALSE}
277-
## Add a vector layer to the QGIS interface
278-
qgis.utils.iface.addVectorLayer(fn, layername, "ogr")
279-
aLayer = qgis.utils.iface.activeLayer()
280-
print aLayer.name()
281-
```
282-
283-
The method `addVectorLayer` takes three arguments:
284-
285-
* the first argument is the path to the data source – the shapefile in our case
286-
* the second argument is the basename – the name that the layer takes in the table of contents
287-
* the third argument is the provider key. Basically, the function wants to know what driver will be used to read this data.
288-
289-
Another example of how we can use the add vector layer method:
290-
291-
`qgis.utils.iface.addVectorLayer('/home/user/Git/Python/data/points.shp', 'anewlayer', "ogr")`
292-
293290
For our purposes, “ogr” will be used most of the time with vector data. Other popular drivers besides ogr are postgres (for PostgreSQL databases), KML, GML, Esri Shapefile or GeoJSON. [The python qgis cookbook](http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadlayer.html) gives more information on the use of the method and available drivers.
294291

295292
## Modify a shape file
@@ -302,21 +299,21 @@ ds = drv.Open(fn, 1)
302299
303300
## Check layers and get the first layer
304301
layernr = ds.GetLayerCount()
305-
print layernr
302+
print(layernr)
306303
layer = ds.GetLayerByIndex(0)
307-
print layer
304+
print(layer)
308305
309306
## Get number of features in shapefile layer
310307
features_number = layer.GetFeatureCount()
311-
print "number of features for this layer:", features_number
308+
print("number of features for this layer:", features_number)
312309
313310
## Get the feature definition
314311
featureDefn = layer.GetLayerDefn()
315312
316313
## Create a new point
317314
point = ogr.Geometry(ogr.wkbPoint)
318315
point.SetPoint(0,5.6909725,50.8513682)
319-
print point
316+
print(point)
320317
## Similarly point.AddPoint(2,1)
321318
322319
## Create a new feature
@@ -361,10 +358,6 @@ map_osm.save('osm.html')
361358
<p>&nbsp;</p>
362359
<div class="img-responsive center-block" align="center"><iframe src="osm.html" width="500" height="300" style="border: 0"></iframe></div>
363360
<p>&nbsp;</p>
364-
```{r, eval = FALSE}
365-
getwd()
366-
list.files()
367-
```
368361

369362
```{r, engine='python', eval = FALSE}
370363
import folium
@@ -381,11 +374,11 @@ map_points.save('points.html')
381374
<p>&nbsp;</p>
382375

383376
Webtutorial about folium: [web-mapping-with-python-and-folium](http://pythonhow.com/web-mapping-with-python-and-folium)
384-
377+
and [latest webmapping with folium](http://folium.readthedocs.io/en/latest/quickstart.html).
378+
379+
385380
## Clean up
386-
387381
From the terminal you can remove the created "points.shp" and related files using:
388-
389382
```{r, engine='bash', eval=FALSE}
390383
echo "in the terminal you can use the following bash commands to easily remove files"
391384
echo "list all the files starting with points*"
@@ -407,13 +400,13 @@ rm -v points*
407400

408401
# Assignment
409402

410-
Create your own shapefile of two point locations (e.g. a location of the GAIA building in Wageningen) in RD_New, buffer one point and make a webmap in Python. Make a well structured IPython Notebook.
403+
Create your own shapefile of two point locations (e.g. a location of the GAIA building in Wageningen) in RD_New, buffer two points and make a webmap in Python. Make a well structured IPython Notebook.
411404

412405
- Create two points with coordinates from [Google Maps](https://www.google.nl/maps/?hl=en) or use the two points from the [R vector tutorial](https://geoscripting-wur.github.io/IntroToVector/).
413406
- Set the projection (Lat/Long, you should know now the EPSG) and reproject to the Dutch projection RD_New
414-
- Create a buffer around the points of 100m
415-
- Export the two point to shape file (that can be imported in QGIS)
416-
- Make a webmap of your buffer with leaflet
407+
- Create a buffer around the two points of 100m
408+
- Export the two points to shape file (that can be imported in QGIS)
409+
- Make a webmap of your buffer with leaflet (Hint: your buffer is a polygon)
417410

418411
Bonus: print the distance between the two points (Hint: `Distance()`)
419412

0 commit comments

Comments
 (0)