%------------------------------------------------------------------
% Example: Monte Carlo Multidimensional Integration
% 
% clear all;
 clc;
   d = 3; %dimension
   M = 2; % power of 10
   I0 = 1.0; % Exact Answer
   a = -10.*ones(d,1); % Lower Side Vector
   b = 10.*ones(d,1); %Upper Side Vector
  % f = 0;
   f = inline ('exp(-sum(x.*x)/2) / sqrt(2*pi)^length(x)','x');
  
clusterHost = 'orca.sharcnet.ca';
remoteDataLocation = '/scratch/jemmyhu/matlab';

% Create a job scheduler / manager object:
sched = findResource('scheduler', 'type', 'generic');

% Use a local directory as the DataLocation
set(sched, 'DataLocation', 'C:\Temp');
set(sched, 'ClusterMatlabRoot', '/opt/sharcnet/matlab/R2010b');
set(sched, 'GetJobStateFcn', @getJobStateFcn);
set(sched, 'DestroyJobFcn', @destroyJobFcn);
set(sched, 'HasSharedFilesystem', false);
set(sched, 'ClusterOsType', 'unix');

% If you want to run parallel jobs, you must specify a ParallelSubmitFcn
set(sched, 'SubmitFcn', {@distributedSubmitFcn, clusterHost, remoteDataLocation});
%set(sched, 'ParallelSubmitFcn', {@parallelSubmitFcn, clusterHost, remoteDataLocation});

job = createJob(sched,'FileDependencies', {'montemd.m'})
   
%Creating Tasks
for i = 0 : M
      n = 10^i;
      I1=createTask(job,@montemd,1,{a,b,d,n,f});
      I2=createTask(job,@montemd,1,{a,b,d,n,f});       
end
%Submitting the Job
submit(job);
%Waiting until the job is complete
waitForState(job,'finished')    
o1 = getAllOutputArguments(job)
%Creating the table for outputs
% fprintf ('\nMonte Carlo Multidimensional Integration: Two Samples \n');
% fprintf ('\n K    n=10^K        I1        |Error1|        I2        |Error2|\n');
% fprintf ('------------------------------------------------------------------\n');
 
% for i=1:M+1
%        n = 10^(i-1);
%        Error1 = 100*(cellfun(@sum,o1(i))-I0)/I0;
%        Error2 = 100*(cellfun(@sum,o1(i+1))-I0)/I0;
%      %  fprintf ('%2i %9i %12.6f %12.6f %12.6f %12.6f\n',i-1,n,cellfun(@sum,o1(i)),Error1,cellfun(@sum,o1(i+1)),Error2);
% end       

