Skip to content

Instantly share code, notes, and snippets.

@barryrowlingson
Created May 28, 2014 12:37
Show Gist options
  • Save barryrowlingson/d1d21c537777cfda8178 to your computer and use it in GitHub Desktop.
Save barryrowlingson/d1d21c537777cfda8178 to your computer and use it in GitHub Desktop.
buffer feature to a fixed percentage area increase
abuff <- function(f, percent, precision, maxsteps = 20){
require(rgeos)
A0 = gArea(f)
targetA = A0 + A0 * (percent/100)
e = bbox(f)
w0 = 0
w2 = diff(e[1,])/10 # initial w
## initial expansion until we pass the solution:
repeat{
b1 = gBuffer(f, width=w2)
if(gArea(b1) < targetA){
w2 = w2 * 2
}else{
break
}
}
w1 = (w0 + w2)/2
## solution is between w0 and w2
steps = 1
repeat{
b = gBuffer(f, width=w1)
A = gArea(b)
if(abs(100*(A-targetA)/targetA) < precision){
return(list(steps = steps, poly = b, target=targetA))
}
if(A < targetA){
w0 = w1
w1 = (w1+w2)/2
}
if(A > targetA){
w2 = w1
w1 = (w2+w0)/2
}
steps = steps + 1
if(steps > maxsteps){
return(NA)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment