Sunday, 8 September 2013

Plot Smith Chart in R

Plot Smith Chart in R

I wrote some code in R to generate a Smith Chart using only base graphic.
I am satisfied with the plot itself, but I would like to improve the code.
In particular I am not sure about the 4 lapply calls, and I guess there
should be a more direct way to draw a group of lines in base R.
Below is the code I am using, and the plot it generates. I am new to
stackoverflow, so please let me know if I should include more comments or
provide additional information.
#!/usr/bin/rscript --vanilla
filename='smith_chart.pdf'
pdf(filename, 6, 6)
# given z = r + jx, calculates complex number gamma = (z-1)/(z+1)
mapping <- function(r, x) {z <- complex(real = r, imaginary = x);
(z-1)/(z+1)}
complex_line <- function(a) {lines(Re(a), Im(a), lwd = 0.5)}
plot.new()
plot.window(c(-1, 1), c(-1, 1), asp = 1)
dd <- c(seq(-100, 100, 1), seq(-10, 10, 0.1), seq(-2, 2, 0.02))
dd <- round(dd, digits = 2)
dd <- sort(unique(dd))
smith_grid <- function (value, step) {
# applies conformal mapping to lines having contast r
r_grid <- lapply(seq(0, value, step),
FUN = function(r){mapping(r, dd[dd >= -value & dd <= value])})
# applies conformal mapping to lines having contast x
x_grid <- lapply(seq(-value, value, step),
FUN = function(x){mapping(dd[dd >= 0 & dd <= value], x)})
lapply(r_grid, FUN=complex_line)
lapply(x_grid, FUN=complex_line)
}
smith_grid(50, 10)
smith_grid(10, 1)
smith_grid(2, 0.2)
smith_grid(0.6, 0.1)
dev.off()

No comments:

Post a Comment