-
Notifications
You must be signed in to change notification settings - Fork 4
/
presentation.Rmd
1445 lines (1064 loc) · 41.6 KB
/
presentation.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
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
---
title: "Analyzing space-time satellite data for disease ecology applications with GRASS GIS and R"
subtitle: "OpenGeoHub Summer School 2021"
author:
- "Veronica Andreo"
date: '`r Sys.Date()`'
output:
xaringan::moon_reader:
css: assets/css/xaringan-themer.css
seal: false
nature:
slideNumberFormat: "%current%"
highlightStyle: dark
highlightLines: true
ratio: 16:9
countIncrementalSlides: true
---
```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
knitr::opts_chunk$set(
fig.width=9, fig.height=6, fig.retina=3,
out.width = "80%",
cache = FALSE,
echo = TRUE,
message = FALSE,
warning = FALSE,
hiline = TRUE
)
```
```{r libraries, include=FALSE}
library(fontawesome)
library(emo)
```
```{r xaringanExtra, echo=FALSE}
# https://github.com/gadenbuie/xaringanExtra
xaringanExtra::use_xaringan_extra("tile_view")
xaringanExtra::use_panelset()
xaringanExtra::use_logo(image_url = "https://grass.osgeo.org/images/logos/grasslogo.svg",
width = "40px")
xaringanExtra::use_fit_screen()
xaringanExtra::use_progress_bar(color = "#ee4912", location = "bottom", height = "3px")
```
<br><br><br>
.center[
#### Slides:
https://veroandreo.github.io/grass_opengeohub2021/presentation.html
<br><br>
#### Repo:
[`r fa("github", width="3em")`](https://github.com/veroandreo/grass_opengeohub2021)
]
---
class: grass-slide, hide_logo, center
## Analyzing space-time satellite data for disease ecology applications with GRASS GIS and R
#### Verónica Andreo
.message-box-white[
<br>
<img src="assets/img/banner_conicet_conae_letrasnegras.png" width="65%">
OpenGeoHub Summer School - September, 2021]
---
layout: false
## About me
.pull-left-wide[
- PhD in Biology and MSc in Remote Sensing and GIS
- Researcher and lecturer at [Gulich Institute](https://ig.conae.unc.edu.ar/) from the [Argentinean Space Agency - CONAE](https://www.argentina.gob.ar/ciencia/conae), working on applications of RS & GIS for disease ecology
- [GRASS GIS](https://grass.osgeo.org/) dev team and PSC Chair
- [OSGeo](https://www.osgeo.org/) Charter member
- [FOSS4G](https://2021.foss4g.org/) enthusiast and advocate]
.pull-right-narrow[
.bio-img[![Vero profile pic](assets/img/vero_round_small.png)]
https://veroandreo.gitlab.io/
]
---
class: grass-slide
## How is this session organized?
.large[
- GRASS GIS basic intro
- Temporal GRASS GIS basic intro
- Demo session
]
---
## What GRASS?
.pull-left-wide[
- **GRASS GIS** (Geographic Resources Analysis Support System), a FOSS suite used for geospatial data management and analysis, image processing, graphics and maps, spatial modeling, and visualization.
- Originally developed by the U.S. Army Construction Engineering Research Laboratories for land management and environmental planning (1982-1995).
- More history: https://grass.osgeo.org/about/history/]
.pull-right-narrow[
![GRASS 38 bday](assets/img/grass_38_bday.png)]
---
class: grass-slide center
A bit of (geek) GRASS GIS history...
<iframe width="560" height="315" scrolling="no" src="//av.tib.eu/player/12963" frameborder="0" allowfullscreen></iframe>
<br>
.message-box-white[
In case you didn't notice, the video is narrated by William Shatner `r emo::ji("nerd")` `r emo::ji("rocket")`
]
---
class: grass-slide
## GRASS GIS general stuff
- Free and open source, you can use, modify, improve, share
- Strong user community, commercial support
- Large amount of tools: 500+ [core modules](#modules), 300+ [addons](#addons)
- GUI and CLI interfaces
- Python API and libraries - new `grass.jupyter` library can be tried [online](https://mybinder.org/v2/gh/OSGeo/grass/c173461?urlpath=lab%2Ftree%2Fdoc%2Fnotebooks%2Fgrass_jupyter.ipynb)
- Connection with R, QGIS, WPS, etc.
- Different data types supported: [raster](https://grass.osgeo.org/grass-stable/manuals/rasterintro.html) (including [satellite imagery](https://grass.osgeo.org/grass-stable/manuals/imageryintro.html)), [3D raster or voxel](https://grass.osgeo.org/grass-stable/manuals/raster3dintro.html), [vector](https://grass.osgeo.org/grass-stable/manuals/vectorintro.html) and [space-time datasets](https://grass.osgeo.org/grass-stable/manuals/temporalintro.html)
---
name: modules
### `r fa("tools")` More than [500 core modules](https://grass.osgeo.org/grass-stable/manuals/full_index.html) `r fa("tools")`
| Prefix | Function class | Type of command | Example
|--------------------------------------------------------------------- |:---------------- |:----------------------------------- |:-------------------------------------------------------------------------------------------------------------------
| [g.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#g) | general | general data management | [g.rename](https://grass.osgeo.org/grass-stable/manuals/g.rename.html): renames map
| [d.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#d) | display | graphical output | [d.rast](https://grass.osgeo.org/grass-stable/manuals/d.rast.html): display raster map
| [r.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#r) | raster | raster processing | [r.mapcalc](https://grass.osgeo.org/grass-stable/manuals/r.mapcalc.html): map algebra
| [v.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#r) | vector | vector processing | [v.clean](https://grass.osgeo.org/grass-stable/manuals/v.clean.html): topological cleaning
| [i.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#i) | imagery | imagery processing | [i.pca](https://grass.osgeo.org/grass-stable/manuals/i.pca.html): Principal Component Analysis
| [r3.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#r3) | voxel | 3D raster processing | [r3.stats](https://grass.osgeo.org/grass-stable/manuals/r3.stats.html): voxel statistics
| [db.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#db) | database | database management | [db.select](https://grass.osgeo.org/grass-stable/manuals/db.select.html): select value(s) from table
| [ps.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#ps) | postscript | PostScript map creation | [ps.map](https://grass.osgeo.org/grass-stable/manuals/ps.map.html): PostScript map creation
| [t.\*](https://grass.osgeo.org/grass-stable/manuals/full_index.html#t) | temporal | space-time datasets | [t.rast.aggregate](https://grass.osgeo.org/grass-stable/manuals/t.rast.aggregate.html): raster time series aggregation
---
class: grass-slide
name: addons
## `r fa("tools")` More than [300 add-ons](https://grass.osgeo.org/grass-stable/manuals/addons/) `r fa("tools")`
Plugins or **Add-ons** can be installed from
a centralized [OSGeo repository](https://grass.osgeo.org/grass-stable/manuals/addons/)
or from github (or similar repositories) using
[g.extension](https://grass.osgeo.org/grass-stable/manuals/g.extension.html) command.
```bash
# install extension from GRASS GIS Add-on repository
g.extension extension=r.hants
# install extension from github repository
g.extension extension=r3.slice \
url=https://github.com/petrasovaa/r3.slice
```
---
### Graphical User Interface (GUI)
<center><img src="assets/img/GUI_description.png" width="870px"></center>
---
### `r fa("terminal")` Command line
<center><img src="assets/img/grass_command_line.png" width="65%"></center>
---
### GRASS + `r fa("r-project", fill="#276dc2")` through rgrass7 package
We can use [R within a GRASS GIS session](https://grasswiki.osgeo.org/wiki/R_statistics/rgrass7#R_within_GRASS) or use [GRASS GIS within an R session](https://grasswiki.osgeo.org/wiki/R_statistics/rgrass7#GRASS_within_R)
<center><img src="assets/img/RwithinGRASS_and_Rstudio_from_grass.png" width="75%"></center>
---
class: grass-slide center
# Temporal support in GRASS GIS: .black[TGRASS]
---
## The TGRASS framework
.left[GRASS GIS was the first FOSS GIS that incorporated capabilities to *manage, analyze, process and visualize spatio-temporal data*, as well as the temporal relationships among time series.]
- TGRASS is fully **based on metadata** and does not duplicate any dataset
- **Snapshot** approach, i.e., adds time stamps to maps
- A collection of time stamped maps (snapshots) of the same variable are called **space-time datasets** or STDS
- Maps in a STDS can have different spatial and temporal extents
---
class: grass-slide
## Space-time datasets
- Space time raster datasets (**STRDS**)
- Space time 3D raster datasets (**STR3DS**)
- Space time vector datasets (**STVDS**)
<br>
> `r emo::ji("announcement")` Upcoming GRASS 8 will support image collections by adding a band reference
---
class: grass-slide
.pull-right-narrow[
<img src="assets/img/temporal_modules.png" width="110%" align="center">
]
## Temporal modules
.pull-left-wide[
- **t.\***: General modules to handle STDS of all types
- **t.rast.\***: Modules that deal with STRDS
- **t.rast3d.\***: Modules that deal with STR3DS
- **t.vect.\***: Modules that deal with STVDS
]
---
layout: true
### Other TGRASS notions
---
.pull-left[
- Time can be defined as **intervals** (start and end time) or **instances** (only start time)
- Time can be **absolute** (e.g., 2017-04-06 22:39:49) or **relative** (e.g., 4 years, 90 days)
- **Granularity** is the greatest common divisor of the temporal extents (and possible gaps) of all maps in the space-time cube
]
.pull-right[
<img src="https://grass.osgeo.org/grass78/manuals/timeline_2D.jpg">
]
---
- **Topology** refers to temporal relations between time intervals in a STDS.
.center[<img src="assets/img/temp_relation.png">]
---
layout: false
.left-column[
### TGRASS:
#### framework and workflow]
.right-column[<img src="assets/img/tgrass_flowchart.png" width="91%">]
---
class: grass-slide center hide_logo
## .black[Walk through space-time analysis for disease ecology with GRASS GIS and] `r fa("r-project", fill="#276dc2", width = "2em")`
---
class: grass-slide
### Demo session overview
> .center[Habitat suitability mapping for the Asian tiger mosquito in Northern Italy based on variables derived from daily LST data]
.pull-left[
- **GRASS**
- Import species records
- Create random background points
- Create different environmental layers from daily LST data
]
.pull-right[
- **R**
- Read data from GRASS into R
- Model species distribution
- Model evaluation
- Visualization of results
]
---
.footnote[Jarnevich et al. 2015. doi:[10.1016/j.ecoinf.2015.06.007](https://doi.org/10.1016/j.ecoinf.2015.06.007)]
.center[<img src="assets/img/sdm_workflow_edited.png" width="72%">]
---
### Data for the session
.pull-left[
- Records of *Aedes albopictus* (Asian tiger mosquito) in Northern Italy downloaded from [GBIF](https://www.gbif.org/)
- Daily MODIS LST reconstructed by [mundialis](https://www.mundialis.de/en/) based on [Metz et al. 2017](https://www.mdpi.com/2072-4292/9/12/1333/htm)
- 1 km spatial resolution
- Converted to Celsius degrees
]
.pull-right[
<img src="assets/img/aedes_albopictus.jpg" width="47%" align="right">
<br>
<img src="assets/img/lst_north_italy_2014.png" width="78%" align="left">
]
---
### `r fa("download")` Get sample location, mosquito records and code `r fa("download")`
- Create a folder named `grassdata_ogh`
- Download and unzip [eu_laea location with LST mapset](https://drive.google.com/file/d/1z1b2NLC4Z6yzz_57RddTdRRK_gUkd7fU/view?usp=sharing) and unzip within your `grassdata_ogh` folder
- Download the asian tiger [mosquito occurrences](https://github.com/veroandreo/grass_opengeohub2021/raw/master/data/aedes_albopictus.gpkg) as `.gpkg` file
- Download the [GRASS script](https://github.com/veroandreo/grass_opengeohub2021/raw/master/code/grass_R_disease_ecology_code.sh)
- Download the [R script](https://github.com/veroandreo/grass_opengeohub2021/raw/master/code/grass_R_disease_ecology_code.r)
The `grassdata_ogh` folder's tree should look like this:
```
grassdata_ogh/
└── eu_laea
├── italy_LST_daily
└── PERMANENT
```
---
.left-column[
## Let's start GRASS GIS!
`r emo::ji("hushed")`
### Fear not!
]
.right-column[
.center[<img src="assets/img/start_grass.png" width="60%">
`r emo::ji("announcement")` This start-up screen will be gone in GRASS 8 !!
]
]
---
## What was that? <a href="https://grass.osgeo.org/grass76/manuals/grass_database.html">GRASS database</a>
.pull-left[
- The **GRASS DATABASE** (or "GISDBASE") is an existing directory containing all GRASS GIS LOCATIONs.
- A **LOCATION** is defined by its coordinate system and geographical boundaries.
- **MAPSET** is a subdirectory within Locations. In a **MAPSET** you can organize GIS maps thematically, geographically, by project, etc.
- When GRASS GIS starts, it connects to `Database/Location/Mapset`:
]
.pull-right[
<img src="assets/img/grass_database.png" width="950px">
.right[More info at [grass database](#grass-database-slide)]
]
---
class: grass-slide center
# Now we are ready to start
# `r emo::ji("runner")`
---
#### Importing species records
.panelset[
.panel[.panel-name[GRASS code]
```bash
# Import records
v.import input=aedes_albopictus.gpkg output=aedes_albopictus
# List raster maps
g.list type=raster
r.colors map=lst_2014.150_avg color=celsius
# Display records
d.mon wx0
d.rast lst_2014.150_avg
d.vect aedes_albopictus icon=basic/circle \
size=7 fill_color=black
```
]
.panel[.panel-name[Map]
.center[<img src="assets/img/wx0_aedes_lst.png" width="570px">]
]
]
.footnote[You can also get the occurrences directly from GBIF into GRASS. See this [extra slide](#gbif-example).]
---
#### Creating random background points
.panelset[
.panel[.panel-name[GRASS code]
```bash
# Create buffer around Aedes albopictus records
v.buffer input=aedes_albopictus output=aedes_buffer distance=2000
# Set computational region
g.region -p raster=lst_2014.001_avg
# Create a vector mask to limit background points
r.mapcalc expression="MASK = if(lst_2014.001_avg, 1, null())"
r.to.vect input=MASK output=vect_mask type=area
# Subtract buffers from vector mask
v.overlay ainput=vect_mask binput=aedes_buffer operator=xor output=mask_bg
# Generate random background points
v.random output=background_points npoints=1000 restrict=mask_bg seed=3749
```
]
.panel[.panel-name[Map]
.center[<img src="assets/img/points_aedes_background.png" width="600px">]
]
]
.footnote[See extra slides for details about [*computational region*](#region) and [*masks*](#mask) in GRASS GIS.]
---
#### Create daily LST STRDS
.panelset[
.panel[.panel-name[GRASS code]
```bash
# Create time series
t.create type=strds temporaltype=absolute \
output=lst_daily title="Average Daily LST" \
description="Average daily LST in degree C - 2014-2018"
# Get list of maps
g.list type=raster pattern="lst_201*" output=list_lst.csv
# Register maps in strds
t.register -i input=lst_daily file=list_lst.csv \
increment="1 days" start="2014-01-01"
# Get info about the strds
t.info input=lst_daily
```
]
.panel[.panel-name[Output]
.center[<img src="assets/img/t_info_output.png" width="50%">]
]
]
.footnote[See [t.create](https://grass.osgeo.org/grass-stable/manuals/t.create.html) & [t.register](https://grass.osgeo.org/grass-stable/manuals/t.register.html)]
---
### Generate environmental variables from LST STRDS
#### Long term monthly avg, min and max LST
.panelset[
.panel[.panel-name[GRASS code]
```bash
for i in $(seq -w 1 12) ; do
t.rast.series input=lst_daily method=average \
where="strftime('%m', start_time)='${i}'" \
output=lst_average_${i}
t.rast.series input=lst_daily method=minimum \
where="strftime('%m', start_time)='${i}'" \
output=lst_minimum_${i}
t.rast.series input=lst_daily method=maximum \
where="strftime('%m', start_time)='${i}'" \
output=lst_maximum_${i}
done
```
]
.panel[.panel-name[Windows cmd]
```vbscript
FOR %i IN (01,02,03,04,05,06,07,08,09,10,11,12) DO (
t.rast.series input=lst_daily method=average where="strftime('%m', start_time)='%i'" output=lst_average_%i
t.rast.series input=lst_daily method=minimum where="strftime('%m', start_time)='%i'" output=lst_minimum_%i
t.rast.series input=lst_daily method=maximum where="strftime('%m', start_time)='%i'" output=lst_maximum_%i
)
```
]
.panel[.panel-name[Output]
.center[<img src="assets/img/list_long_term_avg_lst.png" width="70%">]
]
]
.footnote[See [t.rast.series](https://grass.osgeo.org/grass-stable/manuals/t.rast.series.html) manual for further details]
---
#### Bioclimatic variables
.panelset[
.panel[.panel-name[GRASS code]
```bash
# Install extension
g.extension extension=r.bioclim
# Estimate temperature related bioclimatic variables
r.bioclim \
tmin=$(g.list type=raster pattern="lst_minimum_??" separator=",") \
tmax=$(g.list type=raster pattern="lst_maximum_??" separator=",") \
tavg=$(g.list type=raster pattern="lst_average_??" separator=",") \
output=worldclim_
# List output maps
g.list type=raster pattern="worldclim*"
```
]
.panel[.panel-name[Output]
.center[<img src="assets/img/list_worldclim_lst.png" width="80%">]
]
.panel[.panel-name[Map]
.center[<img src="assets/img/bio1.png" width="50%">]
]
]
.footnote[See [r.bioclim](https://grass.osgeo.org/grass-stable/manuals/addons/r.bioclim.html) manual for further details]
---
#### Spring warming
.panelset[
.panel[.panel-name[GRASS code]
```bash
# Annual spring warming: slope(daily Tmean february-march-april)
t.rast.aggregate input=lst_daily output=annual_spring_warming \
basename=spring_warming suffix=gran \
method=slope granularity="1 years" \
where="strftime('%m',start_time)='02' or \
strftime('%m',start_time)='03' or \
strftime('%m', start_time)='04'"
# Average spring warming
t.rast.series input=annual_spring_warming \
output=avg_spring_warming \
method=average
```
]
.panel[.panel-name[Map]
.center[<img src="assets/img/spring_warming.png" width="50%">]
]
]
.footnote[See [t.rast.aggregate](https://grass.osgeo.org/grass-stable/manuals/t.rast.aggregate.html) manual]
---
#### Autumnal cooling
.panelset[
.panel[.panel-name[GRASS code]
```bash
# Annual autumnal cooling: slope(daily Tmean august-september-october)
t.rast.aggregate input=lst_daily output=annual_autumnal_cooling \
basename=autumnal_cooling suffix=gran \
method=slope granularity="1 years" \
where="strftime('%m',start_time)='08' or \
strftime('%m',start_time)='09' or \
strftime('%m', start_time)='10'"
# Average autumnal cooling
t.rast.series input=annual_autumnal_cooling \
output=avg_autumnal_cooling \
method=average
```
]
.panel[.panel-name[Map]
.center[<img src="assets/img/autumnal_cooling.png" width="51%">]
]
]
---
#### Number of days with LSTmean >= 20 and <= 30
.panelset[
.panel[.panel-name[GRASS code]
```bash
# Keep only pixels meeting the condition
t.rast.algebra -n \
expression="tmean_higher20_lower30 = if(lst_daily >= 20.0 && lst_daily <= 30.0, 1, null())" \
basename=tmean_higher20_lower30 suffix=gran nproc=7
# Count how many times per year the condition is met
t.rast.aggregate input=tmean_higher20_lower30 \
output=count_tmean_higher20_lower30 \
basename=tmean_higher20_lower30 suffix=gran \
method=count granularity="1 years"
# Average number of days with LSTmean >= 20 and <= 30
t.rast.series input=count_tmean_higher20_lower30 \
output=avg_count_tmean_higher20_lower30 method=average
```
]
.panel[.panel-name[Map]
.center[<img src="assets/img/count_days_higher20_lower30.png" width="50%">]
]
]
.footnote[See [t.rast.algebra](https://grass.osgeo.org/grass-stable/manuals/t.rast.algebra.html) manual for further details]
---
layout: true
#### Number of consecutive days with LSTmean <= -2.0
---
```bash
# Create annual mask
t.rast.aggregate input=lst_daily output=annual_mask \
basename=annual_mask suffix=gran \
granularity="1 year" method=count
# Replace values by zero
t.rast.mapcalc input=annual_mask output=annual_mask_0 \
expression="if(annual_mask, 0)" \
basename=annual_mask_0
# Calculate consecutive days with LST <= -2.0
t.rast.algebra \
expression="lower_m2_consec_days = annual_mask_0 {+,contains,l} \
if(lst_daily <= -2.0 && lst_daily[-1] <= -2.0 || \
lst_daily[1] <= -2.0 && lst_daily <= -2.0, 1, 0)" \
basename=lower_m2_ suffix=gran nproc=7
```
---
```bash
# Inspect values
t.rast.list input=lower_m2_consec_days \
columns=name,start_time,end_time,min,max
# Median number of consecutive days with LST <= -2
t.rast.series input=lower_m2_consec_days \
output=median_lower_m2_consec_days method=median
```
---
.center[<img src="assets/img/median_days_lower_m2.png" width="60%">]
---
layout: false
class: grass-slide hide_logo center
## We have all these maps in GRASS, how do we connect with R now?
# `r emo::ji("hushed")`
---
## [**rgrass7**](https://cran.r-project.org/web/packages/rgrass7/index.html)
- `initGRASS()`: starts a GRASS GIS session from R
- `execGRASS()`: executes GRASS GIS commands
- `gmeta()`: shows GRASS location metadata
- `readVECT()` and `readRAST()`: read vector and raster maps from GRASS into *sf* or *sp* objects
- `writeVECT()` and `writeRAST()`: write *sf* or *sp* objects into GRASS GIS database
.footnote[`r emo::ji("announcement")` Volunteers needed!!]
---
layout: true
### GRASS GIS and `r fa("r-project", fill="#276dc2")` can be used together in two ways:
---
.pull-left[
A. Using [R within a GRASS GIS session](https://grasswiki.osgeo.org/wiki/R_statistics/rgrass7#R_within_GRASS), i.e. starting R (or RStudio) from GRASS terminal
<br>
- type `R` or `rstudio &` in the GRASS GIS terminal
- load `rgrass7` library
- use `readVECT()`, `readRAST()` to read data from GRASS into R
- access GRASS GIS modules and database through `execGRASS()`
- write data (back) to GRASS database with `writeVECT()` and `writeRAST()`
]
.pull-right[
<img src="assets/img/grass_terminal_calling_R.png" width="87%">
]
---
.pull-left[
B. Using [GRASS GIS within an R session](https://grasswiki.osgeo.org/wiki/R_statistics/rgrass7#GRASS_within_R), i.e. we connect to GRASS GIS database from within R (or RStudio).
<br>
- we need to start GRASS GIS with `initGRASS()`
- we access GRASS GIS modules through `execGRASS()`
> Originally intended to apply GRASS functions on data outside GRASS DB; hence some prefer to create throw away locations
]
.pull-right[
<img src="assets/img/grass_within_rstudio_session.png" width="100%">
]
---
layout: false
class: grass-slide center hide_logo
# Let's move to `r fa("r-project", fill="#276dc2")`
---
#### Option B: Close GRASS, open Rstudio and run:
.panelset[
.panel[.panel-name[R code]
```{r grass_init, results='hide', message=FALSE}
library(rgrass7)
# path to GRASS binaries (run `grass78 --config path`)
myGRASS <- "/usr/lib64/grass78"
# path to GRASS database
myGISDbase <- "/home/veroandreo/grassdata_ogh/"
# path to location
myLocation <- "eu_laea"
# path to mapset
myMapset <- "italy_LST_daily"
# start GRASS GIS from R
initGRASS(gisBase = myGRASS, home = tempdir(), gisDbase = myGISDbase,
location = myLocation, mapset = myMapset, override = TRUE)
```
]
.panel[.panel-name[Output]
```{r ref.label='grass_init', echo=FALSE, size='tiny'}
# start GRASS GIS from R
initGRASS(gisBase = myGRASS, home = tempdir(), gisDbase = myGISDbase,
location = myLocation, mapset = myMapset, override = TRUE)
```
]
]
---
#### Load other packages
```{r load_libraries}
library(raster)
library(sf)
library(mapview)
library(biomod2)
```
---
#### Read vector data
.panelset[
.panel[.panel-name[R code]
```{r read_vectors, message=FALSE, warning=FALSE, results='hide'}
# Use sf for vectors
use_sf()
# Read vector layers
Aa_pres <- readVECT("aedes_albopictus")
background <- readVECT("background_points")
```
```{r plot, message=FALSE, warning=FALSE, results='hide'}
# Quick visualization in mapview
mapview(Aa_pres) +
mapview(background, col.regions=NA, cex=2)
```
]
.panel[.panel-name[Map]
```{r ref.label='plot', warning=FALSE, echo=FALSE}
mapview(Aa_pres) +
mapview(background, color="black", col.regions="black", cex=2)
```
]
]
---
layout: true
#### Read raster data
---
```{r read_rasters, message=FALSE, warning=FALSE, results='hide'}
# Use sp for rasters
use_sp()
# List rasters by pattern
worldclim <- execGRASS("g.list", parameters = list(type = "raster", pattern = "worldclim*"))
avg <- execGRASS("g.list", parameters = list(type = "raster", pattern = "avg*"))
median <- execGRASS("g.list", parameters = list(type = "raster", pattern = "median*", exclude = "*[1-5]"))
# Concatenate map lists
to_import <- c(attributes(worldclim)$resOut,
attributes(avg)$resOut,
attributes(median)$resOut)
# Read raster layers
predictors <- list()
for (i in to_import){ predictors[i] <- raster(readRAST(i)) }
```
---
```{r quick_view, message=FALSE, warning=FALSE}
# Quick visualization in mapview
mapview(predictors[['worldclim_bio01']]) + Aa_pres
```
---
layout: false
#### Data preparation and formatting
```{r data_prep1, message=FALSE, warning=FALSE, results='hide'}
# Response variable
n_pres <- dim(Aa_pres)[1]
n_backg <- dim(background)[1]
spp_name <- 'Aedes.albopictus'
pres <- rep(1, n_pres)
backg <- rep(0, n_backg)
myResp <- c(pres, backg)
myRespXY <- rbind(st_coordinates(Aa_pres),
st_coordinates(background))
# Explanatory variables
myExpl <- raster::stack(predictors)
names(myExpl)
```
---
#### Data preparation and formatting
.panelset[
.panel[.panel-name[R code]
```{r data_prep2, message=FALSE, warning=FALSE, results='hide', fig.show='hide'}
# Format data as required by biomod
myBiomodData <- BIOMOD_FormatingData(resp.var = myResp,
expl.var = myExpl,
resp.xy = myRespXY,
resp.name = spp_name)
# Inspect data
myBiomodData
# Plot data
plot(myBiomodData)
```
]
.panel[.panel-name[Output]
```{r print_data_object, warning=FALSE, echo=FALSE}
# Inspect data
myBiomodData
```
]
.panel[.panel-name[Plot]
```{r plot_data_object, warning=FALSE, echo=FALSE, out.width='72%'}
par(mar=c(2,2,2,2))
plot(myBiomodData)
```
]
]
---
#### Set model(s) options
.panelset[
.panel[.panel-name[R code]
```{r model_options, message=FALSE, warning=FALSE, results='hide'}
# Set model options
myBiomodOption <- BIOMOD_ModelingOptions(
MAXENT.Phillips =
list(path_to_maxent.jar = "/home/veroandreo/software/maxent/maxent.jar",
maximumiterations = 200,
lq2lqptthreshold = 100,
l2lqthreshold = 100))
# Inspect all configs for MaxEnt
myBiomodOption@MAXENT.Phillips
```
]
.panel[.panel-name[Output]
```{r print_model_options, message=FALSE, warning=FALSE, echo=FALSE}
myBiomodOption@MAXENT.Phillips
```
]
]
---
#### Run model
```{r model_run, message=FALSE, warning=FALSE, results='hide'}
# Run model
myBiomodModelOut <- BIOMOD_Modeling(
myBiomodData,
models = c('MAXENT.Phillips'),
models.options = myBiomodOption,
NbRunEval=5,
DataSplit=80,
VarImport=10,
models.eval.meth = c('ROC','ACCURACY'),
SaveObj = TRUE,
rescal.all.models = FALSE,
do.full.models = FALSE,
modeling.id = paste(spp_name,"Habitat_Suitability",sep="_"))
# Inspect the model
myBiomodModelOut
```
---
#### Model evaluation
.panelset[
.panel[.panel-name[R code]
```{r model_eval, message=FALSE, warning=FALSE, results='hold'}
# Extract evaluation data
myBiomodModelEval <- get_evaluations(myBiomodModelOut)
# Accuracy
myBiomodModelEval["ACCURACY","Testing.data",,,]
# ROC: Receiver-operator curve
myBiomodModelEval["ROC","Testing.data",,,]
# Save run with max ROC
max_roc <- which.max(myBiomodModelEval["ROC","Testing.data",,,])
```
]
.panel[.panel-name[Plot]
```{r plot_model_eval, message=FALSE, warning=FALSE, echo=FALSE, out.width='60%'}
models_scores_graph(myBiomodModelOut,
by = "cv_run",
metrics = c("ROC", "ACCURACY"))
```
]
]
---
#### Variable importance
.panelset[
.panel[.panel-name[R code]
```{r vi, message=FALSE, warning=FALSE, results='hide'}
# Variable importance
vi <- get_variables_importance(myBiomodModelOut)
# Let's see the first part
head(vi[1:13,1, ,], n = 10L) %>%
knitr::kable(format = 'html')
# ... and estimate the mean