1
$\begingroup$

let's say I have a set of discrete data of dimension n by n by n, which may represent a scalar field $f(x,y,z), x,y,z\in [-1/2,1/2]$ in Cartesian 3D space. To be specific,

n=64;
data=Table[i+j+k,{i,-n/2,n/2},{j,-n/2,n/2},{k,-n/2,n/2}];

so that $f(i/n,j/n,k/n)\simeq data[[i,j,k]]$. My question is, is there an efficient way to calculate the "spherically integrated" data? i.e., in the continuous form I would like to calculate $$g(r)=\int f(r\sin\theta\cos\phi,r\sin\theta\sin\phi,r\cos\theta)r^2\sin\theta d\theta d\phi$$ In a less efficient way I would write something like

dataSph=Table[0,{l,0,2n}];
For[i=1,i<=n,i++,
  For[j=1,j<=n,j++,
    For[k=1,k<=n,k++,
      For[l=1,l<=2n,l++,
        If[l-1/2<=Sqrt[i^2+j^2+k^2]<l+1/2,dataSph[[l]]+=data[[i,j,k]]]
   ]]]]

or even just interpolate the data into a continuous version. Is there any better way to do the job?

$\endgroup$
3
  • 1
    $\begingroup$ spherical integral can be write such as Integrate[Sqrt[x^2 + y^2 + z^2], Element[{x, y, z}, Sphere[{0, 0, 0}, r]]] $\endgroup$
    – cvgmt
    Aug 24 '20 at 7:38
  • $\begingroup$ You state that $(x,y,z) \in [-\frac{1}{2}, \frac{1}{2}]^3$ yet then compute Sqrt[i^2+j^2+k^2] to determine the "shells". Shouldn't there be an offset involved? E.g. Sqrt[(i-n/2)^2+(j-n/2)^2+(k-n/2)^2] or something similar. $\endgroup$
    – Natas
    Aug 24 '20 at 16:41
  • $\begingroup$ Yes there should be an offset. Thanks! $\endgroup$
    – H. Zhou
    Aug 25 '20 at 9:19
2
$\begingroup$

Just a quick-n-dirty. This finishes your example on my laptop in about 1/3 of a second vs 10 minutes.

idx = Tuples[Range@n, 3];
idxvals = Norm /@ N[idx];
dataSph = ConstantArray[0, 2 n + 1];
For[l = 1, l <= 2 n, l++,
  dataSph[[l]] = 
    Total[Extract[data, 
      Pick[idx, Unitize[Clip[idxvals, l + {-1/2, 1/2}, {0, 0}]], 1]]];
  ];
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.