harmonics_fun: Harmonic modelling

Description Usage Arguments Details Value References Examples

View source: R/harmonics_fun.R

Description

This function enables the user to model different number of cycles per year

Usage

1
harmonics_fun(user_vals, user_dates, harmonic_deg, ref_date)

Arguments

user_vals

A vector with numeric values.

user_dates

A Vector with Date objects. See as.Date.

harmonic_deg

Numeric. The number of cycles per year (harmonic degree) that should be modelled.

ref_date

(optional) A Date object. Default is 1970-01-01.

Details

To calculate the harmonic fitted curve of a periodic signal, ordinary least squares regressions are computed using coupled sine and cosine curves on time-series data. The underlying algorithm is based on Shumway & Stoffer (2017) equations 4.1 – 4.2.

Value

A numeric vector with the fitted values.

References

Shumway, R. H., & Stoffer, D. S. (2017). Time series analysis and its applications: with r examples. Springer.

Examples

 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
library(ggplot2)

# Load sample NDVI time-series data.frame
ndvi_df <- base::readRDS(system.file(package = "rHarmonics",
                                     "extdata", "MODIS_NDVI_TimeSeries.rda"))

# Apply harmonic function using 3 cycles per year
fitted_3rd_deg <- harmonics_fun(user_vals = ndvi_df$ndvi,
                                user_dates = ndvi_df$dates,
                                harmonic_deg = 3)

# Combine fitted values with original df
combined_df <- cbind(ndvi_df, fitted_3rd_deg)
names(combined_df) <- c("dates", "ndvi", "fitted")

# Plot original data with fitted values
ggplot2::ggplot() +
  geom_point(data=combined_df, aes(x = dates, y = ndvi), color='black', size=1) +
  geom_line(data=combined_df, aes(x = dates, y = fitted), colour = "red", size=1)+
  labs(title="MODIS NDVI TimeSeries with fitted values", x="Date", y="NDVI") +
  theme(plot.title = element_text(hjust = 0.5, face="bold", size=14),
        axis.text=element_text(size=10),
        axis.title=element_text(size=12),
        legend.title=element_text(size=13, face="bold"),
        legend.text=element_text(size=13))+
  ylim(0,1)


# Apply harmonic function on multi-layer raster file

library(raster)

# Load sample cloud- and snow-free MODIS TimeSeries
sample_raster <- raster::brick(system.file(package = "rHarmonics",
                                           "extdata",
                                           "MODIS_NDVI_stack.tif"))

fitted_raster <- raster::calc(sample_raster,
                              function(x){
                                 harmonics_fun(x, user_dates = ndvi_df$dates,
                                               harmonic_deg = 3)
                              })

MBalthasar/rHarmonics documentation built on Aug. 21, 2020, 8:03 p.m.