I have a bottleneck problem involving a function call with symbolic derivatives.
I don't have much experience with Mathematica (or any dynamic language) and I'm certain that the way I've set this up is about as basic as it gets, so anyone Mathematica -fluent will probably spot several "obvious" changes that should speed things up. Please tell me what these are! There are probably a host of RTFM suggestions for speeding up calls to this function (which I welcome) but specific suggestions would be great too.
The quantity mainTerm[l, m, r, Theta, Phi, FactorA, FactorB] gets called many times in a nested loop of (r,Theta,Phi) coordinates and (l,m) iterations; so this involves calling spherical harmonics/Hankel functions (and calculating their derivatives and double derivatives) ad nauseum. When I expanded out the derivatives/double derivatives down to the level of hypergeometric basis functions (to avoid doing calculus on the fly), this seemed to slow things down, which has me baffled.
The block shown below is mainly to illustrate the complexity of the function I need to compute (i.e., I'm hoping for advice on how to compile or otherwise speed up functions when analytic derivatives might need to be calculated on the fly, not quantitative // AbsoluteTiming comparisons):
k = somevalue; preAAA := FactorA*(SphericalHankelH1[l, k*r]* D[D[SphericalHarmonicY[l,m,Theta,Phi],Theta]*Sin[Theta],Theta] + SphericalHankelH1[l, k*r]*D[D[SphericalHarmonicY[l,m,Theta,Phi],Phi]]); AAA := Expand[preRadial]; BBB := (FactorB*SphericalHankelH1[l, k*r])*D[SphericalHarmonicY[l,m,Theta,Phi],Phi] - FactorA*D[SphericalHarmonicY[l,m,Theta,Phi],Theta]* D[r*SphericalHankelH1[l, k*r],r]; CCC := (FactorB*SphericalHankelH1[l, k*r])*D[SphericalHarmonicY[l,m,Theta,Phi],Theta] - FactorA*D[SphericalHarmonicY[l,m,Theta,Phi],Phi]* D[r*SphericalHankelH1[l, k*r],r]; mainTerm[l_,m_,r_,Theta_,Phi_,FactorA_,FactorB_] = AAA + BBB + CCC; Subequently, inside the (l, m) loop I set storeValue[[l, m]] = mainTerm[l, m, ...]. When I compile AAA, BBB and CCC individually and set storeValue this way, the code runs slower (which I am confused about).
I'm aware that compiling my component terms could (should?) speed things up, and I've tried various approaches to that end (with/without compiling to C, with/without explicitly defining Reals and Integers, etc.) but none of them had much effect and some slowed things down.
Any suggestions on how better to set this up for a large number of nested function calls?