TransWikia.com

ParallelSum issue inside package

Mathematica Asked on May 19, 2021

I have the following very simple package with only one external function SumSeries[]:

BeginPackage["testPackage`"];
SumSeries
Begin["`Private`"]

SumSeries[InputSeries_,SeriesCondition_,SumLim_]:=Module[{nseries={},SeriesExtract,CondExtract,SeriesNumber=Length@InputSeries},
SetSharedVariable[nseries];
 Do[
CondExtract=SeriesCondition[[i]];
SeriesExtract=InputSeries[[i]];
nseries=Insert[nseries,ParallelSum[If[CondExtract,SeriesExtract//N,0],Evaluate[Sequence@@SumLim]],-1],{i,SeriesNumber}];
Total@nseries]

End[];
EndPackage[];

Now when I give the following input.

In[1]:= << testPackage`  
In[2]:= series = {((-1)^(2 n1 + n2) 0.1^n1 2.1^(-2 - n1 - n2)
     Gamma[2 + n2])/
   Gamma[1 + n2], ((-1)^(n1 + n2) 0.1^n1 2.1^(-1 - n2)
     Gamma[1 + n1 - n2])/Gamma[n1 - n2]};
seriescond = {True, n1 > n2};
sumlim = {{n1, 0, 10}, {n2, 0, 10}};
In[5]:= SumSeries[series, seriescond, sumlim] 
Out[5]= (121 (-1.)^(2. n1 + n2) 0.1^n1 2.1^(-2. - 1. n1 - 1. n2)
   Gamma[2. + n2])/Gamma[1. + n2] + 
 121 If[n1 > n2, N[testPackage`Private`SeriesExtract$1412], 0]

the code is not working properly. I have figured out that when I replace ParallelSum with Sum, the package works perfectly!
But I can’t understand why it is not working with ParallelSum. Any idea how to fix it?

One Answer

The problem while using ParallelSum inside a package is that the values of the variables CondExtract and SeriesExtract are not automatically distributed among all the subkernels as it is inside a package.

A standard way to properly distribute among subkernels (in a package) is using With.

BeginPackage["testPackage`"];

SumSeriesParallel;

Begin["`Private`"]

SumSeriesParallel[InputSeries_,SeriesCondition_,SumLim_]:=Module[{nseries={},SeriesNumber=Length@InputSeries},
SetSharedVariable[nseries];
 Do[
With[{ CondExtract=SeriesCondition[[i]],
SeriesExtract=InputSeries[[i]]},
nseries=Insert[nseries,ParallelSum[If[CondExtract1,SeriesExtract1//N,0],Evaluate[Sequence@@SumLim]],-1]],{i,SeriesNumber}];
Total@nseries]

End[];
EndPackage[];

Answered by Epsilon on May 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP