##  Copyright (C) 2015  Daniel Kraft <d@domob.eu>
##  GNU Octave level-set package.
##
##  This program is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program.  If not, see <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn  {Function File} {@var{p} =} so_init_params (@var{verbose}, @var{nProc} = 1)
##
## Initialise the parameter structure for the shape optimisation routines.
## Choose default parameters, and set whether or not ``verbose'' log chatter
## should be printed.
##
## @var{nProc} specifies the number of processes to use for some
## steps that can be done in parallel (like the line search with
## @code{so_step_armijo}).  If this number is larger than one,
## the function @code{pararrayfun} from the @code{parallel} package
## must be available.
##
## The result of this function call can be used as a basis for defining
## @code{@var{data}.p}.  Values can be overwritten after the call where desired.
## 
## @seealso{so_run_descent, so_step_armijo, pararrayfun}
## @end deftypefn

function p = so_init_params (verbose, nProc = 1)
  if (nargin () < 1 || nargin () > 2)
    print_usage ();
  endif

  if (nProc < 1 || nProc != round (nProc))
    error ("invalid number of processors");
  endif
  hasParallel = exist ("pararrayfun");
  if (nProc > 1 && hasParallel != 2 && hasParallel != 3)
    error ("multi-threading requested but 'pararrayfun' is not available");
  endif

  p = struct ("verbose", verbose, "nProc", nProc);

  p.lineSearch = struct ("relaxation", 0.1, "backtrack", 0.8, ...
                         "initial", 2, "minStep", 1e-6);

  p.descent = struct ("initialStep", 1);
endfunction

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tests.

% Test for error conditions.
%!error <Invalid call to>
%!  so_init_params ()
%!error <Invalid call to>
%!  so_init_params (true, 1, 2)
%!error <invalid number of processors>
%!  so_init_params (true, 0);
%!error <invalid number of processors>
%!  so_init_params (true, 1.5);

% Check the test for loaded pararrayfun.
%!test
%!  p = so_init_params (true);
%!error <'pararrayfun' is not available>
%!  pkg unload parallel;
%!  p = so_init_params (true, 2);
%!test
%!  pkg load parallel;
%!  p = so_init_params (true, 2);

% Since so_init_params is used in the tests of the other
% routines, they already verify that the parameters
% are accepted by them.
