Sonntag, 26. Mai 2013

Using R to visualize geo optimization algorithms

Site optimization is the process of finding an optimal location for a plant or a warehouse to minimize transportation costs and duration. A simple model only consists of one good and no restrictions regarding transportation capacities or delivery time. The optimizing algorithms are often hard to understand. Fortunately, R is a great tool to make them more comprehensible.


The basic math
A basic contineous optimization problem is to deliver goods to $n$ customers. Every customer has a individual demand $a_j$ and is approached directly from our warehouse. The single routes have a length of $d_j$. The objective function to be minimized is:
$$min(\sum^{n}_{j=1} a_j \cdot d_j)$$ 
How can on calculate distances? Typical distance measures for flat surfaces most of you are probably familiar with are Taxicab distance and Euclidean distanceWe will calculate spherical distances to get a better solution for large routes: $$\\d_{a,b} = arccos[sin(y_a)\cdot sin(y_b)+cos(y_a)\cdot cos(y_b)\cdot cos(x_a-x_b)] \cdot R\\$$ R denotes the Earth radius: ~ 6,370 km. Keep in mind:
  • ...To use geographical coordinates in the form of decimal degrees
  • ... To transform them to radian units (by multiplying pi/180).

How to optimize
We will use an iterative way for optimizing:
  1. set an initial warehouse location: $x_{start}$ and $y_{start}$ 
  2. for every iteration the current warehouse location $(x_w, y_w)$ is calculated by: $$x_w=\frac{\sum_{j=1}^{n}{a_j \cdot \overline{x}/d_j}}{\sum_{j=1}^{n}{a_j/d_j}}  \quad \quad y_w=\frac{\sum_{j=1}^{n}{a_j \cdot \overline{y}/d_j}}{\sum_{j=1}^{n}{a_j/d_j}}$$


Results
Red circles are customer locations. Their surface area represents the individual demands. The single iterations start with dark blue circles and end with the final warehouse location, colored in green.

Click here to download the data file. Below the code:






Samstag, 29. Dezember 2012

Men who stare at needles

Buffon's needle problem is a question first posed in the 18th century by Georges-Louis Leclerc, Comte de Buffon:

What is the probability that a needle thrown at a lined sheet of paper will cross a line?

This problem can be used to estimate π. If we set the nail size and the line distance = 1, the estimator can be calculated by:
$$\widehat{\pi}=\frac{2\cdot throws}{hits}$$
Because throwing 80.000 needles can be annoying, I created an implementation in R. The result took over two hours to render an is attached to this post. It was generated by saving multiple GIF files and combining them to a movie. Red needles are hits, the heading represents the current approximation of π.




After loading the function you can start a simulation by typing:

 buffon([number of simulations], [number of needles], [c(seeds)])

The following command will create one simulation with 100 needles: And here's the function:

For more information on R and what to do with it visit: www.r-bloggers.com