% SIMULATE simulates a discrete ssm with given inputs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: SIMULATE simulates a discrete ssm with given inputs.
%
% CALL: [mat_out pl_out] = simulate(sys, pl)
%
% INPUTS:
%         - sys, (array of) ssm object
%
% OUTPUTS:
%          _ mat_out contains specified returned aos
%          _ pl_out contains 'lastX', the last state position
%
% <a href="matlab:utils.helper.displayMethodInfo('ssm', 'simulate')">Parameters Description</a>
%
% VERSION: $Id: simulate.m,v 1.104 2011/07/11 10:44:38 adrien Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% TO DO:  options to be defined (NL case)
% allow use of other LTPDA functions to generate white noise


function varargout = simulate(varargin)
  
  %% starting initial checks
  
  % use the caller is method flag
  callerIsMethod = utils.helper.callerIsMethod;
  
  % Check if this is a call for parameters
  if utils.helper.isinfocall(varargin{:})
    varargout{1} = getInfo(varargin{3});
    return
  end
  
  utils.helper.msg(utils.const.msg.PROC3, ['running ', mfilename]);
  
  % Collect input variable names
  in_names = cell(size(varargin));
  for ii = 1:nargin,in_names{ii} = inputname(ii);end
  
  % Collect all SSMs and plists
  [sys, ssm_invars, rest] = utils.helper.collect_objects(varargin(:), 'ssm', in_names);
  [pl, invars2, rest]  = utils.helper.collect_objects(rest(:), 'plist');
  if ~isempty(rest)
    pl = combine(pl, plist(rest{:}));
  end
  pl = combine(pl, getDefaultPlist());
  
  
  %% begin function body
  
  tini = pl.find('t0');
  if isempty(tini)
    tini = pl.find('tini'); % check for the old name
    if isempty(tini)
      tini = time;
    else
      warning('The use of the parameter ''tini'' is deprecated and will be removed in future releases. Use ''t0'' instead');
    end
  end
  if isa(tini,'double')
    tini = time(tini);
  end
  
  
  %% retrieve system infos
  if numel(sys)~=1
    error('simulate needs exactly one ssm as an input')
  end
  if ~sys.isnumerical
    error(['error because system ',sys.name,' is not numerical']);
  end
  timestep  = sys.timestep;
  if timestep==0
    error('timestep should not be 0 in simulate!!')
  end
  
  if callerIsMethod
    % we don't need the history of the input
  else
    inhist  = sys.hist;
  end
  
  if pl.isparam('noise variable names')
    error('The noise option used must be split between "covariance" and "cpsd". "noise variable names" does not exist anymore!')
  end
  
  %% display time ?
  displayTime = find(pl, 'displayTime');
  
  %% initial state
  ssini = find(pl,'ssini');
  if isempty(ssini)
    initialize = find(pl, 'initialize');
    if initialize
      ssini = sys.steadyState(pl);
      ssini = find(ssini, 'state');
    else
      ssini = cell(sys.Nss,1);
      for i=1:sys.Nss
        ssini{i} = zeros(sys.sssizes(i),1);
      end
    end
  end
  ssSizesIni = sys.statesizes;
  SSini = double(ssm.blockMatFusion(ssini,ssSizesIni,1));
  
  %% collecting simulation i/o data
  
  % values
  aos_in = find(pl, 'aos');
  constants_in = find(pl, 'constants');
  cov_in = find(pl, 'covariance');
  cpsd_in = find(pl, 'CPSD');
  noise_in = blkdiag(cov_in, cpsd_in/(timestep*2));
  [U1,S1,V1] = svd(noise_in.'); %#ok<NASGU>
  if (sum(S1<0)>0)
    error('Covariance matrix is not positive definite')
  end
  noise_mat = U1*sqrt(S1);
  
  %% modifying system's ordering
  if find(pl, 'reorganize')
    sys = reorganize(sys, pl, 'set', 'for simulate', 'internal', 'internal');
  end
  
  %% getting system's i/o sizes
  inputSizes = sys.inputsizes;
  outputSizes = sys.outputsizes;
  
  Naos_in = inputSizes(1);
  Nnoise = inputSizes(2);
  Nconstants = inputSizes(3);
  NstatesOut = outputSizes(1);
  NoutputsOut = outputSizes(2);
  
  if numel(aos_in)~=Naos_in
    error(['There are ' num2str(numel(aos_in)) ' input aos and ' num2str(Naos_in) ' corresponding inputs indexed.' ])
  elseif numel(diag(noise_in))~=Nnoise
    error(['There are ' num2str(numel(diag(noise_in))) ' input noise variances and ' num2str(Nnoise) ' corresponding inputs indexed.' ])
  elseif numel(constants_in)~=Nconstants
    error(['There are ' num2str(numel(constants_in)) ' input constants and ' num2str(Nconstants) ' corresponding inputs indexed.' ])
  end
  
  A = sys.amats{1,1};
  Coutputs = sys.cmats{2,1};
  Cstates  = sys.cmats{1,1};
  Baos     = sys.bmats{1,1};
  Daos     = sys.dmats{2,1};
  Bnoise   = sys.bmats{1,2} * noise_mat;
  Dnoise   = sys.dmats{2,2} * noise_mat;
  Bcst     = sys.bmats{1,3} * reshape(constants_in, Nconstants, 1);
  Dcst     = sys.dmats{2,3} * reshape(constants_in, Nconstants, 1);
  
  %% getting correct number of samples
  Nsamples = find(pl, 'Nsamples');
  f0 = 1/timestep;
  for i=1:Naos_in
    Nsamples = min(Nsamples,length(aos_in(i).y));
    try
      if ~(f0==aos_in(i).fs)
        str = ['WARNING : ssm frequency is ',num2str(f0),...
          ' but sampling frequency of ao named ',...
          aos_in(i).name, ' is ', num2str(aos_in(i).fs) ];
        utils.helper.msg(utils.const.msg.MNAME, str);
      end
    end
    % maybe tdata should be retrieved and verified to be equal, rather than this.
  end
  if Nsamples == inf % case there is no input!
    error('warning : no input option ''Nsamples'' providing simulation duration is available!!')
    Nsamples = 0;
  end
  
  %% termination condition
  if strcmp(find(pl, 'termincond'),'');
    doTerminate = false;
    terminationCond = '';
  else
    doTerminate = true;
    terminationCond = find(pl, 'termincond');
  end
  
  %% ao vector
  aos_vect = zeros(Naos_in, Nsamples);
  for j = 1:Naos_in
    aos_vect(j,:) = aos_in(j).y(1:Nsamples).';
  end
  
  %% simulation loop
  [x, y, lastX] = ssm.doSimulate(...
    SSini, Nsamples, ...
    A, Baos, Coutputs, Cstates, Daos, Bnoise, Dnoise, Bcst, Dcst,...
    aos_vect, doTerminate, terminationCond, displayTime, timestep, pl.find('force complete'));
  
  %% saving in aos
  fs      = 1/timestep;
  isysStr = sys.name;
  
  ao_out = ao.initObjectWithSize(1,NstatesOut+NoutputsOut);
  for i=1:NstatesOut
    ao_out(i).setData(tsdata( x(i,:), fs ));
    ao_out(i).setName(sys.outputs(1).ports(i).name);
    ao_out(i).setXunits('s');
    ao_out(i).setYunits(sys.outputs(1).ports(i).units);
    ao_out(i).setDescription(...
      ['simulation for ' isysStr, ' : ',  sys.outputs(1).ports(i).name,...
      '    ' sys.outputs(1).ports(i).description]);
    ao_out(i).setT0(tini);
  end
  for i=1:NoutputsOut
    ao_out(NstatesOut+i).setData(tsdata( y(i,:), fs ));
    ao_out(NstatesOut+i).setName(sys.outputs(2).ports(i).name);
    ao_out(NstatesOut+i).setXunits('s');
    ao_out(NstatesOut+i).setYunits(sys.outputs(2).ports(i).units);
    ao_out(NstatesOut+i).setDescription(...
      ['simulation for, ' isysStr, ' : ',  sys.outputs(2).ports(i).name, ...
      '    ', sys.outputs(2).ports(i).description]);
    ao_out(NstatesOut+i).setT0(tini);
  end
  
  %% construct output plist
  plist_out = plist('lastX', ssm.blockMatRecut(lastX,ssSizesIni,1) );
  
  %% construct output matrix object
  out = matrix(ao_out);
  if callerIsMethod
    % do nothing
  else
    myinfo = getInfo('None');
    out.addHistory(myinfo, pl , ssm_invars(1), inhist );
  end
  
  %% Set output depending on nargout
  if nargout == 1;
    varargout = {out};
  elseif nargout == 2;
    varargout = {out plist_out};
  elseif nargout == 0;
    iplot(ao_out);
  else
    error('Wrong number of outputs')
  end
end

%--------------------------------------------------------------------------
% Get Info Object
%--------------------------------------------------------------------------
function ii = getInfo(varargin)
  
  if nargin == 1 && strcmpi(varargin{1}, 'None')
    sets = {};
    pl   = [];
  else
    sets = {'Default'};
    pl   = getDefaultPlist;
  end
  % Build info object
  ii = minfo(mfilename, 'ssm', 'ltpda', utils.const.categories.op, '$Id: simulate.m,v 1.104 2011/07/11 10:44:38 adrien Exp $', sets, pl);
end

%--------------------------------------------------------------------------
% Get Default Plist
%--------------------------------------------------------------------------
function pl = getDefaultPlist()
  pl = ssm.getInfo('reorganize', 'for simulate').plists;
  pl.remove('set');
  
  p = param({'covariance', 'The covariance of this noise between input ports for the <i>time-discrete</i> noise model.'}, []);
  pl.append(p);
  
  p = param({'CPSD', 'The one sided cross-psd of the white noise between input ports.'}, []);
  pl.append(p);
  
  p = param({'aos', 'An array of input AOs.'}, ao.initObjectWithSize(1,0));
  pl.append(p);
  
  p = param({'constants', 'Array of DC values for the different corresponding inputs.'}, paramValue.DOUBLE_VALUE(zeros(0,1)));
  pl.append(p);
  
  p = param({'Nsamples', 'The maximum number of samples to simulate (AO length(s) overide this).'}, paramValue.DOUBLE_VALUE(inf));
  pl.append(p);
  
  p = param({'ssini', 'A cell-array of vectors that give the initial position for simulation.'}, {});
  pl.append(p);
  
  p = param({'initialize', 'When set to 1, a random state value is computed for the initial point.'}, paramValue.FALSE_TRUE);
  pl.append(p);
  
  p = param({'tini', 'Same as t0; kept for backwards compatibility.'}, paramValue.EMPTY_DOUBLE );
  pl.append(p);
  
  p = param({'t0', 'The initial simulation time (seconds).'}, paramValue.EMPTY_DOUBLE );
  pl.append(p);
  
  p = param({'displayTime', 'Switch off/on the display'},  paramValue.TRUE_FALSE);
  pl.append(p);
  
  p = param({'termincond', 'A string to evaluate a termination condition on the states in x (''lastX'') or outputs in y (''lastY'')'}, paramValue.EMPTY_STRING);
  pl.append(p);
  
  p = param({'reorganize', 'When set to 0, this means the ssm does not need be modified to match the requested i/o. Faster but dangerous!'}, paramValue.TRUE_FALSE);
  pl.append(p);
  
  p = param({'force complete', 'Force the use of the complete simulation code.'}, paramValue.FALSE_TRUE);
  pl.append(p);
  
end

