Skip to main content

Circle packing in R (again)

Back in 2010 I posted some R code for circle packing. Now, just five years later, I've ported the code to Rcpp and created a little package which you can find at GitHub.

The main function is circleLayout which takes a set of overlapping circles and tries to find a non-overlapping arrangement for them. Here's an example:


And here's the code:

# Create some random circles, positioned within the central portion
# of a bounding square, with smaller circles being more common than
# larger ones.

ncircles <- 200
limits <- c(-50, 50)
inset <- diff(limits) / 3
rmax <- 20

xyr <- data.frame(
  x = runif(ncircles, min(limits) + inset, max(limits) - inset),
  y = runif(ncircles, min(limits) + inset, max(limits) - inset),
  r = rbeta(ncircles, 1, 10) * rmax)

# Next, we use the `circleLayout` function to try to find a non-overlapping
# arrangement, allowing the circles to occupy any part of the bounding square.
# The returned value is a list with elements for the layout and the number
# of iterations performed.

library(packcircles)

res <- circleLayout(xyr, limits, limits, maxiter = 1000)
cat(res$niter, "iterations performed")

# Now draw the before and after layouts with ggplot

library(ggplot2)
library(gridExtra)

## plot data for the `before` layout
dat.before <- circlePlotData(xyr)

## plot dta for the `after` layout returned by circleLayout
dat.after <- circlePlotData(res$layout)

doPlot <- function(dat, title)
  ggplot(dat) + 
  geom_polygon(aes(x, y, group=id), colour="brown", fill="burlywood", alpha=0.3) +
  coord_equal(xlim=limits, ylim=limits) +
  theme_bw() +
  theme(axis.text=element_blank(),
        axis.ticks=element_blank(),
        axis.title=element_blank()) +
  labs(title=title)

grid.arrange(
  doPlot(dat.before, "before"),
  doPlot(dat.after, "after"),
  nrow=1)

Comments

  1. Wow! It's magic. Thank you for posting this.

    This is an interesting problem to solve in code. Very cool.

    ReplyDelete
    Replies
    1. You're welcome Phillip. If you try it out let me know it goes.

      Delete
  2. I'm having issues compiling the package:

    * installing *source* package 'packcircles' ...
    ** libs
    Warning: running command 'make -f "C:/PROGRA~1/R/R-31~1.3/etc/x64/Makeconf" -f "C:/PROGRA~1/R/R-31~1.3/share/make/winshlib.mk" SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)' SHLIB="packcircles.dll" WIN=64 TCLBIN=64 OBJECTS="RcppExports.o packcircles.o"' had status 127
    ERROR: compilation failed for package 'packcircles'

    ReplyDelete
    Replies
    1. Hi Jim,
      Was that the entire error trace ? I'm building on a windows 7 box with Rtools 3.1.0.1942 and devtools 1.7.0.

      In case I'd missed including something essential in the repo, I just tried cloning it into a new folder, opening the project in RStudio and building it from there. There were no errors.

      If you can't get it to work I could send you a zip file of the built package to install.

      Delete
    2. I also just tried doing `devtools::install_github("mbedward/packcircles")` which also worked. For the moment I'm guessing the problem has to do with your local setup.

      Delete

Post a Comment

Popular posts from this blog

Fitting an ellipse to point data

Some time ago I wrote an R function to fit an ellipse to point data, using an algorithm developed by Radim Halíř and Jan Flusser1 in Matlab, and posted it to the r-help list. The implementation was a bit hacky, returning odd results for some data. A couple of days ago, an email arrived from John Minter asking for a pointer to the original code. I replied with a link and mentioned that I'd be interested to know if John made any improvements to the code. About ten minutes later, John emailed again with a much improved version ! Not only is it more reliable, but also more efficient. So with many thanks to John, here is the improved code: fit.ellipse <- function (x, y = NULL) { # from: # http://r.789695.n4.nabble.com/Fitting-a-half-ellipse-curve-tp2719037p2720560.html # # Least squares fitting of an ellipse to point data # using the algorithm described in: # Radim Halir & Jan Flusser. 1998. # Numerically stable direct least squares fitting of ellipses. …

Build an application plus a separate library uber-jar using Maven

I've been working on a small Java application with a colleague to simulate animal movements and look at the efficiency of different survey methods. It uses the GeoTools library to support map projections and shapefile output. GeoTools is great but comes at a cost in terms of size: the jar for our little application alone is less than 50kb but bundling it with GeoTools and its dependencies blows that out to 20Mb.

The application code has been changing on a daily basis as we explore ideas, add features and fix bugs. Working with my colleague at a distance, over a fairly feeble internet connection, I wanted to package the static libraries and the volatile application into separate jars so that he only needed to download the former once (another option would have been for my colleague to set up a local Maven repository but for various reasons this was impractical).

A slight complication with bundling GeoTools modules into a single jar (aka uber-jar) is that individual modules make ext…

Circle packing with R

To visualize the results of a simulation model of woodland trees within R, I needed an algorithm that could arrange a large number of circles within a rectangle such that no two circles overlapped by more than a specified amount. A colleague had approached this problem earlier by sorting the circles in order of descending size, then randomly dropping each one into the rectangle repeatedly until it landed in a position with acceptable overlap.

I suspected a faster and more robust algorithm could be constructed using some kind of "jiggling the circles" approach. Luckily for me, I discovered that Sean McCullough had written a really nice example of circles packing into a cluster using the Processing language. Sean's program is based on an iterative pair-repulsion algorithm in which overlapping circles move away from each other. Based on this, and modifying the algorithm a little, I came up with an R function to produce constrained random layouts of a given set of circles. He…