Skip to main content

memory - How to force Mathematica to clean up the cache



(see the bottom of this question for the MWE)


I'm working with a set of numerical data: numerous (a few thousands) files in the style of list of vectors (quadruplets x, y, vx, vy). Files are named as v1.txt, v2.txt, ..., vk.txt, where k is a few thousands. I am using For loop in Mathematica, in each cycle several steps are performed:


1) load vi.txt
2) make list of pairs of pairs from it (in the form of {{x1, y1},{v1x, v1y}, ...})
3) construct absolute value of the vector field ({{x1, y1}, norm of {v1x, v1y}, ...})
4) Make list density plot of the absolute value list
5) Make list stream plot of the pairs of pairs
6) export both.

The problem is that after about 200 cycles, Mathematica sucks up all the physical memory available in my machine and the kernel crashes. I tried using:



1) $HistoryLength = 0
2) ClearSystemCache[] after every cycle
3) ClearAll[(plots, data)] after every cycle
4) all of the above combined

up to no avail. What am I doing wrong? What should I do to tell Mathematica to get rid of the images from the previous step, so it won't suck up all of my RAM? The code I'm using is as follows:


$HistoryLength = 0;
SetDirectory[NotebookDirectory[]];
Monitor[
For[i = 1, i <= 5383, i++,

v = Partition[
Partition[
Flatten@Import["output\\results\\v" <> ToString[i] <> ".txt",
"Table"], 2], 2];
Absv = Table[{v[[i, 1, 1]], v[[i, 1, 2]], Norm[v[[i, 2]]]}, {i, 1,
Length@v}];
LDP = ListDensityPlot[Absv, PlotRange -> Full,
ColorFunction -> ColorData[{"SolarColors", "Reverse"}],
MaxPlotPoints -> 100, ImageSize -> 1000];
LSP = ListStreamPlot[v, StreamStyle -> White, StreamPoints -> Fine,

StreamScale -> 0.1, ImageSize -> 1000];
Export["output\\results\\img" <> ToString[i] <> ".png", LDP];
Export["output\\results\\img_stream" <> ToString[i] <> ".png", Show[LDP, LSP]];
ClearSystemCache[];
ClearAll[v,Absv,LDP,LSP];
], i]

Why is Mathematica completely ignoring all statements $HistoryLength, ClearSystemCache and ClearAll?


MWE


This is a minimal working example demonstrating my problem (not depending on any mysterious data that I have on my HDD):



MemoryInUse[]
Do[
ListStreamPlot@
Table[{{Random[], Random[]}, {Random[], Random[]}}, 1000];
ClearSystemCache[],
{i, 10}
];
MemoryInUse[]

Together with Henrik we figured out ListStreamPlot is the culprit, therefore I reported this as a bug.




Answer



This is also not an answer (I think you found the culprit and it needs to be solved by WRI) but a suggestion for a workaround. The idea is to run the memory leaking code in an extra kernel and restart that kernel every once in a while. Using the parallel functionality of current Mathematica releases this is pretty simple and by choosing an appropriate value for the number of parallel kernels you could even take advantage of parallelism if desired.


Here is a simple example based on your minimal working example which demonstrates the idea and shows that the master kernel will not accumulate any memory:


LaunchKernels[1];
Print[MemoryInUse[]];
calcsPerKernel = 3;
Do[
With[{fname = "plot-" <> ToString[i] <> ".png"},
ParallelEvaluate[
Export[

FileNameJoin[{$HomeDirectory, "Desktop", fname}],
ListStreamPlot[
Table[{{Random[], Random[]}, {Random[], Random[]}}, 1000]
]
];
Print[MemoryInUse[]];
]
];
If[Mod[i, calcsPerKernel] == 0,
CloseKernels[];

ClearSystemCache[];
LaunchKernels[1];
];
,
{i, 10}
];
CloseKernels[];
ClearSystemCache[];
Print[MemoryInUse[]];


The idea for a more general and flexible approach is as follows:



  • use LaunchKernels to launch the desired number of parallel kernels

  • use ParallelSubmit to pass the computations (e.g. per file) to the parallel kernel(s)

  • use WaitNext to get the result of a computation from the other kernel(s).

  • use CloseKernels[kernelid] and LaunchKernels to restart a/the parallel kernels


As it is very difficult to completely avoid memory leaks in sufficient complex Mathematica code I think this is a technique that will be helpful in many situations. We are using this approach regularly for computations that run for several days and have found that it works very reliable. Unlike some other parts of Mathematica the parallel toolkit seems to work very stable and reliable even on a larger scale.


Comments

Popular posts from this blog

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1.