Rook

As I said in my last post, I am working on setting up a statistical web service using R.  I decided to use the Rook library to do so and wanted to give a brief overview of how Rook works for others who might be interested.

The best way to learn is often to just dig right in and go line by line, so here is a simple rook application:

require('Rook')

library(Rook)
library(rjson)

rook = Rhttpd$new()
rook$add(
  name ="summarize",
  app = function(env) {
    req = Rook::Request$new(env)
    
    numbers = as.numeric(unlist(strsplit(req$params()$numbers, ",")))
    
    results = list()
    results$mean = mean(numbers)
    results$sd = sd(numbers)

    res = Rook::Response$new()
    res$write(toJSON(results))
    res$finish()
  }
)

rook$browse("summarize")

view raw rookexample.R This Gist brought to you by GitHub.

Line 6 creates a new rook webserver object.  This is what will respond to HTTP requests from the browser.

Line 7 adds an “application” to the webserver.  When you add an application to a Rook server you need to name a route and specify what should happen when a user requests that action.  The route is specified by line 8 and tells the Rook server that when a user requests “summarize” it should execute the code specified in lines 9-21.  For some reason Rook prefaces all routes with the word “custom”, so the url to access the route we specified would be http://server:port/custom/summarize

The interesting part of the application occurs in the function that is assigned to app on line 9.  Rook wraps the parameters of the HTTP request in some nice accessors which can be used as seen in line 10.  While the docs specify all of the information available, the important part of the HTTP request for our app is the params() method.  This returns the union of any variables passed via query string and POST.  For the rails developers it is exactly the Rails params hash.

Line 12 parses the input.  This application is expecting an array of numbers separated by commas assigned to the numbers parameter.  Note that if this isn’t specified the app will break in its current state.

After parsing the input parameters we compute some simple summary statistics on this array of numbers and store them in the list results (14-16).

Rook uses the Rook::Response object to fashion a proper HTTP response.  After instantiating the response on line 18, we call the write() method on the response object.  This sends whatever string it is passed to the output stream which is returned to the requestor (in our case the web browser).  Note that I am returning the results in JSON format and should probably set HTTP headers as well if I was going to deploy this to production.  Line 20 flushes the output stream and returns it to the requestor, call this when you are done constructing your response.

Finally, to start our server and see the thing in action we can use the browse() method (line 24).  We are specifying the action that we want to browse to as the parameter.  This should pop open a web browser pointing to your Rook application–and you should get an error:

Error in strsplit(req$params()$numbers, ",") : non-character argument

This is because we didn’t validate the input and our application is expecting an array of numbers.  So, lets pass them through the query string.  Append the following to the URL in your browser: “?numbers=1,2,3,4,5″ and refresh.  No you should get the following:

{"mean":3,"sd":1.58113883008419}

And you have a functioning Rook server!

If you want to add other functionality you can just make addition add() calls on the rook object and the new applications will be added.  If you want to change the functionality of an existing application make sure that you remove (rook$remove(‘summarize’)) it and then re-add it (or just restart everything).

Rook and R Webservices

Recently I have been working on setting up a webservice that does some non trivial statistical work.  Normally, my go to when building web services is Ruby/Rails due to ease of use, then I offload anything computationally intensive to something more optimized (e.g. a C or Java application on the same box).  In this case however, partly because of my co-author’s skill, partly discipline norms, and a whole lot of R being awesome for this sort of thing, the statistical work is going to be done in R.

While it would have been possible to still build the webservice wrapper in Ruby and then either use one of the existing Ruby wrappers for R (or even spinning up an R process on its own), I wanted to see if I could build the whole thing in R.  As is almost always the case, I was not the first person to think of this, and most of the hard work has already been done.

Rook is an R package on CRAN written by Jeffrey Horner.  For those of you familiar with Ruby and Rack, Rook is very similar.  It provides an interface, using R’s built in rApache webserver, to handle http requests, handle routing, etc.  The more I read about it, the more I was convinced that it was a great solution to the problem that I was working on.  Now if only I get it to run on Heroku….

Well, running Rook on Heroku was surprisingly simple thanks to Noah Lorang’s example which you can find here.

So, how do you get started?  Almost everything that you’ll need is in the README in Noah’s repository, but there are a couple of tricky things to note.

First make sure that you have a Heroku account.  It is free to sign up and you get one free full-time process per project (one single web server in our case).  There are numerous resources (including their excellent help files) to get you through this part.

Next you can either walk through the instructions in Noah’s example (which I ended up doing), or you can do the much easier thing by cloning his repository.  If you do this, then you should be able to deploy it directly.

After you get a running instance of Rook, you will want to write some R code.  To run your own custom R script, replace the “/app/demo.R” in rackup file (config.ru) with the path of your script.  Otherwise, you can just put your code in demo.R.

Because Heroku is a read-only file system, you will need to include any R packages in your source tree so that they are “installed” when you deploy.  Initially you will just have R and Rook installed (if you cloned the existing project).  Because some packages require native compilation, you really should do that compilation on one of heroku’s servers.  In order to do this, you need to ssh into your app server:

heroku run bash

Once you are in the bash shell on your app server you can load R.  From there install any packages that will be dependencies for you project.  When you exit the R shell, do not log out of the ssh session.  If you do the app will reset and you will need to start over (remember it is read only so the file system changes persist only as long as your session).  You then need to figure out how you want to get these changes off of your heroku instance.  First zip them up (I zipped up the whole bin directoy):

tar -cvzf mybin.tar.gz ./bin

Then you can either scp it off of the machine (as Noah suggests):

scp mybin.tar.gz me@myserver.com:~/myproject/bin.tar.gz

Or, if you do not have access to a destination that you can scp (heroku does not have ftp installed), you can do the roundabout method of setting up github as a remote, checking in the tarball, pushing it to github and then cloning that repository locally.  Once you have the tarball on your machine, just untar it into your repositories bin directory, checkin, and deploy.  You will now have access to those packages in R.

I’ll writeup how to actually use Rook in my next post.

 

Exponential growth and resource consumption

In August, while one the road moving to Duke, I heard a great interview on NPR with David Suzuki.  During this interview he talked about the relationship between anything that grows exponentially and the resources that it consumes.  In particular he focused on how we are likely to misperceive the remaining level of resources because humans are bad at understanding exponential growth (see anything by Kurzweil).

I wanted to retell his analogy because it has really stuck with me and then provide a visualization that I found helpful.

Imagine 2 bacteria in a petri dish.  The petri dish is many, many times bigger than they are.  To keep the math simple lets say that it is 1 billion times larger.  The bacteria in the dish look around and realize that they have a bounty of agar on which to live and thus anticipate much prosperity.  So the bacteria, being bacteria, replicate.  After 1 unit of time (lets say they replicate every minute), there are now 4 bacteria.  These 4 bacteria look around and see that they have this vast petri dish at their disposal and thus keep replicating.  Since replicating is fun, this goes on for a while.  Eventually after 20 turns of doubling in size there are 1,048,576 (2^{20} ) bacteria.  They realize that they have used up just more than 0.1% of their resources and there is much rejoicing and still more replicating.

By the time that 29 minutes have passed there are now 536,870,912 bacteria.  They have used over half of their resources, but they look around and see that they still have half of them left and it took them 29 turns to get here, so they have to have a little time to figure out how to get out of this mess.  On the 30th turn, the population doubles again and now there are 1,073,741,824 and they are out of room.  When a population grows by doubling in size, it by definition will go from 50% resource utilization to 100% in one time period.  That was both obvious (mathematically) and shocking to me.  How fast is the human population growing?  How close are we to running out of resources on earth?

Well, if there was any doubt about whether human population growth was exponential here is a graph of estimated growth over the past 12,000 years (courtesy of wikipedia):

Human Growth Chart

And the CIA factbook estimates the current population growth to be about %1.092 year over year.

Here is a graph that just visualizes the thought experiment proposed by Suzuki:

The point of this graph is just to show how quickly the resource level can plunge to zero and how as an inductive species it is easy to fall into the trap of not understanding the rate at which exponential growth can take off by using historical data to improperly predict the future.

Note: For the graph I just picked a time period of 1000 and then decided to drive it to 0 at that point.  Given that there is a finite amount of resources you will get the same graph form, one way or the other after fixing the resource size.  Below is a gist in R to play around with and see how the curve forms change under different growth rates and how the warning time (as a percentage of the species’ history) shrinks as the size of the resource goes up.

rm(list = ls()) #Clear the workspace
library(ggplot2)

time = seq(1:1000)
starting_population = 2
reproduction_rate = 1.0192

population = cbind(time, starting_population*reproduction_rate^time)

starting_resources = population[time==length(time)-1][2]
resources = cbind(time, starting_resources - population[,2])

data = as.data.frame(rbind(population, resources))
# data set indicator
data$ds <- factor(rep(1:2, c(length(time), length(time))))
data$Legend <- factor(rep(c("Population", "Resources"), c(length(time), length(time))))

plot1 = ggplot(data, aes(x=time, y=V2, group=ds, color=Legend)) +
  geom_line(factor=data$ds) +
  scale_y_continuous('Count', limits=c(0, starting_resources)) +
  scale_x_continuous("Time")
print(plot1)
view raw gistfile1.r This Gist brought to you by GitHub.