% MATRIX constructor for matrix class.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: MATRIX constructor for matrix class.
%
% CONSTRUCTOR:
%
%       fb = matrix()      - creates an empty matrix object
%       fb = matrix(objs)  - construct from an array of objects
%       fb = matrix(pl)    - create a matrix object from a parameter list
%
% <a href="matlab:utils.helper.displayMethodInfo('matrix', 'matrix')">Parameters Description</a>
%
% VERSION: $Id: matrix.m,v 1.49 2011/08/23 13:50:46 hewitson Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

classdef matrix < ltpda_uoh
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                            Property definition                            %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  
  %---------- Public (read/write) Properties  ----------
  properties
    objs = []; % objects in matrix
  end
  
  %---------- Protected read-only Properties ----------
  properties (SetAccess = protected)
  end
  
  %---------- Private Properties ----------
  properties (GetAccess = protected, SetAccess = protected)
  end
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                          Check property setting                           %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  
  methods
    
  end
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                                Constructor                                %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  
  methods
    function obj = matrix(varargin)
      
      callerIsMethod = utils.helper.callerIsMethod;
      
      import utils.const.*
      utils.helper.msg(msg.OMNAME, 'running %s/%s', mfilename('class'), mfilename);
      
      % Collect all matrix objects
      [mats, invars, rest] = utils.helper.collect_objects(varargin(:), 'matrix');
      
      if isempty(rest) && ~isempty(mats)
        % Do copy constructor and return
        utils.helper.msg(msg.OPROC1, 'copy constructor');
        obj = copy(mats, 1);
        for kk=1:numel(obj)
          obj(kk).addHistory(matrix.getInfo('matrix', 'None'), [], [], obj(kk).hist);
        end
        return
      end
      
      switch nargin
        case 0
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%   no input   %%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          utils.helper.msg(msg.OPROC1, 'empty constructor');
          obj.addHistory(matrix.getInfo('matrix', 'None'), plist(), [], []);
          
        case 1
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%   one input   %%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
          if ischar(varargin{1})
            %%%%%%%%%%   pzm = matrix('foo.mat')   %%%%%%%%%%
            %%%%%%%%%%   pzm = matrix('foo.xml')   %%%%%%%%%%
            utils.helper.msg(msg.OPROC1, 'constructing from file %s', varargin{1});
            obj = fromFile(obj, varargin{1});
            
          elseif isstruct(varargin{1})
            %%%%%%%%%%   r = matrix(struct)   %%%%%%%%%%
            utils.helper.msg(msg.OPROC1, 'constructing from struct');
            obj = fromStruct(obj, varargin{1});
            
          elseif isa(varargin{1}, 'ltpda_uoh')
            %%%%%%%%%%   r = matrix(<ltpda_uoh-objects>)   %%%%%%%%%%
            obj = obj.fromInput(plist('objs', varargin), callerIsMethod);
            
          elseif isnumeric(varargin{1})
            %%%%%%%%%%   r = matrix(doubleArray)   %%%%%%%%%%
            obj = obj.fromValues(plist('values', varargin{1}), callerIsMethod);
            
          elseif isa(varargin{1}, 'plist')
            %%%%%%%%%%   r = matrix(plist)   %%%%%%%%%%
            pl = varargin{1};
            
            if pl.isparam('filename')
              utils.helper.msg(msg.PROC2, 'constructing from file %s', pl.find('filename'));
              obj = obj.fromFile(pl);
              
            elseif pl.isparam('hostname') || pl.isparam('conn')
              utils.helper.msg(msg.PROC2, 'constructing from repository %s', pl.find('hostname'));
              obj = obj.fromRepository(pl);
              
            elseif pl.isparam('objs')
              obj = obj.fromInput(pl, callerIsMethod);
              
            elseif pl.isparam('plist')
              obj = matrix(pl.find('plist'));
              
            elseif pl.isparam('built-in')
              utils.helper.msg(msg.OPROC1, 'constructing from built-in model');
              obj = fromModel(obj, pl);
              
            elseif pl.isparam('csd')
              utils.helper.msg(msg.PROC2, 'constructing from csd %s', char(pl.find('csd')));
              obj = obj.fromCSD(pl);
              
            elseif pl.isparam('model')
              utils.helper.msg(msg.PROC2, 'constructing Multichannel Zero Mean Gaussian Noise %s', char(pl.find('model')));
              obj = obj.MultiChannelNoise(pl);
              
            elseif pl.isparam('values')
              obj = obj.fromValues(pl, callerIsMethod);
              
            else
              obj.setProperties(pl);
              obj.addHistory(matrix.getInfo('matrix', 'None'), pl, [], []);
            end
            
          else
            error('### Unknown single argument constructor.');
          end
          
        case 2
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%   two inputs   %%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
          if isa(varargin{1}, 'ltpda_uoh') && isa(varargin{2}, 'ltpda_uoh')
            %%%%%%%%%%  f = matrix(a1, a2)   %%%%%%%%%%
            utils.helper.msg(msg.OPROC1, 'retrieve from repository');
            obj = obj.fromInput(plist('objs', varargin), callerIsMethod);
            
          elseif (isa(varargin{1}, 'database') || isa(varargin{1}, 'java.sql.Connection')) ...
              && isnumeric(varargin{2})
            %%%%%%%%%%  f = matrix(<database-object>, [IDs])   %%%%%%%%%%
            utils.helper.msg(msg.OPROC1, 'retrieve from repository');
            obj = obj.fromRepository(plist('conn', varargin{1}, 'id', varargin{2}));
            
          elseif isa(varargin{1}, 'matrix') && isa(varargin{2}, 'plist') && isempty(varargin{2}.params)
            %%%%%%%%%%  f = matrix(matrix-object, <empty plist>) %%%%%%%%%%
            obj = matrix(varargin{1});
            
          elseif isa(varargin{1}, 'org.apache.xerces.dom.DeferredElementImpl') && ...
                 isa(varargin{2}, 'history')
            %%%%%%%%%%   obj = matrix(DOM node, history-objects)   %%%%%%%%%%
            obj = fromDom(obj, varargin{1}, varargin{2});
            
          elseif isnumeric(varargin{1}) && iscell(varargin{2})
            %%%%%%%%%%   r = matrix(doubleArray, cellArray)   %%%%%%%%%%
            obj = matrix(plist('values', varargin{1}, 'yunits', varargin{2}));

          elseif isa(varargin{1}, 'ltpda_uoh') && isa(varargin{2}, 'plist')
            %%%%%%%%%%%   matrix(<ltpda_uoh>-object, plist-object)   %%%%%%%%%%
            % always recreate from plist if it contains 'objs' key
            
            
            % If we are trying to load from file, and the file exists, do
            % that. Otherwise, copy the input object.
            if varargin{2}.isparam('filename')
              if exist(fullfile('.', find(varargin{2}, 'filename')), 'file')==2
                obj = matrix(varargin{2});
              else
                obj = matrix(varargin{1});
              end
            else
              if isparam(varargin{2}, 'objs')
                obj = matrix(varargin{2});
              else
                obj = obj.fromInput(combine(plist('objs', varargin{1}), varargin{2}), callerIsMethod);
              end
            end
          else
            error('### Unknown 2 argument constructor.');
          end
          
        otherwise
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%   any input   %%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          [pls, mat_invars, rest] = utils.helper.collect_objects(varargin, 'plist');
          pl = combine(plist('objs', rest), pls);
          
          obj = obj.fromInput(pl, callerIsMethod);
      end
      
    end % End constructor
    
  end
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                            Methods (static)                               %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  methods (Static)
    
    function mdls = getBuiltInModels(varargin)
      mdls = ltpda_uo.getBuiltInModels('matrix');
    end
    
    function out = VEROUT()
      out = '$Id: matrix.m,v 1.49 2011/08/23 13:50:46 hewitson Exp $';
    end
    
    function ii = getInfo(varargin)
      ii = utils.helper.generic_getInfo(varargin{:}, 'matrix');
    end
    
    function out = SETS()
      out = [SETS@ltpda_uoh, ...
        {'From Input'},  ...
        {'MultiChannel Noise'},  ...
        {'From CSD'}, ...
        {'From Values'}];
    end
    
    function plout = getDefaultPlist(set)
      persistent pl;
      persistent lastset;
      if exist('pl', 'var')==0 || isempty(pl) || ~strcmp(lastset, set)
        pl = matrix.buildplist(set);
        lastset = set;
      end
      plout = pl;
    end
    
    function out = buildplist(set)
      
      if ~utils.helper.ismember(lower(matrix.SETS), lower(set))
        error('### Unknown set [%s]', set);
      end
      
      out = plist();
      out = matrix.addGlobalKeys(out);
      out = buildplist@ltpda_uoh(out, set);
      
      switch lower(set)
        case 'default'
          p = param({'shape', 'Specify the shape of the resulting matrix.'}, paramValue.EMPTY_DOUBLE);
          out.append(p);
          
          p = param({'objs', 'Matrix of user objects.'}, paramValue.EMPTY_DOUBLE);
          out.append(p);
        case 'from input'
          p = param({'shape', 'Specify the shape of the resulting matrix.'}, paramValue.EMPTY_DOUBLE);
          out.append(p);
          
          p = param({'objs', 'Matrix of user objects.'}, paramValue.EMPTY_DOUBLE);
          out.append(p);
          
        case 'from csd'

          % CSD
          p = param({'csd','A matrix of fsdata AOs containing the cross spectral density matrix elements.'}, paramValue.EMPTY_DOUBLE);
          out.append(p);
          
          % Target Objects
          p = param({'targetobj', ['Choose the type of output objects:<ul>',...
                         '<li>''miir'' output a matrix containing filterbanks of parallel miir filters</li>',...
                         '<li>''parfrac'' output a matrix containing parafracs objects</li>']}, ...
                         {1, {'miir','parfrac'}, paramValue.OPTIONAL});
          out.append(p);

          % Fs
          p = param({'fs', 'The sampling frequency of the discrete filters.'}, {1, {1}, paramValue.OPTIONAL});
          out.append(p);

          % Max Iter
          p = param({'MaxIter', 'Maximum number of fit iterations.'}, {1, {50}, paramValue.OPTIONAL});
          out.append(p);

          % Pole type
          p = param({'PoleType',['Choose the pole type for fitting initialization:<ul>',...
                         '<li>1 == use real starting poles</li>',...
                         '<li>2 == generates complex conjugate poles of the type <tt>a.*exp(theta*pi*j)</tt> with <tt>theta = linspace(0,pi,N/2+1)</tt></li>',...
                         '<li>3 == generates complex conjugate poles of the type <tt>a.*exp(theta*pi*j)</tt> with <tt>theta = linspace(0,pi,N/2+2)</tt></li></ul>']}, ...
                         {1, {1, 2, 3}, paramValue.SINGLE});
          out.append(p);

          % Min order
          p = param({'MinOrder','Minimum order to fit with.'}, {1, {7}, paramValue.OPTIONAL});
          out.append(p);

          % Max Order
          p = param({'MaxOrder','Maximum order to fit with.'}, {1, {35}, paramValue.OPTIONAL});
          out.append(p);

          % Weights
          p = param({'Weights',['Choose weighting for the fit:<ul>',...
                       '<li> 1 == equal weights for each point</li>',...
                       '<li> 2 == weight with <tt>1/abs(model)</tt></li>',...
                       '<li> 3 == weight with <tt>1/abs(model).^2</tt></li>',...
                       '<li> 4 == weight with inverse of the square mean spread of the model</li></ul>']}, {2, {1 2 3 4}, paramValue.SINGLE});
          out.append(p);

          % Plot
          p = param({'Plot', 'Plot results of each fitting step.'}, paramValue.TRUE_FALSE);
          p.val.setValIndex(2);
          out.append(p);

          % MSE Vartol
          p = param({'MSEVARTOL', ['Mean Squared Error Variation - Check if the realtive variation of the mean squared error is<br>',...
                           'smaller than the value specified. This option is useful for finding the minimum of Chi squared.']}, ...
                           {1, {1e-2}, paramValue.OPTIONAL});
          out.append(p);

          % FIT TOL
          p = param({'FITTOL',['Mean Squared Error Value - Check if the mean squared error value <br>',...
                      ' is lower than the value specified.']},  {1, {1e-2}, paramValue.OPTIONAL});
          out.append(p);
          
          % UseSym
          p = param({'UseSym', ['Use symbolic calculation in eigen-decomposition.<ul>'...
                                '<li>''on'' - uses symbolic math toolbox calculation<br>'...
                                'for poles stabilization</li>'...
                                '<li>''off'' - perform double-precision calculation<br>'...
                                'for poles stabilization</li>']}, {1, {'on','off'}, paramValue.SINGLE});
          out.append(p);
          
          % Iunits
          p = param({'iunits', 'The unit to set as input unit for the output filters'}, paramValue.EMPTY_STRING);
          out.append(p);
          
          % Ounits
          p = param({'ounits', 'The unit to set as output unit for the output filters'}, paramValue.EMPTY_STRING);
          out.append(p);
          
        case 'multichannel noise'

          % Model
          p = param({'model','A matrix of filterbanks or parfarcs objects, modeling multichannel system response.'}, paramValue.EMPTY_DOUBLE);
          out.append(p);
          
          % Nsecs
          p = param({'nsecs', 'Number of seconds in the desired noise data series.'}, {1, {1}, paramValue.OPTIONAL});
          out.append(p);

          % Fs
          p = param({'fs', 'The sampling frequency of the noise data series.'}, {1, {1}, paramValue.OPTIONAL});
          out.append(p);
          
          % Yunits
          p = param({'yunits','Unit on Y axis.'},  paramValue.STRING_VALUE('m'));
          out.append(p);
          
        case 'from values'
          
          % Values
          p = param({'values', 'Each value will create a single AO.'}, paramValue.EMPTY_DOUBLE);
          out.append(p);
          
          % Yunits
          p = param({'yunits', 'Y-unit for the AOs which are built from the values'}, paramValue.EMPTY_CELL);
          out.append(p);
          
          % Names
          p = param({'names', 'Names for the AOs which are built from the values'}, paramValue.EMPTY_CELL);
          out.append(p);
          
      end
    end % function out = getDefaultPlist(varargin)
    
    function obj = initObjectWithSize(n,m)
      obj = matrix.newarray([n m]);
    end
    
  end % End static methods
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                         Methods (static, private)                         %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  
  methods (Static, Access=private)
    varargout = elementOp(varargin)
  end % End static, private methods
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                         Methods (static, hidden)                          % 
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  
  methods (Static = true, Hidden = true)
    varargout = loadobj(varargin)
    varargout = update_struct(varargin);
  end
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                             Methods (public)                              %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  methods
    
    varargout = char(varargin)
    varargout = display(varargin)
    varargout = copy(varargin)
    out       = det(varargin)
    out       = inv(varargin)
    varargout = minus(varargin)
    varargout = plus(varargin)
    varargout = rdivide(varargin)
    varargout = times(varargin)
    varargout = mtimes(varargin)
    varargout = transpose(varargin)
    varargout = ctranspose(varargin)
    varargout = filter(varargin)
    varargout = conj(varargin)
    varargout = nrows(varargin)
    varargout = ncols(varargin)
    varargout = osize(varargin)
    varargout = setObjs(varargin)
    varargout = getObjectAtIndex(varargin)
  end
  
  methods (Hidden = true)
    varargout = attachToDom(varargin)
  end
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                            Methods (protected)                            %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  methods (Access = protected)
    varargout = fromInput(varargin)
    varargout = fromStruct(varargin)
    varargout = fromDom(varargin)
  end
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %                           Methods (private)                               %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  methods (Access = private)
    % Constructors
    varargout = wrapper(varargin)
    a = fromCSD(a, pli)
    a = MultiChannelNoise(a, pli)
  end
  
end % End classdef

