function  reps = reps_from_cache(Mparams,arg2)

%REPS_FROM_CACHE -- Add noise and apply sigmoid to raw representations.
%
%  reps = reps_from_cache(Mparams)
%  reps = reps_from_cache(Mparams,N)
%  reps = reps_from_cache(Mparams,cache)
%
%  MPARAMS is a parameter structure produced by PLM_PARAMS. 
%  The relevant fields are 'rep_gain' 'rep_noise', and 'max_act'.
%  REPS_FROM_CACHE depends on the global var PLM_CACHE (see CACHE_INPUTS).
%  N is a positive integer indicating the number of replications.
%  When not supplied, it defaults to PLM_CACHE(1).N.
%  An explicit CACHE can be supplied, superseding the global PLM_CACHE.
%
%  The function adds independent Gaussian noise to the 'raw' reps made by
%  PLM_FRONTEND, and then applies the sigmoidal activation function with
%  gain MPARAMS.rep_gain. It returns a [N,N_rep,N_cond] matrix REPS, where
%  N_rep is the length of each representation vector (typically 35) and
%  N_cond is the number of conditions in cache (typically 12).
%
%  Example:
%   Idef=make_PLFrontend(PLM_input_params);PLM_CACHE=cache_inputs(Idef,N);
%   Mparams = PLM_params ; reps = reps_from_cache(Mparams) ;
%   subplot(2,1,1);plot(mean(PLM_CACHE(1).rep));ylabel('Raw cache');
%   subplot(2,1,2);plot(mean(reps(:,:,1)));ylabel('Activation');
%
%  See also CACHE_INPUTS, PLM_HEBB1, PLM_FRONTEND, HEBB_STATS.

%  Original coding by Alexander Petrov, UC Irvine.
%  $Revision: 1.0 $  $Date: 2003/07/16 09:47 $

global PLM_CACHE

%-- Collect the 'raw' reps from the cache
if (nargin==1)             % default PLM_CACHE ; default N
   N = PLM_CACHE(1).N ;
   N_cond = prod(size(PLM_CACHE)) ;    % typically 12
   N_rep = size(PLM_CACHE(1).rep,2) ;  % typically 35 = 7 orient x 5 spfreq
   reps = zeros(N,N_rep,N_cond) ;
   for k = 1:N_cond  reps(:,:,k) = PLM_CACHE(k).rep(1:N,:) ; end
elseif (isnumeric(arg2))   % N explicitly supplied ; default PLM_CACHE
   N = arg2 ;
   N_cond = prod(size(PLM_CACHE)) ;    % typically 12
   N_rep = size(PLM_CACHE(1).rep,2) ;  % typically 35 = 7 orient x 5 spfreq
   reps = zeros(N,N_rep,N_cond) ;
   for k = 1:N_cond  reps(:,:,k) = PLM_CACHE(k).rep(1:N,:) ; end
elseif (isstruct(arg2))    % CACHE explicitly supplied
   N = arg2(1).N ;
   N_cond = prod(size(arg2)) ;
   N_rep = size(arg2(1).rep,2) ;
   reps = zeros(N,N_rep,N_cond) ;
   for k = 1:N_cond  reps(:,:,k) = arg2(k).rep(1:N,:) ; end
else
   error('The second argument must be either N or CACHE.') ;
end

%-- Decipher and store the relevant model parameters
max_act = Mparams.max_act ;
minus_rep_gain = -Mparams.rep_gain ;
rep_noise = Mparams.rep_noise ;

%-- Add representation noise, if specified.
if (rep_noise>0)
   reps = reps + randn(size(reps)).*rep_noise ;
end      
      
%-- Apply the sigmoidal activation function and return
reps = max(0,max_act.*(2./(1+exp(minus_rep_gain.*reps))-1)) ;

%--- Return REPS
%%%%% End of file REPS_FROM_CACHE.M
