Based on this post (https://www.mathworks.com/matlabcentral/answers/368486-using-parallel-computing-with-external-software), I have modified my code accordingly.
(1) Main function:
% run in parallel
spmd
mkdir(sprintf('worker%d', labindex));
copyfile(Case0Input_path,sprintf('worker%d',labindex));
cd(sprintf('worker%d', labindex));
end
addAttachedFiles(gcp,{'windows_nlcon.m','windows_generatePumpingSchedule.m'})
(2) GA objective function:
X = sprintf('I am worker %d',labindex);
disp(X)
%MatlabOpt_path = char(strcat(Input_path,'\MatlabOpt',num2str(labindex))); % this line has been commented out
MatlabOpt_path = char(strcat(pwd,'\MatlabOpt')); % this line has been added
MyFolder = MatlabOpt_path; % this is a folder
if ~isdir(MyFolder) % The first time to call objective function
mkdir(MatlabOpt_path) % this is a folder
copyfile('Case0.txt', MatlabOpt_path)
else
rmdir(MatlabOpt_path, 's')
mkdir(MatlabOpt_path) % this is a folder
copyfile('Case0.txt', MatlabOpt_path)
end
Then, I can run my code in parallel properly.
However, I have a new issue.
From my GA objective function, you can see that the folder "MatlabOpt" in floder "worker%d" will be created, deleted, created, deleted... The code works properly at the beginning. However, after sevearl hours, after around 20 generations of GA, the code gave me an error:
Error using windows_objective (line 23) % comment by Min: this line is "mkdir(MatlabOpt_path) % this is a folder"
Access is denied.
Error in
objAndConVectorizer>@(Vars)windows_objective(Vars,Engine_path,security_count,FluidDensity,FluidViscosity,PropDensity_0,PropDiameter_0,NoofClusters,Opt_PerfNo,Opt_PerfDia,Opt_ClusterSpacing,Opt_ProppSize,Opt_ProppDen,Opt_MaxInjRate,Opt_MaxPropConc,Opt_RampUpSpeed,PerfNo_Option,PerfDia_Option,ProppSize_Option,ProppDen_Option,NoofStages,ProppPerCluster,SlurryPerCluster)
Error in createAnonymousFcn>@(x)fcn(x,FcnArgs{:}) (line 11)
fcn_handle = @(x) fcn(x,FcnArgs{:});
Error in objAndConVectorizer (line 37)
parfor (i = 1:popSize)
Error in gaminlppenaltyfcn
Error in gapenalty
Error in stepGA (line 46)
nextScore = FitnessFcn(nextPopulation);
Error in galincon (line 62)
[score,population,state] =
stepGA(score,population,options,state,GenomeLength,FitnessFcn);
Error in gapenalty
Error in gaminlp
Error in ga (line 393)
[x,fval,exitFlag,output,population,scores] = gaminlp(FitnessFcn,nvars, ...
Error in windows_frac_optimization (line 234)
[x,fval,exitflag] =
ga(@(Vars)windows_objective(Vars,Engine_path,security_count,FluidDensity,...
Caused by:
Failure in user-supplied fitness function evaluation. Cannot continue.
IdleTimeout has been reached.
Parallel pool using the 'local' profile is shutting down.
This error tells me that, after hundreds of successful "creating, deleting, creating, deleting, ..." of this "MatlabOpt" folder, it cannot create this folder anymore after deleting it.