function runBatchJob()
% function runBatchJob()
% PURPOSE: Demonstrates details of how to call user script or 
%          function via MATLAB's batch command
% REASON: When user runs a MATLAB job on the SCC cluster, it is 
% assigned, at runtime, to a compute node. For both MATLAB standalone
% or MATLAB PCT jobs, MATLAB generates internal and administrative folders
% and files in user's ~/.matlab folder. This causes excessive and highly 
% inefficient I/O for the operating system. By using the MATLAB batch 
% command, these folders can be created, at run time, on the assigned 
% SCC batch compute node's TMPDIR folder. This eliminates the need for
% I/O between the user's login node .matlab folder and the compute node. 
% NOTE: the term "MATLAB batch" is used to differentiate it from the
% word "batch" (or "SCC 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. You can use any PCT commands.
% However, if SPMD is used, 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;  % RCS util to get batch-generated env vars

% myApp computes Arithmetic Sequence Sum. Input: n, nslots
% s = 1 + 2 + 3 + . . . + n
if task == 'undefined'
  n = 100;   % default if Array Job (qsub -t) not used
else
  n = task;  % 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: Computes s = 1+2+3+ . . . + n with multiprocessors
% Job launched with MATLAB batch: myApp.m is function with 3 output
% Furthermore, it is a parpool job with nslots cores
job1 = batch(myCluster, 'myApp', 3, {n, nslots}, 'Pool', 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; see myApp.m

% Example 2: Computes transcendental A(1:n) = sin(...) with 
%            multiprocessors; myWave.m is a script m-file
job2 = batch(myCluster, 'myWave', 'Pool', 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            % second output; see myWave.m

end
