function L = logL(x,data)

% LOGL -- Negative loglikelihood function for user-supplied model and data.
%
% L = logL(x,data)
%
% LOGL is a generic function that allows arbitrary user-supplied 
% probabilistic models to be fitted to data via Matlab's Optimization
% toolbox (ver. 2.0).
%
% DATA must be a strucuture with the following five fields:
%  - model_name -- name of the function implementing your model
%  - model_data -- arbitrary structure passed to your function
%  - params     -- a structure containing all parameters of the model
%  - v2p_templ  -- a vector-to-param conversion template that defines the
%       interpretation of the elements of the vector X. See functions
%       VECTOR2PARAMS, PARAMS2VECTOR, and SAMPLE_TEMPLATE for details.
%  - clip_prob  -- a number b/n 0 and 1 specifying the minimum value for
%       PROB for any trial. Values lower than that are clipped.
%       Recommended clip_prob=exp(-4)=0.0183. Zero means "don't clip".
%
% LOGL works according to the following algorithm:
%  1. The vector X is converted into a PARAMS structure:
%     > PARAMS = vector2params(x,data.params,data.v2p_templ) ;
%  2. The user-supplied model is called using FEVAL
%     > model_data = data.model_data ; model_data.params = PARAMS ;
%     > prob = feval(data.model_name,model_data) ;   % <-- main load
%  3. The output of the model must be a list of probabilities.
%     They are converted to loglikelihood L by the expression
%     > L = -sum(log(max(PROB,data.clip_prob)))) ;
%
% See also PARAMSEARCH, VECTOR2PARAMS, SAMPLE_TEMPLATE, FMINCON.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.2 $  $Date: 2001/05/29 02:00 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

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

model_data = data.model_data ;
model_data.params = params ;

prob = feval(data.model_name,model_data) ;   % <-- main load

L = -sum(log(max(prob,data.clip_prob))) ;
  
%%% End of file LOGL.M
