Skip to content

Commit

Permalink
add md files
Browse files Browse the repository at this point in the history
  • Loading branch information
CoastWatch-WestCoast committed May 21, 2021
1 parent 38ce0d0 commit a40da68
Show file tree
Hide file tree
Showing 27 changed files with 1,951 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.nc
Binary file added data.nc
Binary file not shown.
171 changes: 171 additions & 0 deletions define_marine_habitat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
# Define a marine habitat

> notebook filename | 07\_turtlewatch\_xtracto.Rmd
The TurleWatch project investigated the thermal habitat of loggerhead
sea turtles in the Pacific Ocean north of the Hawaiian Islands. Research
results indicate that most loggerhead turtles stay in water between
17.5°C and 18.5°C. When the 17.5°C to 18.5°C temperature contour is
drawn on a map of sea surface temperature conditions, it delineates the
boundary of the loggerhead’s preferred habitat.

In this exercise you will plot the thermal boundary of loggerhead sea
turtles using satellite sea surface temperature. The exercise
demonstrates the following techniques:
\* Using xtracto\_3D to extract data from a rectangular area
\* Masking a data array
\* Plotting maps using
ggplot

## Install required packages and load libraries

``` r
# Function to check if pkgs are installed, install missing pkgs, and load
pkgTest <- function(x)
{
if (!require(x,character.only = TRUE))
{
install.packages(x,dep=TRUE,repos='http://cran.us.r-project.org')
if(!require(x,character.only = TRUE)) stop(x, " :Package not found")
}
}

list.of.packages <- c( "ncdf4", "rerddap", "plotdap", "RCurl",
"raster", "colorRamps", "maps", "mapdata",
"ggplot2", "RColorBrewer", "rerddapXtracto")

# create list of installed packages
pkges = installed.packages()[,"Package"]

for (pk in list.of.packages) {
pkgTest(pk)
}
```

## Select the Satellite Data

- Use the MUR SST dataset (ID jplMURSST41mday)
- Gather information about the dataset (metadata) using **rerddap**
- Displays the information

<!-- end list -->

``` r
# CHOOSE DATASET and get information about it


url = "http://coastwatch.pfeg.noaa.gov/erddap/"
dataInfo <- rerddap::info('jplMURSST41mday',url=url)
parameter <- 'sst'
```

## Get Satellite Data

- Select an area off the coast of California: longitude range of -130
to -115 east and latitude range of 25 to 40 north
- Set the time range to days withing one month:
tcoord=c(‘2018-06-06’,‘2018-06-08’)). The values do have to be
different.

<!-- end list -->

``` r
# latitude and longitude of the vertices
ylim<-c(25,40)
xlim<-c(-130,-115)

# Choose an area off the coast of California
# Extract the data
SST <- rxtracto_3D(dataInfo,xcoord=xlim,ycoord=ylim,parameter=parameter,
tcoord=c('2018-06-06','2018-06-08'))
```

## Registered S3 method overwritten by 'httr':
## method from
## print.cache_info hoardr

## info() output passed to x; setting base url to: http://coastwatch.pfeg.noaa.gov/erddap/

``` r
# Drop command needed to reduce SST from a 3D variable to a 2D one
SST$sst <- drop(SST$sst)
```

## Make a quick plot using plotBBox

``` r
plotBBox(SST, plotColor = 'thermal',maxpixels=100000)
```

## grid object contains more than 1e+05 pixels

## increase `maxpixels` for a finer resolution

## Warning in raster::projectRaster(r, crs = crs_string): input and ouput crs are
## the same

![](define_marine_habitat_files/figure-gfm/qplot-1.png)<!-- -->

## Define the Thermal niche of Loggerhead Turtles

\_\_ Set the thermal range to 17.5-18.5 degrees C, as determined by the
TurtleWatch program.\_\_

``` r
## Define turtle temperature range
min.temp <- 17.5
max.temp <- 18.5
```

**Create another variable for habitat temperature**

Set the habitat temperature to equal NA

``` r
SST2 <- SST
SST2$sst[SST2$sst >= min.temp & SST2$sst <= max.temp] <- NA
plotBBox(SST2, plotColor = 'thermal',maxpixels=100000)
```

## grid object contains more than 1e+05 pixels

## increase `maxpixels` for a finer resolution

## Warning in raster::projectRaster(r, crs = crs_string): input and ouput crs are
## the same

![](define_marine_habitat_files/figure-gfm/makeVar-1.png)<!-- -->

It would be nicer to color in the turtle habitat area (the NA values)
with a different color. If you want to customize graphs its better to
use `ggplot` than the `plotBBox` that comes with `rerrdapXtracto`
package. Here we will use `ggplot` to plot the data. But first the data
is reformatted for use in `ggplot`.

Restructure the data

``` r
dims <- dim(SST2$sst)
SST2.lf <- expand.grid(x=SST$longitude,y=SST$latitude)
SST2.lf$sst<-array(SST2$sst,dims[1]*dims[2])
```

## Plot the Data using ‘ggplot’

``` r
coast <- map_data("worldHires", ylim = ylim, xlim = xlim)

par(mar=c(3,3,.5,.5), las=1, font.axis=10)

myplot<-ggplot(data = SST2.lf, aes(x = x, y = y, fill = sst)) +
geom_tile(na.rm=T) +
geom_polygon(data = coast, aes(x=long, y = lat, group = group), fill = "grey80") +
theme_bw(base_size = 15) + ylab("Latitude") + xlab("Longitude") +
coord_fixed(1.3,xlim = xlim, ylim = ylim) +
ggtitle(unique(as.Date(SST2$time))) +
scale_fill_gradientn(colours = rev(rainbow(12)),limits=c(10,22),na.value = "firebrick4")

myplot
```

![](define_marine_habitat_files/figure-gfm/plot-1.png)<!-- -->
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
213 changes: 213 additions & 0 deletions extract_data_marine-sanctuary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
# Extract data within a boundary

In this exercise, you will download data from within the boundaries of
the Monterey Bay National Marine Sanctuary (MBNMS) and visualize the
data on a map.

The exercise demonstrates the following skills:

- Using **rerddap** to retrieve information about a dataset from
ERDDAP
- Using the **rxtractogon** function from **rerdapXtracto** to extract
satellite data within an polygon over time
- Mapping satellite data

## Install packages and load libraries

``` r
pkges = installed.packages()[,"Package"]
# Function to check if pkgs are installed, install missing pkgs, and load
pkgTest <- function(x)
{
if (!require(x,character.only = TRUE))
{
install.packages(x,dep=TRUE,repos='http://cran.us.r-project.org')
if(!require(x,character.only = TRUE)) stop(x, " :Package not found")
}
}

# create list of required packages
list.of.packages <- c("ncdf4", "rerddap","plotdap", "parsedate",
"sp", "ggplot2", "RColorBrewer",
"reshape2", "maps", "mapdata",
"jsonlite", "rerddapXtracto")

# Run install and load function
for (pk in list.of.packages) {
pkgTest(pk)
}

# create list of installed packages
pkges = installed.packages()[,"Package"]
```

## Load sanctuary boundary coordinates

The **rerddapXtracto** package comes with the dataset **mbnms** which
conatains the longitude and latitude values for the boundary of the
Monterey Bay National Marine Sanctuary. These coordinates draw the the
boundary of the sanctuary on a map, like tracing a dot-to-dot drawing.
Take a quick look at the contents of this data variable.

``` r
str(mbnms)
```

## 'data.frame': 6666 obs. of 2 variables:
## $ Longitude: num -123 -123 -123 -123 -123 ...
## $ Latitude : num 37.9 37.9 37.9 37.9 37.9 ...

Additional sanctuary boundaries may be obtained at
<http://sanctuaries.noaa.gov/library/imast_gis.html>.

**The script below:**

- Extracts the longitude and latitude data into vector variables

<!-- end list -->

``` r
xcoord <- mbnms$Longitude
ycoord <- mbnms$Latitude
```

## Select the chloropyll dataset

For this example we will use a 750 m VIIRS monthly chlorophyll dataset
(ID erdVHNchlamday)

**The script below:**
\* Gathers information about the dataset (metadata) using **rerddap**
\* The default source ERDDAP for **rerddap** is
<https://upwell.pfeg.noaa.gov/erddap>”. Since we are pulling the data
from a different ERDDAP at “<http://coastwatch.pfeg.noaa.gov/erddap/>”,
change the url to url = “<http://coastwatch.pfeg.noaa.gov/erddap/>\*
Displays the dataset information

``` r
# Use rerddap to get dataset metadata
url = "http://coastwatch.pfeg.noaa.gov/erddap/"
dataInfo <- rerddap::info('erdVHNchlamday',url=url) # N. Pacific 750 m VIIRS chl
# Display the metadata dataset info
dataInfo
```

## <ERDDAP info> erdVHNchlamday
## Base URL: http://coastwatch.pfeg.noaa.gov/erddap/
## Dataset Type: griddap
## Dimensions (range):
## time: (2015-03-16T00:00:00Z, 2021-04-16T00:00:00Z)
## altitude: (0.0, 0.0)
## latitude: (-0.10875, 89.77125)
## longitude: (-180.03375, -110.00625)
## Variables:
## chla:
## Units: mg m^-3

## Set the options for the polygon data extract

The **rxtractogon** function will need the parameter and coordinates for
the extract \* For the parameter: Use the name of the chlorophyll
parameter that was displayed above in dataInfo: **parameter \<- “chla”**
\* For the coordinates: determine your selctions for x, y, z, and time.
\* z coordinate: The metadata from dataInfo shows that this variable has
a altitude coordinate that equals zero. So set the value of the z
coordinate to zero: **zcoord \<- 0.**
\* time coordinate: The time variable passed to xtracogon must contain
two elements, the start and endpoints of the desired time period. This
example uses ERDDAP’s **last** option to retrieve data from the most
recent time step. The **last** option also accepts the minus **-**
operator. To request the time step with the second most recent data use
“last-1”. In the script below the time variable (tcoord) is defined as
**tcoord \<- c(“last-1”, “last”)**

``` r
# set the parameter to extract
parameter <- 'chla'
# set the time range
tcoord <- c("last-1", "last")
# Assign longitude and latitude vectors from the CSV file to variables
xcoord <- mbnms$Longitude
ycoord <- mbnms$Latitude
# set the altitude variable to zero
zcoord <- 0.
```

## Extract data and mask it using rxtractogon

- Run **rxtractogon** to extract data from the “erdVHNchlamday”
dataset and mask out any data outside the MBNMS boundary.
- List the data

<!-- end list -->

``` r
## Request the data
sanctchl <- rxtractogon (dataInfo, parameter=parameter, xcoord=xcoord, ycoord=ycoord,tcoord=tcoord,zcoord=zcoord)
```

## Registered S3 method overwritten by 'httr':
## method from
## print.cache_info hoardr

## info() output passed to x; setting base url to: http://coastwatch.pfeg.noaa.gov/erddap/

``` r
## List the returned data
str(sanctchl)
```

## List of 6
## $ chla : num [1:272, 1:311, 1:2] NA NA NA NA NA NA NA NA NA NA ...
## $ datasetname: chr "erdVHNchlamday"
## $ longitude : num [1:272(1d)] -123 -123 -123 -123 -123 ...
## $ latitude : num [1:311(1d)] 35.6 35.6 35.6 35.6 35.6 ...
## $ altitude : num [1(1d)] 0
## $ time : POSIXlt[1:2], format: "2021-03-16" "2021-04-16"
## - attr(*, "class")= chr [1:2] "list" "rxtracto3D"

## Choose Time to Plot

The extracted data contains two time periods of chlorophyll data within
the sanctuary boundaries. For this example we will show how to select
just one time period from the options and map it, here we choose the
second time stamp.

``` r
sanctchl1 <- sanctchl
sanctchl1$chla <- sanctchl1$chla[, , 2]
sanctchl1$time <- sanctchl1$time[2]
```

### Plot the data

- Use the plotBBox function in rerddapXtracto to quickly plot the
data

<!-- end list -->

``` r
plotBBox(sanctchl1, plotColor = 'algae',maxpixels=100000)
```

## Warning in raster::projectRaster(r, crs = crs_string): input and ouput crs are
## the same

![](extract_data_marine-sanctuary_files/figure-gfm/map-1.png)<!-- -->

### Apply a function to the data

- Here we apply a log function to the chlorophyll data and plot it
again.

<!-- end list -->

``` r
myFunc <- function(x) log(x)
plotBBox(sanctchl1, plotColor = 'algae',maxpixels=100000, myFunc=myFunc)
```

## Warning in raster::projectRaster(r, crs = crs_string): input and ouput crs are
## the same

![](extract_data_marine-sanctuary_files/figure-gfm/addfunc-1.png)<!-- -->
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added grid.nc
Binary file not shown.
Binary file added grid_subset.nc
Binary file not shown.
Loading

0 comments on commit a40da68

Please sign in to comment.