Skip to content

Commit cfc9b2a

Browse files
committed
Update intro on Peter's post
Signed-off-by: Alex Ellis (OpenFaaS Ltd) <alexellis2@gmail.com>
1 parent 966c98c commit cfc9b2a

File tree

1 file changed

+243
-0
lines changed

1 file changed

+243
-0
lines changed

_posts/2021-05-14-r-templates.md

Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
---
2+
title: "Functions for data science with R templates for OpenFaaS"
3+
description: "Learn how to combine the power of R with Serverless for data science."
4+
date: 2021-05-12
5+
image: /images/2021-05-r/background.jpg
6+
categories:
7+
- kubernetes
8+
- r
9+
- plumber
10+
author_staff_member: peter
11+
dark_background: true
12+
---
13+
14+
Learn how to combine the power of R with Serverless for data science.
15+
16+
## Introduction
17+
18+
> Intro by [Alex Ellis](https://twitter.com/alexellisuk): "This is a guest post by Peter Solymos. Peter reached out to me after becoming an OpenFaaS Sponsor. He wanted to help other data-scientists like himself understand the value of combining R with functions in the cloud. Hope you enjoy the post and feel free to reach out to us via [OpenFaaS Slack](https://slack.openfaas.io/) with comments, questions and suggestions."
19+
20+
In this post I will introduce you to the [R](https://www.r-project.org/) templates for OpenFaaS, then I will build a function that pulls data from a COVID-19 API, fits a time series model to the data, and makes a forecast for the future case counts.
21+
22+
> This post is written for existing OpenFaaS users, if you're new then you should [try deploying OpenFaaS](https://docs.openfaas.com/deployment/) and following a tutorial to get a feel for how everything works. Why not start with this course? [Introduction to Serverless course by the LinuxFoundation](https://www.openfaas.com/blog/introduction-to-serverless-linuxfoundation/)
23+
24+
### Why R?
25+
26+
[R](https://www.r-project.org/) is one of the most popular languages for data science. R's strength is in _statistical computing_ and _graphics_. Is popularity has been growing steadily as measured by the increase in [Stack Overflow questions](https://stackoverflow.blog/2017/10/10/impressive-growth-r/). R's use is most prominent in disciplines relying on classical statistical approaches, such as academia, healthcare/biostatistics, environmental sciences, and finance, just to mention a few. What makes R ideal in these disciplines is the immediate access to latest statistical methods which often get published as extension packages alongside journal articles.
27+
28+
R's huge ecosystem of extension packages (currently more than 14 thousand in [CRAN](https://cran.r-project.org/) repositories, not counting packages on GitHub etc.) is driving the growth of R and the community around it. Some of the most well known packages include [ggplot2](https://CRAN.R-project.org/package=ggplot2) for the grammar of graphics, and [dplyr](https://CRAN.R-project.org/package=ggplot2) for the grammar of data manipulation, both part of the [tidyverse](https://www.tidyverse.org/).
29+
30+
Besides the interactive data wrangling use cases, R is also a capable scripting language from the command line, and has powerful web server frameworks for building interactive applications or publishing APIs with minimal effort. This post naturally ties into these frameworks. So let's dive right into how to turn your first R script into a serverless function using `faas-cli` templates.
31+
32+
### The R templates
33+
34+
Use the [`faas-cli`](https://github.com/openfaas/faas-cli) and pull R templates:
35+
36+
```bash
37+
faas-cli template pull \
38+
https://github.com/analythium/openfaas-rstats-templates
39+
```
40+
41+
Now `faas-cli new --list` should give you a list with the available R/rstats templates to choose from (rstats refers to the #rstats Twitter hashtag used for R related posts). The templates differ with respect to the Docker base image, the OpenFaaS watchdog type, and the server framework used.
42+
43+
You can choose between the following base images:
44+
45+
- Debian-based `rocker/r-base` Docker image from the [rocker](https://github.com/rocker-org/rocker/tree/master/r-base) project for bleeding edge,
46+
- Ubuntu-based `rocker/r-ubuntu` Docker image from the [rocker](https://github.com/rocker-org/rocker/tree/master/r-ubuntu) project for long term support (uses [RSPM](https://packagemanager.rstudio.com/client/) binaries for faster R package installs),
47+
- Alpine-based `rhub/r-minimal` Docker image from the [r-hub](https://github.com/r-hub/r-minimal) project for smallest image sizes.
48+
49+
> The use of Docker with R is discussed in the original article introducing the [Rocker](https://journal.r-project.org/archive/2017/RJ-2017-065/RJ-2017-065.pdf) project and also in a recent review of the [Rockerverse](https://journal.r-project.org/archive/2020/RJ-2020-007/RJ-2020-007.pdf), packages and applications for containerization with R.
50+
51+
The template naming follows the pattern `rstats-<base_image>-<server_framework>`. Templates without a server framework (e.g. `rstats-base`) use the classic [watchdog](https://github.com/openfaas/faas/tree/master/watchdog) which passes in the HTTP request via STDIN and reads a HTTP response via STDOUT. The other templates use the he HTTP model of the [of-watchdog](https://github.com/openfaas-incubator/of-watchdog) that provides more control over your HTTP responses and is more performant due to caching and pre-loading data and libraries.
52+
53+
R has an ever increasing number of server frameworks available. There are templates for the following frameworks (R packages): [httpuv](https://CRAN.R-project.org/package=httpuv), [plumber](https://www.rplumber.io/), [fiery](https://CRAN.R-project.org/package=fiery), [beakr](https://CRAN.R-project.org/package=beakr), [ambiorix](https://ambiorix.john-coene.com/). Each of these frameworks have their own pros and cons for building standalone applications. But for our serverless purposes, the most important aspect of picking one comes down to support and ease of use.
54+
55+
In this post I focus on the [plumber](https://www.rplumber.io/) R package and the `rstats-base-plumber` template. Plumber is one of the oldest of these frameworks. It has gained popularity, corporate adoption, and there are many [examples](https://github.com/rstudio/plumber/tree/master/inst/plumber) and tutorials out there to get you started.
56+
57+
### Make a new function
58+
59+
Let's define a few variables then use `faas-cli new` to create a new function called `covid-forecast` based on the `rstats-base-plumber` template:
60+
61+
```bash
62+
# Populate with your registry prefix or Docker Hub username
63+
export OPENFAAS_PREFIX=""
64+
65+
# Populate with your OpenFaaS URL
66+
export OPENFAAS_URL="http://174.138.114.98:8080"
67+
68+
faas-cli new --lang rstats-base-plumber \
69+
covid-forecast --prefix=$OPENFAAS_PREFIX
70+
```
71+
72+
Your folder now should contain the following files:
73+
74+
```bash
75+
# ls
76+
77+
covid-forecast/handler.R
78+
covid-forecast/DESCRIPTION
79+
80+
covid-forecast.yml
81+
```
82+
83+
The `covid-forecast.yml` is the stack file used to configure functions (read more [here](https://docs.openfaas.com/reference/yaml/)). You can now edit the files in the `covid-forecast` folder.
84+
85+
### Time series forecast
86+
87+
I will use [exponential smoothing](https://en.wikipedia.org/wiki/Exponential_smoothing) as a time series forecasting method. The method needs _time series_ data, that is a series of numeric values collected at some interval. I use here daily updated COVID-19 case counts. The [data source](https://github.com/CSSEGISandData/COVID-19) is the Center for Systems Science and Engineering (CSSE) at Johns Hopkins University. The flat files provided by the CSSE are further processed to provide a JSON API (read more about the [API](https://blog.analythium.io/data-integration-and-automated-updates-for-web-applications/) and its [endpoints](https://github.com/analythium/covid-19#readme), or explore the data interactively [here](https://hub.analythium.io/covidapp/)).
88+
89+
### Customize the function
90+
91+
The `covid-forecast/handler.R` contains the actual R code implementing the function logic. You'll see an example for that below. The dependencies required by the handler need to be added to the `covid-forecast/DESCRIPTION` file. See how the dependencies specified in the `DESCRIPTION` file are installed [here](https://github.com/analythium/openfaas-rstats-templates#customize-your-function).
92+
93+
> See [worked examples](https://github.com/analythium/openfaas-rstats-examples) for different use cases. Read more about the [structure of the templates](https://github.com/analythium/openfaas-rstats-templates/tree/master/template#r-rstats-templates-for-openfaas) if advanced tuning is required, e.g. by editing the `Dockerfile`, etc.
94+
95+
Add the forecast R package to the `covid-forecast/DESCRIPTION` file:
96+
97+
```yaml
98+
Package: COVID
99+
Version: 0.0.1
100+
Imports:
101+
forecast
102+
Remotes:
103+
SystemRequirements:
104+
VersionedPackages:
105+
```
106+
107+
Change the `covid-forecast/handler.R` file:
108+
109+
```
110+
library(forecast)
111+
112+
covid_forecast <- function(region, cases, window, last) {
113+
## API endpoint for region in global data set
114+
u <- paste0("https://hub.analythium.io/covid-19/api/v1/regions/", region)
115+
x <- jsonlite::fromJSON(u) # will throw error if region is not found
116+
## check arguments
117+
if (missing(cases))
118+
cases <- "confirmed"
119+
cases <- match.arg(cases, c("confirmed", "deaths"))
120+
if (missing(window))
121+
window <- 14
122+
window <- round(window)
123+
if (window < 1)
124+
stop("window must be > 0")
125+
## time series: daily new cases
126+
y <- pmax(0, diff(x$rawdata[[cases]]))
127+
## dates
128+
z <- as.Date(x$rawdata$date[-1])
129+
## trim time series according to last date
130+
if (!missing(last)) {
131+
last <- min(max(z), as.Date(last))
132+
y <- y[z <= last]
133+
z <- z[z <= last]
134+
} else {
135+
last <- z[length(z)]
136+
}
137+
## fit exponential smoothing model
138+
m <- ets(y)
139+
## forecast based on model and window
140+
f <- forecast(m, h=window)
141+
## processing the forecast object
142+
p <- cbind(Date=seq(last+1, last+window, 1), as.data.frame(f))
143+
p[p < 0] <- 0
144+
as.list(p)
145+
}
146+
147+
#* COVID
148+
#* @get /
149+
function(region, cases, window, last) {
150+
if (!missing(window))
151+
window <- as.numeric(window)
152+
covid_forecast(region, cases, window, last)
153+
}
154+
```
155+
156+
The R script loads the forecast package, defines the `covid_forecast` function with 4 arguments:
157+
158+
- `region`: a region slug value for the API endpoint in global data set (see [available values](https://hub.analythium.io/covid-19/api/v1/regions/)),
159+
- `cases`: one of `"confirmed"` or `"deaths"`,
160+
- `window`: a positive integer giving the forecast horizon in days,
161+
- `last`: last day (`"YYYY-MM-DD"` date format) of the time series to consider.
162+
163+
The function gives the following output in R:
164+
165+
```
166+
covid_forecast("canada-combined", cases="confirmed", window=4, last="2021-02-18")
167+
# $Date
168+
# [1] "2021-02-19" "2021-02-20" "2021-02-21" "2021-02-22"
169+
# $`Point Forecast`
170+
# [1] 2861.592 2871.802 2879.980 2886.529
171+
# $`Lo 80`
172+
# [1] 1694.809 1695.439 1686.198 1667.680
173+
# $`Hi 80`
174+
# [1] 4028.375 4048.165 4073.761 4105.377
175+
# $`Lo 95`
176+
# [1] 1077.152 1072.711 1054.249 1022.461
177+
# $`Hi 95`
178+
# [1] 4646.033 4670.894 4705.710 4750.596
179+
```
180+
181+
The result of the call is a list with six elements, all elements are vectors of length 4 which is our time window. The `Date` element gives the days of the forecast, the `Point Forecast` is the expected value of the prediction, whereas the lower (`Lo`) and upper (`Hi`) prediction intervals represent the uncertainty around the point forecast. The 80% interval (within the `Lo 80` and `Hi 80` bound) and the 95% interval means that the 80% or 95% of the future observations will fall inside that range, respectively.
182+
183+
The following plot combines the historical daily case counts and the 30-day forecast for Canada. The point forecast is the white line, the 80% and 95% forecast intervals are the blue shaded areas. I made two forecasts, the first on December 1st, 2020, the second on February 18th, 2021:
184+
185+
![COVID-19 Canada](/images/2021-05-r/covid-canada-2021-02-18.png)
186+
187+
The last part of the script defines the Plumber endpoint `/` for a GET request. One of the nicest features of Plumber is that you can create a web API by [decorating the R source code](https://www.rplumber.io/articles/quickstart.html) with special `#*` comments. These annotations will tell Plumber how to handle the requests, what kind of parsers and formatters to use, etc. The current setup will treat the function arguments as URL parameters. The default content type for the response is JSON, thus we do not need to specify it.
188+
189+
```
190+
#* COVID
191+
#* @get /
192+
function(region, cases, window, last) {
193+
if (!missing(window))
194+
window <- as.numeric(window)
195+
covid_forecast(region, cases, window, last)
196+
}
197+
```
198+
199+
The `covid_forecast` arguments can be missing except for region. This makes the corresponding URL parameters optional. We have to remember that URL form encoded parameters will be of type character, thus checking type and making appropriate type conversions is necessary (i.e. `as.numeric()` for the `window` argument).
200+
201+
### Build, push, and deploy the function
202+
203+
Now you can use `faas-cli up` to build, push, and deploy the COVID-19 forecast function to your OpenFaaS cluster:
204+
205+
```bash
206+
faas-cli up -f covid-forecast.yml
207+
```
208+
209+
Test the function's deployed instance with curl:
210+
211+
```bash
212+
curl -X GET -G \
213+
$OPENFAAS_URL/function/covid-forecast \
214+
-d region=canada-combined \
215+
-d cases=confirmed \
216+
-d window=4 \
217+
- last=2021-02-18
218+
```
219+
220+
Or simply by visiting the URL `$OPENFAAS_URL/function/covid-forecast?region=canada-combined&window=4&last=2021-02-18`.
221+
222+
The output should be something like this:
223+
224+
```bash
225+
{
226+
"Date":["2021-02-19","2021-02-20","2021-02-21","2021-02-22"],
227+
"Point Forecast":[2861.5922,2871.8024,2879.9795,2886.5285],
228+
"Lo 80":[1694.8092,1695.4395,1686.1983,1667.6804],
229+
"Hi 80":[4028.3753,4048.1652,4073.7608,4105.3767],
230+
"Lo 95":[1077.1515,1072.7106,1054.2487,1022.4611],
231+
"Hi 95":[4646.0329,4670.8941,4705.7104,4750.596]
232+
}
233+
```
234+
235+
### Wrapping up
236+
237+
In this post I showed how to use the R templates for OpenFaaS. We built a serverless function that consumes data from an external API, fits exponential smoothing model, and makes a forecast. The data API with the forecasting function can be added to web applications to provide timely updates on the fly. Here are some resources for taking you further:
238+
239+
- [Learn about alternative ways of passing parameters to the COVID-19 function](https://github.com/analythium/openfaas-rstats-examples/tree/main/02-time-series-forecast)
240+
- [See the list of available R templates for OpenFaaS](https://github.com/analythium/openfaas-rstats-templates#readme)
241+
- [Check out other R examples with OpenFaaS](https://github.com/analythium/openfaas-rstats-examples)
242+
243+
Now you might ask why you should care about R in a serverless landscape. R is being used by data science teams. The OpenFaaS templates I presented here can reduce time to production by wrapping R code into serverless functions or microservices without significant overhead. If you are an R user, go ahead and try the templates with one of your use cases. If you are not an R user but this introduction piqued your interest, you can find great introductory courses on [freeCodeCamp](https://www.freecodecamp.org/news/tag/r-programming/). The [_R for data science_](https://r4ds.had.co.nz/) book gives a concise and modern overview of working with data in R.

0 commit comments

Comments
 (0)