function  sumsq = PLM_paramsearch(x,data)

%PLM_PARAMSEARCH -- PLModel fit with human data as a fun of parameters X.
%
%  sumsq = PLM_paramsearch(x,data)
%
%  PLM_PARAMSEARCH is a generic function that allows to fit an
%  arbitrary model of the PLM family. It is intended to serve as a
%  "loss function" for PARAMSEARCH in the eponymous toolbox.
%  The Paramsearch toolbox in turn calls FMINCON from Matlab's 
%  Optimization toolbox (ver. 2.0) to do the actual search.
%
%  DATA must be a strucuture with the following five fields:
%   - model_name -- name of the M-file implementing the model
%   - sumsq_name -- name of the M-file defining the sum-of-squares error
%   - model_data -- arbitrary structure passed to this M-file
%       When MODEL_DATA is an array of length N, the M-file is called
%       N times and the average "loss" is returned in SUMSQ.
%   - params     -- a struct containing all parameters of the model
%   - v2p_templ  -- a vector-to-param conversion template defining
%        the interpretation of the vector X. See PLM_TEMPLATE.
%  Optionally, DATA may also have a sixth field:
%   - verbose -- 0 or a file-id of a verbose stream (1=stdout)
%
%  See also PARAMSEARCH, VECTOR2PARAMS, PLM_TEMPLATE, FMINCON.

%  Original coding by Alexander Petrov, Carnegie Mellon University.
%  $Revision: 1.3 $  $Date: 2003/07/24 10:53 $

if (isfield(data,'verbose'))  verbose=data.verbose ; else verbose=0 ; end
if (verbose>0)  fprintf(verbose,'%.4f  ',x) ; end

params = vector2params(x,data.params,data.v2p_templ) ;

N = length(data.model_data) ;
sumsqN = zeros(N,1) ;
for k = 1:N
  model_data = data.model_data(k) ;
  model_data.params = params ;
  Zcongr = feval(data.model_name,model_data) ;   % <-- main load
  sumsqN(k) = feval(data.sumsq_name,Zcongr) ;
end

sumsq = mean(sumsqN) ;
if (verbose>0)  fprintf(verbose,'-->  %f\n',sumsq) ; end

%-- Return SUMSQ
%%% End of file PLM_PARAMSEARCH.M
