function runBatchJob()
% function runBatchJob()
% PURPOSE: example to call user script & function via MATLAB batch
% REASON: When users run parallel jobs on the SCC cluster, they are
% assigned at runtime to arbitrary compute nodes. For both MATLAB 
% standalone or MATLAB PCT jobs, many MATLAB administrative folders
% and files are generated in users' ~/.matlab folder. This causes
% excessive and highly inefficient I/O and data movement for the 
% system. Towards this end, the MATLAB's batch command enables these
% folders and files to be generated on the compute node's TMPDIR
% folder to eliminate intra-node communications.
% NOTE: the term MATLAB batch is used to differentiate it from the
% word batch which is a batch job submitted by qsub to the SCC.
% In this example, qsub submits a batch job to the SCC in which 
% the runBatchJob.m is invoked. The runBatchJob file in turn uses 
% the MATLAB batch command to launch an "internal batch job," with
% the cores already assigned through qsub. If SPMD is used for 
% parallel computing, be sure to use the PCT's gather/gplus/gop 
% utilities to transfer data from the workers' storage back to the 
% client before returning from MATLAB batch (see myApp.m). This 
% requirement is applicable to both function (myApp) and script
% (myWave) m-files.
% Kadin Tseng, RCS, IS&T, Boston University, November, 2014

[nslots, task] = getbev;    % get batch-generated env vars

% myApp computes Arithmetic Sequence Sum. Input: n, nslots
% s = 1 + 2 + 3 + . . . + n
n = 1000;
if task ~= 'undefined'
  n = task * 1000;  % for Array Jobs,each job has its only n
end

myCluster = parcluster('local')  % treat compute node as "local"
if isBatch
  myCluster.JobStorageLocation = getenv('TMPDIR');  % for batch job
end

% Example 1: for function m-file myApp.m
% Computes sum of Arithmetic Sequence s = 1+2+3+ . . . + n
job1 = batch(myCluster, 'myApp', 3, {n, nslots}, 'matlabpool', nslots)
wait(job1);   % wait for job to finish
% A function needs fetchOutputs to recover output (cell array)
data=fetchOutputs(job1);  % retrieve output for function m-file

data{1:end}   % prints myApp output

% Example 2: for script m-file myWave.m
% Computes transcendental function A(1:n) = sin(...)
job2 = batch(myCluster, 'myWave', 'matlabpool', nslots)  % submit batch
wait(job2);      % wait for job to finish
load(job2, 'A', 'y'); % retrieve output for script m-file with load
A = A(1:6)   % prints the 1st 6 elements
y            % SPMD output; same as in myApp.m

end
