I'm trying to set up a ParallelDo loop inside of a Do loop, however I'm running into issues. Here is a very simplified toy model code of the final code that I wish to implement:
LaunchKernels[16];
ParallelEvaluate[
n[i_] = {};
M[i_] = {};
Do[
AppendTo[n[i],{0,0}];
AppendTo[M[i],{0,0}],
{i,1,5}
]
];
Do[
ParallelDo[
J1[i] = {i, j};
J2[i] = {i + 1, j + 1};
AppendTo[M[i], J1[i]];
AppendTo[n[i], J2[i]],
{i, 1, 5}
],
{j, 0, 5}
]
The problem seems to be that Mathematica appends to the initial conditions to a given n[i] (or M[i]) as many times as there are parallel kernels. For example,
Join@@ParallelEvaluate[n[1]] = {{0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
{0, 0}, {0, 0}, {2, 1}, {2, 2}, {2, 3},
{2, 4}, {2, 5}, {2, 6}}
And so Mathematica duplicates the initial conditions that it AppendsTo a particular n[i] (or M[i]) 16 times over.
Why is this happening and what can I do to resolve it?
n,M,J1andJ2are synchronized? If so seeSetSharedVariable. This might provide a slow-down though. Better to initialize each chunk separately, I think so that it's right in the end. Oh, or are you trying to get the code in theParallelDoto happen on all kernels? Then just useParallelEvaluateand `Do. – b3m2a1 Mar 29 '17 at 17:24Doloop to be parallelised, i.e. like you say, I want the computations in theParallelDoto be distributed among the kernels. The outer one needs to be a "normal"Doloop since the results might depend on previous calculations. – user35305 Mar 29 '17 at 17:43SetSharedVariablethen. Based on what you say I think that's what you want. – b3m2a1 Mar 29 '17 at 17:47ParallelEvaluatecompletely and just putSetSharedVariable[n[i], M[i]]? – user35305 Mar 29 '17 at 17:58SetSharedVariable[n,M]I think. – b3m2a1 Mar 29 '17 at 17:59n[i]andM[i]are more complicated functions and each kernel will require knowledge of their functional forms and the associated parameters. – user35305 Mar 29 '17 at 18:02SetSharedFunction. In any case between those two and partitioning the work cleverly you can almost certainly find your solution. – b3m2a1 Mar 29 '17 at 18:04SetSharedFunctionis what you need to make this code work. I'd suggest it would be preferable to useParallelTableand avoidAppendTo– george2079 Mar 29 '17 at 18:56Do+AppendTois generally a bad approach in Mathematica, particularly so with parallelization. UseTableinstead. – Szabolcs Mar 29 '17 at 20:11