forked from AdamWilsonLabEDU/SpatialDataScience
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_CreatingWorkflows.html
More file actions
1107 lines (1014 loc) · 37.5 KB
/
06_CreatingWorkflows.html
File metadata and controls
1107 lines (1014 loc) · 37.5 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<title>Creating Workflows</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cosmo.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/textmate.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-5.0.13/css/fa-svg-with-js.css" rel="stylesheet" />
<script src="site_libs/font-awesome-5.0.13/js/fontawesome-all.min.js"></script>
<script src="site_libs/font-awesome-5.0.13/js/fa-v4-shims.min.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 51px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 56px;
margin-top: -56px;
}
.section h2 {
padding-top: 56px;
margin-top: -56px;
}
.section h3 {
padding-top: 56px;
margin-top: -56px;
}
.section h4 {
padding-top: 56px;
margin-top: -56px;
}
.section h5 {
padding-top: 56px;
margin-top: -56px;
}
.section h6 {
padding-top: 56px;
margin-top: -56px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = true;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
padding-left: 25px;
text-indent: 0;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">GEO 503: Spatial Data Science</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="Syllabus.html">Syllabus</a>
</li>
<li>
<a href="Schedule.html">Schedule</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Content
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="CourseContent.html">About Course Content</a>
</li>
<li class="dropdown-header">Module 1: Introduction to R</li>
<li>
<a href="00_CourseIntroductionFrame.html">00 Course Introduction</a>
</li>
<li>
<a href="01_Rintro.html">01 First Steps</a>
</li>
<li>
<a href="02_graphics.html">02 Graphics</a>
</li>
<li>
<a href="03_DataWrangling.html">03 Data Wrangling</a>
</li>
<li>
<a href="03b_DataWrangling.html">03 Data Wrangling 2</a>
</li>
<li class="divider"></li>
<li class="dropdown-header">Module 2: Spatial Analyses</li>
<li>
<a href="04_Spatial_with_sf.html">04 Spatial Data with sf</a>
</li>
<li>
<a href="05_Raster.html">05 Spatial Raster Data</a>
</li>
<li class="divider"></li>
<li class="dropdown-header">Module 3: Advanced Programming</li>
<li>
<a href="06_CreatingWorkflows.html">06 Creating Workflows</a>
</li>
<li>
<a href="07_Reproducibile.html">07 Reproducible Research</a>
</li>
<li>
<a href="08_WeatherData.html">08 Weather Data Processing</a>
</li>
<li>
<a href="09_RemoteSensing_appeears.html">09 Satellite Data Processing</a>
</li>
<li>
<a href="11_ParallelProcessing.html">11 Parallel Processing</a>
</li>
<li>
<a href="12_DynamicVisualization.html">12 Dynamic Visualization</a>
</li>
<li>
<a href="13_SDM_Exercise.html">13 Species Distribution Modeling</a>
</li>
<li class="divider"></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Assignments
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="Tasklist.html">Task list</a>
</li>
<li>
<a href="DataCamp.html">DataCamp</a>
</li>
<li>
<a href="PackageIntro.html">Package Introduction</a>
</li>
<li>
<a href="Project.html">Final Project</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Resources
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="Provenance.html">Provenance</a>
</li>
<li>
<a href="Projects_2018.html">2018 Project Drafts</a>
</li>
<li>
<a href="Projects_2017.html">2017 Final Projects</a>
</li>
<li>
<a href="GitSSHNotes.html">Setting up Github</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/adammwilson/RDataScience">
<span class="fa fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Creating Workflows</h1>
</div>
<p><a href="scripts/06_CreatingWorkflows.R"><i class="fa fa-file-code-o fa-3x" aria-hidden="true"></i> The R Script associated with this page is available here</a>. Download this file and open it (or copy-paste into a new script) with RStudio so you can follow along.</p>
<div id="libraries" class="section level2">
<h2>Libraries</h2>
<pre class="r"><code>library(knitr)
library(dplyr)
library(tidyr)
library(ggplot2)
library(raster)
library(rasterVis)
library(scales)
library(rgeos)
# load data for this course
# devtools::install_github("adammwilson/DataScienceData")
library(DataScienceData)</code></pre>
</div>
<div id="todays-question" class="section level2">
<h2>Today’s question</h2>
<div id="how-will-future-projected-sea-level-rise-affect-bangladesh" class="section level3">
<h3>How will future (projected) sea level rise affect Bangladesh?</h3>
<ol style="list-style-type: decimal">
<li>How much area is likely to be flooded by rising sea level?</li>
<li>How many people are likely to be displaced?</li>
<li>Will sea level rise affect any major population centers?</li>
</ol>
</div>
</div>
<div id="bangladesh" class="section level2">
<h2>Bangladesh</h2>
<pre class="r"><code>getData("ISO3")%>%
as.data.frame%>%
filter(NAME=="Bangladesh")</code></pre>
<pre><code>## ISO3 NAME
## 1 BGD Bangladesh</code></pre>
<div id="download-bangladesh-border" class="section level3">
<h3>Download Bangladesh Border</h3>
<p>Often good idea to keep data in separate folder. You will need to edit this for your machine!</p>
<pre class="r"><code>datadir="~/Downloads/data"
if(!file.exists(datadir)) dir.create(datadir, recursive=T)</code></pre>
<p>Download country border.</p>
<pre class="r"><code>bgd=getData('GADM', country='BGD', level=0,path = datadir)</code></pre>
<p>Or load it from the data package.</p>
<pre class="r"><code>data(bangladesh)
bgd=bangladesh</code></pre>
<pre class="r"><code>bgd%>%
gSimplify(0.01)%>%
plot()</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-7-1.png" /><!-- --></p>
</div>
</div>
<div id="topography" class="section level2">
<h2>Topography</h2>
<p>SRTM Elevation data with <code>getData()</code> as 5deg tiles. If you have trouble downloading using <code>getData()</code>, skip to the <code>data(bangladesh_dem)</code> line below</p>
<pre class="r"><code>bgdc=gCentroid(bgd)%>%coordinates()
dem1=getData("SRTM",lat=bgdc[2],lon=bgdc[1],path=datadir)</code></pre>
<div id="mosaicingmerging-rasters" class="section level3">
<h3>Mosaicing/Merging rasters</h3>
<p>Download the remaining necessary tiles</p>
<pre class="r"><code>dem2=getData("SRTM",lat=23.7,lon=85,path=datadir)</code></pre>
<p>Use <code>merge()</code> to join two aligned rasters (origin, resolution, and projection). Or <code>mosaic()</code> combines with a function.</p>
<pre class="r"><code>dem=merge(dem1,dem2)</code></pre>
<p>Or, load it from the data package.</p>
<pre class="r"><code>data(bangladesh_dem)
dem=bangladesh_dem # rename for convenience</code></pre>
<pre class="r"><code>plot(dem)
bgd%>%
gSimplify(0.01)%>%
plot(add=T)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-12-1.png" /><!-- --></p>
</div>
</div>
<div id="savingexporting-rasters" class="section level2">
<h2>Saving/exporting rasters</h2>
<p>Beware of massive temporary files!</p>
<pre class="r"><code>inMemory(dem)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>dem@file@name</code></pre>
<pre><code>## [1] "/private/var/folders/fh/g_hk6yxx4cj5c83096lj3g4r0000gn/T/Rtmp9gEdq9/raster/r_tmp_2017-08-21_132716_46406_48324.grd"</code></pre>
<pre class="r"><code>file.size(sub("grd","gri",dem@file@name))*1e-6</code></pre>
<pre><code>## [1] NA</code></pre>
<pre class="r"><code>showTmpFiles()</code></pre>
<pre><code>## --- none ---</code></pre>
<pre class="r"><code>rasterOptions()</code></pre>
<pre><code>## format : raster
## datatype : FLT4S
## overwrite : FALSE
## progress : none
## timer : FALSE
## chunksize : 1e+07
## maxmemory : 1e+09
## tmpdir : /var/folders/fh/g_hk6yxx4cj5c83096lj3g4r0000gn/T//RtmphO758X/raster//
## tmptime : 168
## setfileext : TRUE
## tolerance : 0.1
## standardnames : TRUE
## warn depracat.: TRUE
## header : none</code></pre>
<p>Set with <code>rasterOptions(tmpdir = "/tmp")</code></p>
<p>Saving raster to file: <em>two options</em></p>
<p>Save while creating</p>
<pre class="r"><code>dem=merge(dem1,dem2,filename=file.path(datadir,"dem.tif"),overwrite=T)</code></pre>
<p>Or after</p>
<pre class="r"><code>writeRaster(dem, filename = file.path(datadir,"dem.tif"))</code></pre>
<div id="writeraster-formats" class="section level3">
<h3>WriteRaster formats</h3>
<table>
<thead>
<tr class="header">
<th>Filetype</th>
<th>Long name</th>
<th>Default extension</th>
<th>Multiband support</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>raster</td>
<td>‘Native’ raster package format</td>
<td>.grd</td>
<td>Yes</td>
</tr>
<tr class="even">
<td>ascii</td>
<td>ESRI Ascii</td>
<td>.asc</td>
<td>No</td>
</tr>
<tr class="odd">
<td>SAGA</td>
<td>SAGA GIS</td>
<td>.sdat</td>
<td>No</td>
</tr>
<tr class="even">
<td>IDRISI</td>
<td>IDRISI</td>
<td>.rst</td>
<td>No</td>
</tr>
<tr class="odd">
<td>CDF</td>
<td>netCDF (requires <code>ncdf</code>)</td>
<td>.nc</td>
<td>Yes</td>
</tr>
<tr class="even">
<td>GTiff</td>
<td>GeoTiff (requires rgdal)</td>
<td>.tif</td>
<td>Yes</td>
</tr>
<tr class="odd">
<td>ENVI</td>
<td>ENVI .hdr Labelled</td>
<td>.envi</td>
<td>Yes</td>
</tr>
<tr class="even">
<td>EHdr</td>
<td>ESRI .hdr Labelled</td>
<td>.bil</td>
<td>Yes</td>
</tr>
<tr class="odd">
<td>HFA</td>
<td>Erdas Imagine Images (.img)</td>
<td>.img</td>
<td>Yes</td>
</tr>
</tbody>
</table>
<p><code>rgdal</code> package does even more…</p>
</div>
<div id="crop-to-coastal-area-of-bangladesh" class="section level3">
<h3>Crop to Coastal area of Bangladesh</h3>
<pre class="r"><code># crop to a lat-lon box
dem=crop(dem,extent(90,91,21.5,24),filename=file.path(datadir,"dem_bgd.tif"),overwrite=T)
plot(dem)
bgd%>%
gSimplify(0.01)%>%
plot(add=T)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-17-1.png" /><!-- --></p>
</div>
</div>
<div id="use-ggplot" class="section level1">
<h1>Use ggplot</h1>
<pre class="r"><code>gplot(dem,max=1e5)+
geom_tile(aes(fill=value))+
scale_fill_gradientn(
colours=c("red","yellow","grey30","grey20","grey10"),
trans="log1p",breaks= log_breaks(n = 5, base = 10)(c(1, 1e3)))+
coord_equal(ylim=c(21.5,24),xlim=c(90,91))+
geom_path(data=fortify(bgd),
aes(x=long,y=lat,group=group),size=.5)</code></pre>
<pre><code>## Regions defined for each Polygons</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-18-1.png" /><!-- --></p>
</div>
<div id="terrain-analysis-an-aside" class="section level1">
<h1>Terrain analysis (an aside)</h1>
<div id="terrain-analysis-options" class="section level2">
<h2>Terrain analysis options</h2>
<p><code>terrain()</code> options:</p>
<ul>
<li>slope</li>
<li>aspect</li>
<li>TPI (Topographic Position Index)</li>
<li>TRI (Terrain Ruggedness Index)</li>
<li>roughness</li>
<li>flowdir</li>
</ul>
<p>Use an even smaller region:</p>
<pre class="r"><code>reg1=crop(dem,extent(90.6,90.7,23.25,23.4))
plot(reg1)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-19-1.png" /><!-- --></p>
<p>The terrain indices are according to Wilson et al. (2007), as in <a href="http://www.gdal.org/gdaldem.html">gdaldem</a>.</p>
<div id="calculate-slope" class="section level3">
<h3>Calculate slope</h3>
<pre class="r"><code>slope=terrain(reg1,opt="slope",unit="degrees")
plot(slope)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-20-1.png" /><!-- --></p>
</div>
<div id="calculate-aspect" class="section level3">
<h3>Calculate aspect</h3>
<pre class="r"><code>aspect=terrain(reg1,opt="aspect",unit="degrees")
plot(aspect)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-21-1.png" /><!-- --></p>
</div>
<div id="tpi-topographic-position-index" class="section level3">
<h3>TPI (Topographic Position Index)</h3>
<p>Difference between the value of a cell and the mean value of its 8 surrounding cells.</p>
<pre class="r"><code>tpi=terrain(reg1,opt="TPI")
gplot(tpi,max=1e6)+geom_tile(aes(fill=value))+
scale_fill_gradient2(low="blue",high="red",midpoint=0)+
coord_equal()</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-22-1.png" /><!-- --> Negative values indicate valleys, near zero flat or mid-slope, and positive ridge and hill tops</p>
<div class="well">
<h2 id="your-turn">Your turn</h2>
<ul>
<li>Identify all the pixels with a TPI less than -5 or greater than 5.</li>
<li>Use <code>plot()</code> to:
<ul>
<li>plot elevation for this region</li>
<li>overlay the valley pixels in blue</li>
<li>overlay the ridge pixels in red</li>
</ul></li>
</ul>
<p>Hint: use <code>transparent</code> to plot a transparent pixel and <code>add=T</code> to add a layer to an existing plot.</p>
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo1">
Show Solution
</button>
<div id="demo1" class="collapse">
<pre class="r"><code>plot(reg1)
plot(tpi>5,col=c("transparent","red"),add=T,legend=F)
plot(tpi<(-5),col=c("transparent","blue"),add=T,legend=F)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-23-1.png" /><!-- --></p>
<pre class="r"><code>#OR (ggplot solution, sort of)
rcl=matrix(c(-Inf,-5,1,
-5,5,2,
5,Inf,3),byrow=T,nrow=3)
regclass=reclassify(tpi,rcl)
gplot(regclass,max=1e6)+geom_tile(aes(fill=value))+
scale_fill_gradient2(low="blue",high="red",midpoint=2)+
coord_equal()</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-23-2.png" /><!-- --></p>
</div>
</div>
</div>
<div id="tri-terrain-ruggedness-index" class="section level3">
<h3>TRI (Terrain Ruggedness Index)</h3>
<p>Mean of the absolute differences between the value of a cell and the value of its 8 surrounding cells.</p>
<pre class="r"><code>tri=terrain(reg1,opt="TRI")
plot(tri)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-24-1.png" /><!-- --></p>
</div>
<div id="roughness" class="section level3">
<h3>Roughness</h3>
<p>Difference between the maximum and the minimum value of a cell and its 8 surrounding cells.</p>
<pre class="r"><code>rough=terrain(reg1,opt="roughness")
plot(rough)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-25-1.png" /><!-- --></p>
</div>
<div id="hillshade-pretty" class="section level3">
<h3>Hillshade (pretty…)</h3>
<p>Compute from slope and aspect (in radians). Often used as a backdrop for another semi-transparent layer.</p>
<pre class="r"><code>hs=hillShade(slope*pi/180,aspect*pi/180)
plot(hs, col=grey(0:100/100), legend=FALSE)
plot(reg1, col=terrain.colors(25, alpha=0.5), add=TRUE)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-26-1.png" /><!-- --></p>
</div>
<div id="flow-direction" class="section level3">
<h3>Flow Direction</h3>
<p><em>Flow direction</em> (of water), i.e. the direction of the greatest drop in elevation (or the smallest rise if all neighbors are higher).</p>
<p>Encoded as powers of 2 (0 to 7). The cell to the right of the focal cell ‘x’ is 1, the one below that is 2, and so on:</p>
<table>
<thead>
<tr class="header">
<th align="left">32</th>
<th align="left">64</th>
<th>128</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">16</td>
<td align="left"><strong>x</strong></td>
<td>1</td>
</tr>
<tr class="even">
<td align="left">8</td>
<td align="left">4</td>
<td>2</td>
</tr>
</tbody>
</table>
<pre class="r"><code>flowdir=terrain(reg1,opt="flowdir")
plot(flowdir)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-27-1.png" /><!-- --> Much more powerful hydrologic modeling in <a href="https://grass.osgeo.org">GRASS GIS</a></p>
</div>
</div>
</div>
<div id="sea-level-rise" class="section level1">
<h1>Sea Level Rise</h1>
<div id="global-slr-scenarios" class="section level2">
<h2>Global SLR Scenarios</h2>
<pre class="r"><code>slr=data.frame(year=2100,
scenario=c("RCP2.6","RCP4.5","RCP6.0","RCP8.5"),
low=c(0.26,0.32,0.33,0.53),
high=c(0.54,0.62,0.62,0.97))
slr</code></pre>
<pre><code>## year scenario low high
## 1 2100 RCP2.6 0.26 0.54
## 2 2100 RCP4.5 0.32 0.62
## 3 2100 RCP6.0 0.33 0.62
## 4 2100 RCP8.5 0.53 0.97</code></pre>
<p><a href="https://www.ipcc.ch/pdf/assessment-report/ar5/wg1/drafts/fgd/WGIAR5_WGI-12Doc2b_FinalDraft_Chapter13.pdf">IPCC AR5 WG1 Section 13-4</a></p>
</div>
<div id="storm-surges" class="section level2">
<h2>Storm Surges</h2>
<p>Range from 2.5-10m in Bangladesh since 1960 <a href="http://www.sciencedirect.com/science/article/pii/S0959378008000447">Karim & Mimura, 2008</a>.</p>
<pre class="r"><code>ss=c(2.5,10)</code></pre>
</div>
<div id="raster-area" class="section level2">
<h2>Raster area</h2>
<p>1st Question: How much area is likely to be flooded by rising sea levels?</p>
<p>WGS84 data is unprojected, must account for cell area (in km^2)…</p>
<pre class="r"><code>area=raster::area(dem)
plot(area)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-30-1.png" /><!-- --></p>
<div class="well">
<h2 id="your-turn-1">Your Turn</h2>
<ol style="list-style-type: decimal">
<li>How much area is likely to be flooded by rising sea levels for two scenarios:
<ul>
<li>0.26m SLR and 2.5m surge (2.76 total) - call this <code>flood1</code></li>
<li>0.97 SLR and 10m surge (10.97 total) - call this <code>flood2</code></li>
</ul></li>
</ol>
<p>Steps:</p>
<ul>
<li>Identify which pixels are below thresholds</li>
<li>Multiply by cell area</li>
<li>Use <code>cellStats()</code> to calculate potentially flooded areas.</li>
</ul>
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo2">
Show Solution
</button>
<div id="demo2" class="collapse">
<h2 id="identify-pixels-below-thresholds">Identify pixels below thresholds</h2>
<pre class="r"><code>flood1=dem<=2.76
flood2=dem<=10.97
plot(flood2,col=c("transparent","darkred"))
plot(flood1,col=c("transparent","red"),add=T)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-31-1.png" /><!-- --></p>
<h2 id="multiply-by-area-and-sum">Multiply by area and sum</h2>
<pre class="r"><code>flood1_area=flood1*area
flood2_area=flood2*area
cellStats(flood1_area,sum)</code></pre>
<pre><code>## [1] 1569.09</code></pre>
<pre class="r"><code>cellStats(flood2_area,sum)</code></pre>
<pre><code>## [1] 18250.66</code></pre>
</div>
</div>
</div>
<div id="reclassification" class="section level2">
<h2>Reclassification</h2>
<p>Another useful function for raster processing is <code>reclass()</code>.</p>
<pre class="r"><code>rcl=matrix(c(-Inf,2.76,1,
2.76,10.97,2,
10.97,Inf,3),byrow=T,ncol=3)
rcl</code></pre>
<pre><code>## [,1] [,2] [,3]
## [1,] -Inf 2.76 1
## [2,] 2.76 10.97 2
## [3,] 10.97 Inf 3</code></pre>
<pre class="r"><code>regclass=reclassify(dem,rcl)
gplot(regclass,max=1e5)+
geom_tile(aes(fill=as.factor(value)))+
scale_fill_manual(values=c("red","orange","blue"),
name="Flood Class")+
coord_equal()</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-33-1.png" /><!-- --></p>
<p>Or, do reclassification ’on the fly in the plotting function</p>
<pre class="r"><code>gplot(dem,max=1e5)+
geom_tile(aes(fill=cut(value,c(-Inf,2.76,10.97,Inf))))+
scale_fill_manual(values=c("red","orange","blue"),
name="Flood Class")+
coord_equal()</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-34-1.png" /><!-- --></p>
</div>
<div id="socioeconomic-data" class="section level2">
<h2>Socioeconomic Data</h2>
<p>Socioeconomic Data and Applications Center (SEDAC) <a href="http://sedac.ciesin.columbia.edu" class="uri">http://sedac.ciesin.columbia.edu</a> <img src="06_assets/sedac.png" alt="alt text" width="70%"></p>
<ul>
<li>Population</li>
<li>Pollution</li>
<li>Energy</li>
<li>Agriculture</li>
<li>Roads</li>
</ul>
<div id="gridded-population-of-the-world" class="section level3">
<h3>Gridded Population of the World</h3>
<p>Data <em>not</em> available for direct download (e.g. <code>download.file()</code>) and are only available globally.</p>
<p><img src="06_assets/sedacData.png" alt="alt text" width="80%"></p>
<p>The steps to aquire the full dataset are as follows:</p>
<ul>
<li>Log into SEDAC with an Earth Data Account <a href="http://sedac.ciesin.columbia.edu" class="uri">http://sedac.ciesin.columbia.edu</a></li>
<li>Download Population Density Grid for 2015</li>
<li>Crop and mask to the country boundary for Bangladesh</li>
</ul>
<p>The masked data are available in the DataScienceData package in the <code>bangladesh_pop</code> dataset.</p>
</div>
<div id="load-population-data" class="section level3">
<h3>Load population data</h3>
<p>Use <code>raster()</code> to load a raster from disk.</p>
<pre class="r"><code>pop_global=raster(file.path(datadir,"gpw-v4-population-density-2015/gpw-v4-population-density_2015.tif"))</code></pre>
<pre class="r"><code>data(bangladesh_population)</code></pre>
<p>If the data package isn’t working, download directly from github.</p>
<pre class="r"><code>tf=tempfile()
download.file("https://github.com/adammwilson/DataScienceData/raw/master/data/bangladesh_population.rda",destfile = tf)
load(tf)</code></pre>
<pre class="r"><code>## make a virtual copy with a shorter name for convenience
pop=bangladesh_population</code></pre>
</div>
<div id="explore-population-data" class="section level3">
<h3>Explore population data</h3>
<pre class="r"><code>gplot(pop,max=1e5)+geom_tile(aes(fill=value))+
scale_fill_gradientn(colours=c("grey90","grey60","darkblue","blue","red"),
trans="log1p",breaks= log_breaks(n = 5, base = 10)(c(1, 1e5)))+
coord_equal()</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-39-1.png" /><!-- --></p>
</div>
<div id="resample-to-dem" class="section level3">
<h3>Resample to DEM</h3>
<p>Compare the resolution and origin of <code>pop</code> and <code>dem</code>.</p>
<pre class="r"><code>pop</code></pre>
<pre><code>## class : RasterLayer
## dimensions : 707, 560, 395920 (nrow, ncol, ncell)
## resolution : 0.008333333, 0.008333333 (x, y)
## extent : 88.00833, 92.675, 20.74167, 26.63333 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
## data source : in memory
## names : gpw.v4.population.density_2015
## values : 19.83075, 154258.4 (min, max)</code></pre>
<pre class="r"><code>dem</code></pre>
<pre><code>## class : RasterLayer
## dimensions : 3000, 1200, 3600000 (nrow, ncol, ncell)
## resolution : 0.0008333333, 0.0008333333 (x, y)
## extent : 89.99958, 90.99958, 21.49958, 23.99958 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
## data source : /Users/adamw/Downloads/data/dem_bgd.tif
## names : dem_bgd
## values : -27, 37 (min, max)</code></pre>
<pre class="r"><code>res(pop)</code></pre>
<pre><code>## [1] 0.008333333 0.008333333</code></pre>
<pre class="r"><code>res(dem)</code></pre>
<pre><code>## [1] 0.0008333333 0.0008333333</code></pre>
<pre class="r"><code>origin(pop)</code></pre>
<pre><code>## [1] -6.536993e-13 2.629008e-13</code></pre>
<pre class="r"><code>origin(dem)</code></pre>
<pre><code>## [1] -0.000416061 -0.000416207</code></pre>
<pre class="r"><code># Look at average cell area in km^2
cellStats(raster::area(pop),"mean")</code></pre>
<pre><code>## [1] 0.7828593</code></pre>
<pre class="r"><code>cellStats(raster::area(dem),"mean")</code></pre>
<pre><code>## [1] 0.007886292</code></pre>
<p>So to work with these rasters (population and elevation), it is easiest to “adjust” them to have the same resolution. But there is no good way to do this. Do you aggregate the finer raster or resample the coarser one?</p>
<p>Assume equal density within each grid cell and resample</p>
<pre class="r"><code>pop_fine=pop%>%
resample(dem,method="bilinear")
gplot(pop_fine,max=1e5)+geom_tile(aes(fill=value))+
scale_fill_gradientn(
colours=c("grey90","grey60","darkblue","blue","red"),
trans="log1p",breaks= log_breaks(n = 5, base = 10)(c(1, 1e5)))+
coord_equal()</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-41-1.png" /><!-- --></p>
<div class="well">
<h2 id="your-turn-2">Your turn</h2>
<p>How many people are likely to be displaced?</p>
<p>Steps:</p>
<ul>
<li>Multiply flooded area (<code>flood2</code>) <strong>x</strong> population density <strong>x</strong> area</li>
<li>Summarize with <code>cellStats()</code></li>
<li>Plot a map of the number of people potentially affected by <code>flood2</code></li>
</ul>
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo3">
Show Solution
</button>
<div id="demo3" class="collapse">
<p>For the fine resolution population data</p>
<pre class="r"><code>floodpop2=flood2_area*pop_fine
cellStats(floodpop2,sum)</code></pre>
<pre><code>## [1] 29796929</code></pre>
<p>Number of potentially affected people across the region.</p>
<pre class="r"><code>gplot(floodpop2,max=1e6)+geom_tile(aes(fill=value))+
scale_fill_gradientn(
colours=c("grey90","grey60","darkblue","blue","red"),
trans="log1p",breaks= log_breaks(n = 5, base = 10)(c(1, 1e4)))+
coord_equal()</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-43-1.png" /><!-- --></p>
</div>
</div>
<p>Or resample elevation to resolution of population: 1. First aggregate to approximate spatial resolution 2. Resample to align grids perfectly</p>
<pre class="r"><code>res(pop)/res(dem)</code></pre>
<pre><code>## [1] 10 10</code></pre>
<pre class="r"><code>dem_coarse=dem%>%
aggregate(fact=10,fun=min,expand=T)%>%
resample(pop,method="bilinear")</code></pre>
<p>For the coarse resolution data</p>
<pre class="r"><code>flood_coarse=dem_coarse<=10.97
dem_coarse_area=raster::area(dem_coarse)
flood_coarse_area=flood_coarse*dem_coarse_area
floodpop_coarse=flood_coarse_area*pop
cellStats(floodpop_coarse,sum)</code></pre>
<pre><code>## [1] 40077457</code></pre>
</div>
</div>
<div id="raster-distances" class="section level2">
<h2>Raster Distances</h2>
<p><code>distance()</code> calculates distances for all cells that are NA to the nearest cell that is not NA.</p>
<pre class="r"><code>popcenter=pop>5000
popcenter=mask(popcenter,popcenter,maskvalue=0)
plot(popcenter,col="red",legend=F)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-46-1.png" /><!-- --></p>
<p>In meters if the RasterLayer is not projected (<code>+proj=longlat</code>) and in map units (typically also meters) when it is projected.</p>
<pre class="r"><code>popcenterdist=distance(popcenter)
plot(popcenterdist)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-47-1.png" /><!-- --></p>
<div class="well">
<h2 id="your-turn-3">Your Turn</h2>
<p>Will sea level rise affect any major population centers?</p>
<p>Steps:</p>
<ul>
<li>Resample <code>popcenter</code> to resolution of <code>dem</code> using <code>method=ngb</code></li>
<li>Identify <code>popcenter</code> areas that flood according to <code>flood2</code>.</li>
</ul>
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo4">
Show Solution
</button>
<div id="demo4" class="collapse">
<p>Will sea level rise affect any major population centers?</p>
<pre class="r"><code>popcenter2=raster::resample(popcenter,dem,method="ngb")
floodpop2= flood2==1 & popcenter2
floodpop2=mask(floodpop2,floodpop2,maskval=0)
plot(flood2);plot(floodpop2,add=T,col="red",legend=F);
bgd%>%
gSimplify(0.01)%>%
plot(add=T)</code></pre>
<p><img src="06_CreatingWorkflows_files/figure-html/unnamed-chunk-48-1.png" /><!-- --></p>
</div>
</div>
</div>