Hello everyone,
I have a model where I need to generate a large number of variables of the form
r = exp.(Xss[indexes.rSS] .+ X[indexes.r])
rPrime = exp.(Xss[indexes.rSS] .+ XPrime[indexes.r])
w = exp.(Xss[indexes.wSS] .+ X[indexes.w])
wPrime = exp.(Xss[indexes.wSS] .+ XPrime[indexes.w])
within a function and and I’d like to use metaprogramming to not have to do this manually.
At the global scope, I can easily do this with eval()
# Preliminary setup
struct index
r::Int
w::Int
rSS::Int
wSS::Int
end
indexes = index(1,2,1,2)
X = [1.0 2.0]
XSS = [3.0 4.0]
XPrime = [5.0 6.0]
var_names = (:r, :w)
# Create equations
for i in var_names
varnamePrime = Symbol(i, "Prime")
varnameSS = Symbol(i, "SS")
ex = quote
$i = exp.(XSS[indexes.$varnameSS] + X[indexes.$i])
$varnamePrime = exp.(XSS[indexes.$varnameSS] + XPrime[indexes.$i])
end
eval(ex)
end
and it also works with a macro at global scope
macro gen_equations()
ex = quote # initialize expression to append to
temp = 1
end
for i in var_names # loop over variables to generate
varnamePrime = Symbol(i, "Prime")
varnameSS = Symbol(i, "SS")
ex_aux = quote
$i = exp.(XSS[indexes.$varnameSS] + X[indexes.$i])
$varnamePrime = exp.(XSS[indexes.$varnameSS] + XPrime[indexes.$i])
end
append!(ex.args, ex_aux.args) # append to expression
end
return esc(ex)
end
@gen_equations
However, if I put everything in a function
function test_scope()
indexes = index(1,2,1,2)
X = [1.0 2.0]
XSS = [3.0 4.0]
XPrime = [5.0 6.0]
var_names = (:r, :w)
@gen_equations
end
I get an error that UndefVarError: var_names not defined
. My guess is that this is a scoping issue. So I defined the same macro but passed all objects explicitly to the macro
macro gen_equations(var_names, X, XSS, indexes)
...
end
But if I then try to define my function
function test_scope()
indexes = index(1,2,1,2)
X = [1.0 2.0]
XSS = [3.0 4.0]
XPrime = [5.0 6.0]
var_names = (:r, :w)
@gen_equations var_names, X, XSS, indexes
end
I get a MethodError: no method matching @gen_equations(::Expr)
.
Any hints would be greatly appreciated. I’m just starting getting my head around macros and I’m still mostly confused.
Setup is Julia 0.6.4 on MacOS.
Thank you very much,
Benjamin