How can I make compilation to go through with a module inside module? I tried this, failed, a few other ways failed too.
f = Compile[
{{σt, _Real, 1}, {sρ, _Complex, 1}, {dt, _Real, 1}, {x, _Real}, {nnt, _Integer},
{dqt, _Real}, {divt, _Integer}},
Module[{temp, dq = dqt, div = divt, j, h},
temp[x_] :=
Module[{kz = 1/2 x, σ = σt, d = dt, i, kp, c, β, r, k, ρ = sρ * 10^-6, nn = nnt},
kp = kz + 0. I;
k = Sqrt[kz^2 - 4 π (ρ[[2]] - ρ[[1]])];
r = (kp - k)/(kp + k) E^(-2 kp k σ[[1]]^2);
c = {{1 + 0. I, r }, {r , 1}};
kp = k;
For[i = 2, i < 2 nn + 2, i++,
If[EvenQ[i],
k = Sqrt[kz^2 - 4 π (ρ[[3]] - ρ[[1]])];
r = (kp - k)/(kp + k) E^(-2 kp k σ[[2]]^2);
β = I kp d[[1]],
k = Sqrt[kz^2 - 4 π (ρ[[2]] - ρ[[1]])];
r = (kp - k)/(kp + k) E^(-2 kp k σ[[3]]^2);
β = I kp d[[2]]
];
c = c.{{E^β, r E^β}, {r E^-β, E^-β}};
(*previous k*)
kp = k
];
Abs[c[[2, 1]]/c[[1, 1]]]^2];
h = 0.0;
For[j = 1, j < div + 1, j++,
h = h + temp[x - dq/2 + dq/div*j]
];
h/div
]
, CompilationTarget -> "C"]
temp
function on its own. You will also want to look at more efficient and idiomatic Mathematica alternatives to explicitFor
loops. $\endgroup$"InlineCompiledFunctions"
and"InlineExternalDefinitions"
suboptions ofCompilationOptions
. $\endgroup$