I have defined a function $f_{a}(\boldsymbol{r})$ that gives a finite discrete approximation of a continuous function $f(\boldsymbol{r})$ that represents a 3D object. Here, the object is a sphere of radius equal to $R$ and value of $f(\boldsymbol{r})$ is $0$ anywhere outside the sphere.
The approximation function $f_{a}(\boldsymbol{r})$ is defined as:
$$f_{a}(\boldsymbol{r}) = \sum_{n=1}^{N} \theta_n \phi_n(\boldsymbol{r}) \tag{1} $$
Where, $$\boldsymbol{r}=(x,y,z),\ \boldsymbol{r_n} = (n_x \epsilon, n_y \epsilon, n_z \epsilon),\ \boldsymbol{n}= (n_x, n_y , n_z) \in (\mathbb{Z},\mathbb{Z},\mathbb{Z})\equiv \mathbb{Z^3},$$
$$\phi_n(\boldsymbol{r}) = rect \left(\frac{\boldsymbol{r}-\boldsymbol{r_n}}{\epsilon }\right ) \tag{2} $$
$$\theta_n = \int_{\infty }{} {\mathrm{d^3} r} \ \delta(\boldsymbol{r}-\boldsymbol{r_n})f(\boldsymbol{r}) = f(\boldsymbol{r_n}) \tag{3} $$
$$f(\boldsymbol{r})= \begin{cases} 1 \ , & \sqrt{x^2+y^2+z^2}\leq R \\ 0 \ , & otherwise \end{cases} \tag{4}$$
The code for above equations:
Remove[ncoords, ObjFunc];
ncoords = Tuples[Range[-5, 5], 3];
ObjFunc =
Compile[{{x, _Real, 0}, {y, _Real, 0}, {z, _Real, 0}},
Module[{Phi, f, Theta, fa},
Phi[x, y, z, nx_, ny_, nz_] =
UnitBox[(x - nx*\[Epsilon])/\[Epsilon],
(y - ny*\[Epsilon])/\[Epsilon],
(z - nz*\[Epsilon])/\[Epsilon]] /. {\[Epsilon] -> 0.4};
f[x_, y_, z_] = Piecewise[{{1, Sqrt[x^2 + y^2 + z^2] <= R}}, 0]/. {R -> 2};
Theta[ nx_, ny_, nz_] = f[nx*\[Epsilon], ny*\[Epsilon],
nz*\[Epsilon]] /. {\[Epsilon] -> 0.4};
fa[x, y, z] = Sum[Theta[ncoords[[n, 1]], ncoords[[n, 2]], ncoords[[n, 3]]]*
Phi[x, y, z, ncoords[[n, 1]], ncoords[[n, 2]],
ncoords[[n, 3]]], {n, 1, Length[ncoords]}]
],
RuntimeAttributes -> {Listable}, CompilationTarget -> "C", Parallelization -> True, RuntimeOptions -> "Speed"];
Image3D[Parallelize[Table[ObjFunc[x, y, z], {x, -2, 2, 0.4}, {y, -2, 2, 0.4}, {z, -2, 2, 0.4}]]] // AbsoluteTiming
When I increase the range of ncoodrs
or reduce the interval size $\epsilon$ while evaluating Table[ObjFunc[x, y, z], {x, -2, 2, \[Epsilon]}, {y, -2, 2, \[Epsilon]}, {z, -2, 2, \[Epsilon]}]
, it takes a lot of time to complete. The above image of the approximated object took 41.878
sec in my system, which is a lot of time for a bad approximation. I can get better approximation of the object by increaseing the Range
of ncoords
and by taking smaller values of $\epsilon$ but it takes a lot of time. How can I boost the perfomance of this code?. Any suggestion on the mathematical approach (equations used) will also help.