-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy path07-prac7.Rmd
672 lines (438 loc) · 27.4 KB
/
07-prac7.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
# Advanced raster analysis
## Learning objectives
By the end of this practical you should be able to:
1. Explain and execute appropraite pre-proessing steps of raster data
2. Replicate published methodologies using raster data
3. Design new R code to undertake further analysis
## Recommended listening
Some of these practicals are long, take regular breaks and have a listen to some of our fav tunes each week.
[Andy](https://www.youtube.com/watch?v=P00HMxdsVZI)
## Introduction
Within this practical we are going to be using data from the Landsat satellite series provided for free by the United States Geological Survey (USGS) to replicate published methods. Landsat imagery is the longest free temporal image repository of consistent medium resolution data. It collects data at each point on Earth each every 16 days (temporal resolution) in a raster grid composed of 30 by 30 m cells (spatial resolution). Geographical analysis and concepts are becoming ever more entwined with remote sensing and Earth observation. Back when I was an undergraduate there was specific software for undertaking certain analysis, now you can basically use any GIS. I see remote sensing as the science behind collecting the data with spatial data analysis then taking that data and providing meaning. So whilst i'll give a background to Landsat data and remote sensing, this practical will focus on more advanced methods for analysing and extracting meaning from raster data.
### Remote sensing background (required)
* Landsat is raster data
* It has pixels of 30 by 30m collected every 16 days with global coverage
* As humans we see in the visible part of the electromagnetic spectrum (red-green-blue) Landsat takes samples in these bands and several more to make a spectral sigature for each pixel (see image below)
* Each band is provided as a seperate ```.TIFF``` raster layer
```{r echo=FALSE, out.width = "500pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac7_images/specsig.jpg')
```
Later on we will compute temperature from the Landsat data, whilst i refer to and explain each varaiable created don't get overwhelmed by it, take away the process of loading and manipulating raster data in R to extract meaningful information. An optional remote sensing background containing additional information can be found at the end of this practical should you wish to explore this further.
## Data
### Shapefile
The shapefile of Manchester is available from the data folder for this week on [GitHub](https://github.com/andrewmaclachlan/CASA0005repo/tree/master/prac7_data)
### Raster data (Landsat)
To access the Landsat data we will use in this practical you can either:
(a) Sign up for a free account at: https://earthexplorer.usgs.gov/.
(b) Use the Landsat data provided on Moodle --- this will be available only if the earth explorer website is down (e.g. in the case of US government shutdowns)
To download the data:
1. Search for Manchester in the address/place box and select it.
2. Select the date range between the 12/5/2019 and 14/5/2019 --- it's a US website so check the dates are correct.
3. Click dataset and select Landsat, then Landsat Collection 1 Level-1, check Landsat 8 (level 2 is surface reflectance --- see [Remote sensing background (optional)]
4. Click results, there should be one image, download it..it might take a while
5. Landsat data comes zipped twice as a ```.tar.gz```. Use [7Zip](https://www.7-zip.org/) or another file extractor, extract it once to get to a ```.tar``` then extract again and files should appear.
## Processing raster data
### Loading
Today, we are going to be using a Landsat 8 raster of Manchester. The vector shape file for Manchester has been taken from an ESRI repository.
6. Let's load the majority of packages we will need here.
```{r message=FALSE, warning=FALSE, cache=TRUE}
## listing all possible libraries that all presenters may need following each practical
library(sp)
library(raster)
library(rgeos)
library(rgdal)
library(rasterVis)
library(ggplot2)
```
7. Now let's list all our Landsat bands except band 8 (i'll explain why next) along with our study area shapefile. Each band is a seperate ```.TIF``` file.
```{r message=FALSE, warning=FALSE, cache=TRUE}
# List your raster files excluding band 8 using the patter argument
listlandsat <- list.files("prac7_data/Lsatdata",pattern=".*[B123456790]\\.tif$",
ignore.case=TRUE, full.names=TRUE)
# Load the manchester boundary
manchester_boundary <- readOGR('prac7_data/manchester_boundary.shp')
# Load our raster layers into a stack
stacklandsat <- stack(listlandsat)
#check they have the same Coordinate Reference System (CRS)
crs(manchester_boundary)
crs(stacklandsat)
```
### Resampling
8. There is an error with this dataset as band 8 does not fully align with the extent of the other raster layers. There are several ways to fix this, but in this tutorial we will resample the band 8 layer with the extent of band 1. Resampling takes awhile, so please be patient...
```{r eval=FALSE, cache=TRUE}
# get band 8
b8list <- list.files("prac7_data/Lsatdata",pattern=".*B[8]\\.tif$",
ignore.case=TRUE, full.names=TRUE)
b8 <- raster(b8list)
## ngb is a nearest neighbour sampling method
b8<-resample(b8,
stacklandsat$LC08_L1TP_203023_20190513_20190521_01_T1_B1,
method = "ngb")
# Write out the raster
writeRaster(b8, names(b8), format='GTiff', overwrite=TRUE)
```
9. Load band 8 and add it to our raster stack
```{r, cache=TRUE}
b8list2 <- list.files("prac7_data/Lsatdata",pattern=".*B[8]\\.tif$", ignore.case=TRUE,
full.names = TRUE)
# Read in band 8
b8backin <- raster(b8list2)
stacklandsat <- addLayer(stacklandsat, b8backin)
```
10. We can compare it to see if both rasters have the same extent, number of rows and columns, projection, resolution and origin
```{r, cache=TRUE}
compareRaster(stacklandsat$LC08_L1TP_203023_20190513_20190521_01_T1_B1,
stacklandsat$LC08_L1TP_203023_20190513_20190521_01_T1_B8)
```
### Clipping
10. Our raster is currently the size of the scene which satellite data is distributed in, to clip it to our study area it's best to first crop it to the extent of the shapefile and then mask it as we have done in previous practicals...
```{r, cache=TRUE}
e <- extent(manchester_boundary)
lsatcrop <- crop(stacklandsat, e)
lsatmask <- mask(lsatcrop, manchester_boundary)
```
11. If all we wanted to do was clip our data, we could now change our filenames in the raster stack and write the ```.TIFF ``` files out again...
```{r, cache=TRUE}
# add mask to the filenames within the raster stack
names(lsatmask)<-paste(names(lsatmask), "mask", sep="")
# I need to write mine out in another location
outputfilenames <- paste("prac7_data/Lsatdata/", names(lsatmask), sep="")
```
In the first line of code i'm taking the original names of the raster layers and adding "mask" to the end of them. This is done using ```paste()``` and the arguments
* ```names(lsatmask)```: original raster layer names
* ```"mask"```: what i want to add to the names
* ```sep=""```: how the names and "mask" should be seperated --- "" means no spaces
As i can't upload my Landsat files to GitHub i'm storing them in a folder that is not linked (remember this is all sotred on GitHub) -- so you won't find ```prac7_data/Lsatdata``` on there. If you want to store your clipped Landsat files in your project directory just use:
```{r eval=FALSE, cache=TRUE}
writeRaster(lsatmask, names(lsatmask), bylayer=TRUE, format='GTiff', overwrite=TRUE)
```
For me though it's:
```{r, cache=TRUE}
writeRaster(lsatmask, outputfilenames, bylayer=TRUE, format='GTiff', overwrite=TRUE)
```
Here i write out each raster layer individually though specifying ```bylayer=TRUE```.
## Data exploration
### More loading and manipulating
12. For the next stage of analysis we are only interested in bands 1-7, we can either load them back in from the files we just saved or take them directly from the original raster stack.
```{r, cache=TRUE}
# either read them back in from the saved file:
manc_files<-list.files("prac7_data/Lsatdata/",pattern=".*B[1234567]\\mask.tif$",
ignore.case=TRUE, full.names=TRUE)
manc <- stack(manc_files)
# or extract them from the original stack
manc<-stack(lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B1mask,
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B2mask,
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B3mask,
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B4mask,
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B5mask,
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B6mask,
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B7mask)
# Name the Bands based on where they sample the electromagentic spectrum
names(manc) <- c('ultra-blue', 'blue', 'green', 'red', 'NIR', 'SWIR1', 'SWIR2')
```
13. If you want to extract specific information from a raster stack use:
```{r results="hide", eval=FALSE, cache=TRUE}
crs(manc) # projection
extent(manc) # extent
ncell(manc) # number of cells
dim(manc) # number of rows, columns, layers
nlayers(manc) # number of layers
res(manc) # xres, yres
```
### Plotting data
14. Let's actually have a look at our raster data, first in true colour (how humans see the world) and then false colour composites (using any other bands but not the combination of red, green and blue).
```{r, cache=TRUE}
# true colour composite
manc_rgb <- stack(manc$red, manc$green, manc$blue)
# false colour composite
manc_false <- stack(manc$NIR, manc$red, manc$green)
plotRGB(manc_rgb, axes=TRUE, stretch="lin")
plotRGB(manc_false, axes=TRUE, stretch="lin")
```
### Data similarity
15. What if you wanted to look at signle bands and also check the similarity between bands?
```{r, cache=TRUE}
# Looking at single bands
plot(manc$SWIR2)
## How are these bands different?
#set the plot window size (2 by 2)
par(mfrow = c(2,2))
#plot the bands
plot(manc$blue, main = "Blue")
plot(manc$green, main = "Green")
plot(manc$red, main = "Red")
plot(manc$NIR, main = "NIR")
## Look at the stats of these bands
pairs(manc[[1:7]])
```
Low statistical significance means that the bands are sufficiently different enough in their wavelength reflectance to show different things in the image. We can also make this look a bit nicer with ```ggplot2``` and ```GGally```
```{r cache=TRUE}
library(ggplot2)
library(GGally)
mancdataframe=as.data.frame(manc[[1:7]], na.rm=TRUE)
randomsample<-mancdataframe[sample(nrow(mancdataframe), 100), ]
ggpairs(randomsample, axisLabels="none")
```
You can do much more using ```GGally``` have a look at the great [documentation](https://ggobi.github.io/ggally/#ggallyggpairs)
## Basic raster calculations
Now we will move on to some basic advanced raster analysis to compute temperature from this raster data. To do so we need to generate additional raster layers, the first of which is NDVI
### NDVI
Live green vegetation can be represented with the NIR and Red Bands through the normalised difference vegetation index (NDVI) as chlorophyll reflects in the NIR wavelength, but absorbs in the Red wavelength.
$$NDVI= \frac{NIR-Red}{NIR+Red}$$
### NDVI function
In R we can write functions to logically break our code into simpler sections. We can use NDVI as an example...
16. Let's make a function called ```NDVIfun```
```{r, cache=TRUE}
NDVIfun <- function(NIR, Red) {
NDVI <- (NIR - Red) / (NIR + Red)
return(NDVI)
}
```
Here we have said our function needs two arguments NIR and Red, the next line calcualtes NDVI based on the formula and returns it. To be able to use this function throughout our analysis either copy it into the console or make a new R script, save it in your project then call it within this code using the ```source()``` function e.g...
```{r eval=FALSE, cache=TRUE}
source('insert file name')
```
17. To use the function do so through...
```{r, cache=TRUE}
ndvi <- NDVIfun(manc$NIR, manc$red)
```
Here we call the function ```NDVIfun()``` and then provide the NIR and Red band.
18. Check the output
```{r, cache=TRUE}
plot(ndvi, col = rev(terrain.colors(10)), main = "Landsat-NDVI")
# Let's look at the histogram for this dataset
hist(ndvi, breaks = 40, main = "NDVI Histogram", xlim = c(-.3,.8))
```
19. We can reclassify to the raster to show use what is most likely going to vegetation based on the histogram using the 3rd quartile --- anything above the 3rd quartile we assume is vegetation.
> Note, this is an assumption for demonstration purposes, if you were to do something similar in your assignment be sure to provide reasoning with linkage to literature (e.g. policy or academic)
```{r, cache=TRUE}
veg <- reclassify(ndvi, cbind(-Inf, 0.3, NA))
plot(veg, main = 'Possible Veg cover')
```
20. Let's look at this in relation to Manchester as a whole
```{r, cache=TRUE}
plotRGB(manc_rgb, axes = TRUE, stretch = "lin", main = "Landsat True Color Composite")
plot(veg, add=TRUE, legend=FALSE)
```
## Advanced raster calculations
The goal of this final section is to set up a mini investigation to see if there is a relationship between urban area and temperature. If our hypothesis is that there is a relationship then our null is that there is not a relationship...
### Calucating tempearture from Landsat data
Here we are going to compute temperature from Landsat data --- there are many methods that can be found within literature to do so but we will use the one originally developed by Artis & Carnahan (1982), recently summarised by Guha et al. 2018 and and Avdan and Jovanovska (2016).
Some of the terms used our outlined in the remote sensing background section at the end of the document, so check back there if you get confused.
21. Calcualte the Top of Atmopshere (TOA) spectral radiance from the Digital Number (DN) using:
$$\lambda= Grescale * QCAL + Brescale$$
TOA spectral radiance is light reflected off the Earth as seen from the satellite measure in radiance units.
In this equation Grescale and Brescale represent the gain and bias of the image, with QCAL the Digital Number (DN) --- how the raw Landsat image is captured.
Grescale and Brescale are available from the ```.MTL``` file provided when you downloaded the Landsat data. Either open this file in notepad and extract the required values for band 10 gain (MULT_BAND) and bias (ADD_BAND)
...Or we can automate it using the ```MTL()``` function within the ```RStoolbox``` package
```{r results="hide", warnings=FALSE, message=FALSE, cache=TRUE}
library(RStoolbox)
MTL <- list.files("prac7_data/Lsatdata/",pattern="*.txt", ignore.case=TRUE, full.names = TRUE)
readMTL<-readMeta(MTL)
#To see all the attributes
readMTL
```
22. Now let's extract the values from the readMTL variable for Band 10...
```{r, cache=TRUE}
offsetandgain <- subset(readMTL$CALRAD, rownames(readMTL$CALRAD) == "B10_dn")
```
23. Run the calculation using the band 10 raster layer
```{r, cache=TRUE}
TOA <- offsetandgain$gain *
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B10mask +
offsetandgain$offset
```
24. Next convert the TOA to Brightness Temperature $T_b$ using the following equation:
$$T_b=\frac{K_2}{ln((K_1/\lambda)+1)}$$
Brightness temperature is the radiance travelling upward from the top of the atmosphere to the satellite in units of the temperature of an equivalent black body.
K1 (774.8853) and K2 (1321.0789) are pre launch calibration constants provided by USGS.
Check the [handbook](https://prd-wret.s3-us-west-2.amazonaws.com/assets/palladium/production/atoms/files/LSDS-1574_L8_Data_Users_Handbook_v4.0.pdf) for these values
25. Instead of hardcoding these values...yep, you guessed it... we can extract them from our ```MTL```
```{r, cache=TRUE}
Calidata <- as.data.frame(readMTL$CALBT)
# subet the rows
Calidata <- subset(Calidata, rownames(Calidata) %in% "B10_dn")
# subset the columns
K1<-subset(Calidata, select=(K1))
K2<-subset(Calidata, select=(K2))
# get just the values out
K1<-K1$K1
K2<-K2$K2
# this would also work for K1
K1<-readMTL$CALBT$K1[1]
#for K2
K2<-readMTL$CALBT$K2[1]
Brighttemp<-(K2 / log((K1 / TOA) + 1))
```
Earlier we calcualted NDVI, let's use that to determine emissivity of each pixel.
26. First we need to calcualte the fractional vegetation of each pixel, through the equation:
$$F_v= \left( \frac{NDVI - NDVI_{min}}{NDVI_{max}-NDVI_{min}} \right)^2$$
```{r, cache=TRUE}
facveg=(ndvi-0.2/0.5-0.2)^2
```
Fractional vegetation cover is the ratio of vertically projected area of vegetation to the total surface extent.
Here, $NDVI_{min}$ is the minimum NDVI value (0.2) where pixels are considered bare earth and $NDVI_{max}$ is the value at which pixels are considered healthy vegetation (0.5)
27. Now compute the emissivity using:
$$\varepsilon = 0.004*F_v+0.986$$
```{r, cache=TRUE}
emiss=0.004*facveg+0.986
```
Emissivity is the ratio absorbed radiation engery to total incoming radiation engery compared to a blackbody (which would absorb everything), being ameasure of absoptivity.
28. Great, we're nearly there... get our LST following the equation from Weng et al. 2004 (also summarised in Guja et al. (2018) and Avdan and Jovanovska (2016)):
$$LST= \frac{T_b}{1+(\lambda \varrho T_b / (p))ln\varepsilon}$$
Where:
$$p= h\frac{c}{\varrho}$$
Ok, don't freak out....let's start with calculating $p$
Here we have:
* $h$ which is Plank's constant $6.626 × 10^-34 Js$
* $c$ which is the velocity of light in a vaccum $2.998 × 10^8 m/sec$
* $\varrho$ which is the Boltzmann constant of $1.38 × 10^-23 J/K$
```{r, cache=TRUE}
Boltzmann=1.38*10e-23
Plank=6.626*10e-34
c=2.998*10e8
p=Plank*(c/Boltzmann)
```
Now for the rest of the equation....we have the values for:
* $\lambda$ which is the effective wavelength of our data (10.9 for Landsat 8 band 10)
* $\varepsilon$ emissivity
* $T_b$ Brightness Temperature
30. Run the equation with our data
```{r, cache=TRUE}
#define remaining varaibles
lambda=1.09e-5
#run the LST calculation
LST <-Brighttemp/(1 +(lambda*Brighttemp/p)*log(emiss))
# check the values
LST
```
31. Are the values very high?... That's because we are in Kevlin not degrees Celcius...let's fix that and plot the map
```{r, cache=TRUE}
LST<-LST-273.15
plot(LST)
```
Nice that's our temperature data sorted.
## Calucating urban area from Landsat data
How about we extract some urban area using another index and then see how our temperature data is related?
We will use the Normalized Difference Built-up Index (NDBI) algorithm for identification of built up regions using the reflective bands: Red, Near-Infrared (NIR) and Mid-Infrared (MIR) originally proposed by Zha et al. (2003).
It is very similar to our earlier NDVI calculation but using different bands...
$$NDBI= \frac{Short-wave Infrared (SWIR)-Near Infrared (NIR)}{Short-wave Infrared (SWIR)+Near Infrared (NIR)}$$
In Landsat 8 data the SWIR is band 6 and the NIR band 5
31. Let's compute this index now...
```{r, cache=TRUE}
NDBI=((lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B6mask-
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B5mask)/
(lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B6mask+
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B5mask))
```
But do you remember our function? ...Well this is the same calculation we used there just with different raster layers (or bands) so we could reuse it...
```{r, cache=TRUE}
NDBIfunexample <- NDVIfun(lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B6mask,
lsatmask$LC08_L1TP_203023_20190513_20190521_01_T1_B5mask)
```
## Urban area and temperature relationship
32. We could plot the varaibles agaisnt each other but there are a lot of data points
```{r, cache=TRUE}
plot(values(NDBI), values(LST))
```
This is termed the overplotting problem. So, let's just take a random subset of the same pixels from both raster layers.
33. To do so we need to again stack our layers
```{r, cache=TRUE}
# stack the layers
computeddata=stack(LST,NDBI)
# take a random subset
random=sampleRandom(computeddata, 500, cells=TRUE)
# check the output
plot(random[,2], random[,3])
```
34. Let's jazz things up, load some more packages
```{r message=FALSE, warning=FALSE, cache=TRUE}
library(plotly)
library(tidyverse)
library(htmlwidgets)
library(ggplot2)
```
35. Transfrom the data to a data.frame to work with ggplot, then plot
```{r, cache=TRUE}
#convert to a data frame
randomdf=as.data.frame(random)
#rename the coloumns
names(randomdf)<-c("cell", "Temperature", "Urban")
heat<-ggplot(randomdf, aes(x = Urban, y = Temperature))+
geom_point(alpha=2, colour = "#51A0D5")+
labs(x = "Temperature",
y = "Urban index",
title = "Manchester urban and temperature relationship")+
geom_smooth(method='lm', se=FALSE)+
theme_classic()+
theme(plot.title = element_text(hjust = 0.5))
# interactive plot
ggplotly(heat)
```
36. How about plotting the whole dataset rather than a random subset...
```{r message=FALSE, warning=FALSE, cache=TRUE}
computeddatadf<-as.data.frame(computeddata)
names(computeddatadf)<-c("Temperature", "Urban")
hexbins <- ggplot(computeddatadf, aes(x=Urban, y=Temperature) ) +
geom_hex(bins=100, na.rm=TRUE) +
labs(fill = "Count per bin")+
geom_smooth(method='lm', se=FALSE, size=0.6)+
theme_bw()
ggplotly(hexbins)
```
## Statistical summary
37. To see if our varaibles are related let's run some basic correlation
```{r, cache=TRUE}
stat.sig=cor.test(computeddatadf$Temperature, computeddatadf$Urban, use = "complete.obs",
method = c("pearson"))
stat.sig
```
Let's walk through the results here...
* t: is the t-test statistic value, we can work out the critical t value using:
```{r, cache=TRUE}
abs(qt(0.05/2, 198268))
```
As our t values is > than the critial value we can say that there is a relationship between the datasets. However, we would normally report the p-value...
* df: is the number of values we have -2...
```{r, cache=TRUE}
length(computeddatadf$Temperature)
# but some are NA
removena<-na.omit(computeddatadf)
length(removena$Temperature)
length(removena$Urban)
```
* p-value: tells us wheather there is a statistically significant correlation between the datasets and if that we can reject the null hypothesis if p<0.05 (there is a 95% chance that the relationship is real).
* cor: Pearon's correlation coefficient
* 95 percent confidence interval: 95% confident that the population correlation coeffieicent is within this interval
As p<0.05 is shows that are variables are have a statistically significant correlation... so as urban area (assuming the index in representative) per pixel increases so does temperature...therefore we can reject our null hypothesis... but remember that this does not imply causation!!
If you want more information on statistics in R go and read [YaRrr! A Pirate's Guide to R](https://bookdown.org/ndphillips/YaRrr/), chapter 13 on hypothesis tests.
## Considerations
If you wanted to explore this type of analysis further then you would need to consider the following:
* Other methods for extracting temperature from Landsat data
* Validation of your temperature layer (e.g. weather station data)
* The formula used to calculate emissivity --- there are many
* The use of raw satellite data as opposed to remove the effects of the atmosphere. Within this practical we have only used relative spatial indexes (e.g. NDVI). However, if you were to use alternative methods it might be more appropraite to use surface reflectance data (also provided by USGS).
## Extension
Already an expert with raster data and R? Here we have just looked at one temperature image and concluded that urban area and temperature are realted, but does that hold true for other time periods?
If you found this practical straightforward source some Landsat data for an area of interest and create some R code to explore the temporal relationship between urban area and temperature.
...Or run the analysis with different data and methods.
Data:
MODIS daily LST: https://modis.gsfc.nasa.gov/data/dataprod/mod11.php
MODIS imagery: https://modis.gsfc.nasa.gov/
Methods:
Supervised or unsupervised landcover classificaiton: https://rspatial.org/rs/5-supclassification.html#
Here you could classify an image into several landcover classes and explore their relationship with temperature
## References
Thanks to CASA gradaute student Matt Ng for providing the outline to the start of this practical
Avdan, U. and Jovanovska, G., 2016. Algorithm for automated mapping of land surface temperature using LANDSAT 8 satellite data. Journal of Sensors, 2016.
Guha, S., Govil, H., Dey, A. and Gill, N., 2018. Analytical study of land surface temperature with NDVI and NDBI using Landsat 8 OLI and TIRS data in Florence and Naples city, Italy. European Journal of Remote Sensing, 51(1), pp.667-678.
Weng, Q., Lu, D. and Schubring, J., 2004. Estimation of land surface temperature–vegetation abundance relationship for urban heat island studies. Remote sensing of Environment, 89(4), pp.467-483.
Young, N.E., Anderson, R.S., Chignell, S.M., Vorster, A.G., Lawrence, R. and Evangelista, P.H., 2017. A survival guide to Landsat preprocessing. Ecology, 98(4), pp.920-932.
Zha, Y., Gao, J. and Ni, S., 2003. Use of normalized difference built-up index in automatically mapping urban areas from TM imagery. International journal of remote sensing, 24(3), pp.583-594.
## Remote sensing background (optional)
Landsat sensors capture reflected solar energy, convert these data to radiance, then rescale this data into a Digital Number (DN), the latter representing the intensity of the electromagnetic radiation per pixel. The range of possible DN values depends on the sensor radiometric resolution. For example Landsat Thematic Mapper 5 (TM) measures between 0 and 255 (termed 8 bit), whilst Landsat 8 OLI measures between 0 and 65536 (termed 12 bit). These DN values can then be converted into Top of Atmosphere (TOA) radiance and TOA reflectance through available equations and known constants (https://landsat.usgs.gov/landsat-8-l8-data-users-handbook-section-5¬) that are preloaded into certain software. The former is how much light the instrument sees in meaningful units whilst the latter removes the effects of the light source. However, TOA reflectance is still influenced by atmospheric effects. These atmospheric effects can be removed through atmospheric correction achievable in software such as ENVI and QGIS to give surface reflectance representing a ratio of the amount of light leaving a target to the amount of light striking it.
We must also consider the spectral resolution of satellite imagery, Landsat 8 OLI has 11 spectral bands and as a result is a multi-spectral sensor. As humans we see in the visible part of the electromagnetic spectrum (red-green-blue) --- this would be three bands of satellite imagery --- however satellites can take advantage of the rest of the spectrum. Each band of Landsat measures in a certain part of the spectrum to produce a DN value. We can then combine these values to produce ‘colour composites’. So a ‘true’ colour composite is where red, green and blue Landsat bands are displayed (the visible spectrum). Based on the differing DN values obtained, we can pick out the unique signatures (values of all spectral bands) of each land cover type, termed spectral signature.
For more information read Young et al. (2017) A survival guide to Landsat preprocessing:
https://esajournals.onlinelibrary.wiley.com/doi/pdf/10.1002/ecy.1730
## Feedback
Was anything that we explained unclear this week or was something really clear...let us know [here](https://forms.gle/w2GUDYc7tSavGy7r6). It's anonymous and we'll use the responses to clear any issues up in the future / adapt the material.