I just did a model of spatial competition between two species with different competitive ability & dispersal rates on a lattice with variables nrs of individuals per site. To speed it up I tried to use Compile - but I get an error at runtime. It works OK though if I run it uncompiled. Anybody any ideas what I might be doing wrong? My code is
gridsize = 30;
k = 1000;
zeroMatrix[n_, m_] := Table[0, {n}, {m}];
initSpace[n_, m_, k_] := Block[{s},
s = { zeroMatrix[n, m], zeroMatrix[n, m] };
s[[1, 1, 1]] = k;
s[[2, n, m]] = k;
Return[s];
];
current = initSpace[gridsize, gridsize, k];
This function does one time step iteration, using synchronous updating:
stepC = Compile[{{current, _Real, 3}, {b, _Real, 1}, {disp, _Real,
1}, {fitness, _Real, 1}},
Block[{tmp, k, k2, n, m, curr = current},
n = Dimensions[curr][[2]];
m = Dimensions[curr][[3]];
Do[
curr[[species]] *= b[[species]];
curr[[species]] +=
Map[Round,
GaussianFilter[curr[[species]], disp[[species]]], {2}];
, {species, 2}];
tmp = (fitness[[1]]*curr[[1]] + fitness[[2]]*curr[[2]]);
k = Max[curr];
Do[
k2 = If[tmp[[i, j]] < k, tmp[[i, j]], k];
tmp[[i, j]] = If[ tmp[[i, j]] == 0, 1, tmp[[i, j]] ];
curr[[1, i, j]] = k2*fitness[[1]]*curr[[1, i, j]] / tmp [[i, j]];
curr[[2, i, j]] = k2*fitness[[2]]*curr[[2, i, j]] / tmp [[i, j]];
, {j, m}, {i, n}];
curr
],
CompilationTarget -> "C", Parallelization -> True,
RuntimeOptions -> "Speed"];
I then define a function to display the densities of the two species:
getImage[current_] := Module[{img},
img = Map[{#/k, 0, 0} &, current[[1]], {2} ];
img += Map[{0, 0, #/k} &, current[[2]], {2} ];
Return[Graphics[Raster[img]]];
];
And iterate and display an animation of the dynamics:
b = {2.0, 2.0};
d = {3.0, 1.0};
f = {1.0, 1.3};
current = initSpace[gridsize, gridsize, k];
ngens = 30;
steps = 5;
imgs = Table[0, {ngens}];
Timing[Do[
imgs[[i]] = getImage[current];
Do[current = stepC[current, b, d, f], {steps}];
, {i, ngens}]]
Animate[
imgs[[i]]
, {i, 1, ngens, 1}, AnimationRepetitions -> 1,
AnimationRunning -> False]
During runtime I then get an error "CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation." Any thoughts what's wrong?
GaussianFilter[]
isn't compilable? $\endgroup$LibraryFunction
s can be called efficiently from within the VM. $\endgroup$ListAnimate
to the precomputed data, or does this have to be a real time animation ? $\endgroup$