I am trying to optimize a function which involves NDSolveValue, but I cannot complete the optimization due to a memory leak. As mentioned in Memory leak with NDSolve, the memory leak might be due to a bug, but I am trying to break down my problem to see if I am doing some mistakes. I am using Mathematica 11.0.1.
To illustrate my point, let us solve the 2D heat equation $\nabla \cdot \left[ \kappa ( \boldsymbol{r} ) \nabla T( \boldsymbol{r} ) \right] = \partial_x \left[ \kappa ( \boldsymbol{r} ) \partial_x T( \boldsymbol{r} ) \right] + \partial_y \left[ \kappa ( \boldsymbol{r} ) \partial_y T( \boldsymbol{r} ) \right] = 0$ using some arbitrary region, boundary conditions and a piecewise function $\kappa$:
area = Rectangle[{0, 0}, {10, 10}];
kappa[x_, y_] := Piecewise[{{5, y <= 5}, {10, 5 < y}}];
op = D[kappa[x, y]*D[u[x, y], x], x] + D[kappa[x, y]*D[u[x, y], y], y];
sol = NDSolveValue[
{op == 0,
DirichletCondition[u[x, y] == 10, y == 0],
DirichletCondition[u[x, y] == 0, y == 10 && x < 2]},
u,
{x, y} ∈ area];
DensityPlot[sol[x, y], {x, y} ∈ area, Mesh -> None,
ColorFunction -> "TemperatureMap", PlotRange -> All,
PlotLegends -> Automatic]
with the output:
I am completely satisfied with the result, but some global variables have been generated during the calculation:
Names["Global`*"]
with the output:
{area, kappa, op, s5, s6, s7, s8, sol, u, x, y}
I do not understand where these s5, s6, s7 and s8 come from! After running the code multiple times, more and more global variables are generated. After five times, the output is:
{area, kappa, op, s12, s13, s14, s15, s18, s19, s20, s21, s24, s25, s26, s27, s30, s31, s32, s33, s5, s6, s7, s8, sol, u, x, y, y$}
My question is if this can cause me any memory problems? In my actual code, around 80 global variables are generated for each calculation and I guess that around 1000 calculations has to be done during my optimization. I have tried to use Remove[s5,s6,...], but it does not seem to release any memory, but maybe this large number of variables causes me some other problems?
If I define kappa to be a constant, no additional variables are generated. What can I do to the code to avoid the generation of these global variables?
Piecewise[]
function. $\endgroup$ – Feyre Oct 25 '16 at 11:59NDSolve
creates symbols withUnique["s"]
in processing the discontinuities. It should be considered a bug. It shouldn't be causing a significant memory leak, though, since it appears they are used only as symbols. $\endgroup$ – Michael E2 Oct 25 '16 at 12:26