% UTP_AO_PSD a set of UTPs for the ao/firwhiten method
%
% M Hewitson 06-08-08
%
% $Id: utp_ao_firwhiten.m,v 1.21 2011/11/16 08:16:08 mauro Exp $
%

% <MethodDescription>
%
% The firwhiten method of the ao class computes the spectral density of time-series AOs.
%
% </MethodDescription>

function results = utp_ao_firwhiten(varargin)

  % Check the inputs
  if nargin == 0

    % Some keywords
    class   = 'ao';
    mthd    = 'firwhiten';

    results = [];
    disp('******************************************************');
    disp(['****  Running UTPs for ' class '/' mthd]);
    disp('******************************************************');

    % Test AOs
    [at1,at2,at3,at4,at5,at6,atvec,atmat] = eval(['get_test_objects_' class]);

    % Exception list for the UTPs:
    [ple1,ple2,ple3,ple4,ple5,ple6] = get_test_ples();

    % Run the tests
    results = [results utp_01];    % getInfo call
    results = [results utp_02];    % Vector input
    results = [results utp_03];    % Matrix input
    results = [results utp_04];    % List input
    results = [results utp_05];    % Test with mixed input
    results = [results utp_06];    % Test history is working
    results = [results utp_07];    % Test the modify call works
    results = [results utp_08];    % Test the data shape
    results = [results utp_09];    % Test with complex plist
    results = [results utp_10];    % Test the spectral falttening
    results = [results utp_11(mthd, at1, ple1)];    % Test plotinfo doesn't disappear    
    results = [results utp_12(mthd, at1, ple1)];    % Test errors are cleared

    disp('Done.');
    disp('******************************************************');

  elseif nargin == 1 % Check for UTP functions
    if strcmp(varargin{1}, 'isutp')
      results = 1;
    else
      results = 0;
    end
  else
    error('### Incorrect inputs')
  end

  %% UTP_01

  % <TestDescription>
  %
  % Tests that the getInfo call works for this method.
  %
  % </TestDescription>
  function result = utp_01


    % <SyntaxDescription>
    %
    % Test that the getInfo call works for no sets, all sets, and each set
    % individually.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      % Call for no sets
      io(1) = eval([class '.getInfo(''' mthd ''', ''None'')']);
      % Call for all sets
      io(2) = eval([class '.getInfo(''' mthd ''')']);
      % Call for each set
      for kk=1:numel(io(2).sets)
        io(kk+2) = eval([class '.getInfo(''' mthd ''', ''' io(2).sets{kk} ''')']);
      end
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check that getInfo call returned an minfo object in all cases.
    % 2) Check that all plists have the correct parameters.
    %
    % </AlgoDescription>

    atest = true;
    if stest
      % <AlgoCode>
      % check we have minfo objects
      if isa(io, 'minfo')
        prefs = getappdata(0, 'LTPDApreferences');
        defaultWinType = char(prefs.getMiscPrefs.getDefaultWindow);
        
        %%% SET 'None'
        pn = 1;
        if ~isempty(io(pn).sets), atest = false; end
        if ~isempty(io(pn).plists), atest = false; end
        %%% Check all Sets
        pn = 2;
        if ~any(strcmpi(io(pn).sets, 'Default')), atest = false; end
        if numel(io(pn).plists) ~= numel(io(pn).sets), atest = false; end
        %%%%%%%%%%   SET 'Default'
        pn = 3;
        if io(pn).plists.nparams ~= 7, atest = false; end
        % Check key
        if ~io(pn).plists.isparam('nfft'), atest = false; end
        if ~io(pn).plists.isparam('bw'), atest = false; end
        if ~io(pn).plists.isparam('hc'), atest = false; end
        if ~io(pn).plists.isparam('win'), atest = false; end
        if ~io(pn).plists.isparam('order'), atest = false; end
        if ~io(pn).plists.isparam('firwin'), atest = false; end
        if ~io(pn).plists.isparam('ntaps'), atest = false; end
        % Check default value
        if ~isequal(io(pn).plists.find('nfft'), -1), atest = false; end
        if ~isequal(io(pn).plists.find('bw'), 20), atest = false; end
        if ~isequal(io(pn).plists.find('hc'), .8), atest = false; end
        if ~strcmpi(io(pn).plists.find('win'), defaultWinType), atest = false; end
        if ~isequal(io(pn).plists.find('order'), -1), atest = false; end
        if ~strcmpi(io(pn).plists.find('win'), defaultWinType), atest = false; end
        if ~isequal(io(pn).plists.find('ntaps'), 256), atest = false; end
        % Check options
        if ~isequal(io(pn).plists.getOptionsForParam('nfft'), {-1}), atest = false; end
        if ~isequal(io(pn).plists.getOptionsForParam('bw'), {20}), atest = false; end
        if ~isequal(io(pn).plists.getOptionsForParam('hc'), {.8}), atest = false; end
        if ~isequal(io(pn).plists.getOptionsForParam('win'), specwin.getTypes), atest = false; end
        if ~isequal(io(pn).plists.getOptionsForParam('order'), {-1 0 1 2 3 4 5 6 7 8 9}), atest = false; end
        if ~isequal(io(pn).plists.getOptionsForParam('firwin'), specwin.getTypes), atest = false; end
        if ~isequal(io(pn).plists.getOptionsForParam('ntaps'), {256}), atest = false; end
      end
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_01

  %% UTP_02

  % <TestDescription>
  %
  % Tests that the firwhiten method works with a vector of AOs as input.
  %
  % </TestDescription>
  function result = utp_02

    % <SyntaxDescription>
    %
    % Test that the firwhiten method works for a vector of AOs as input.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      avec  = [at5 at5 at6];
      N     = 512;
      fwin  = specwin('Hanning', N+1);
      [out, outf, outxx] = firwhiten(avec, plist('Ntaps', N, 'FIRwin', fwin));
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check the number of elements in 'out'
    % 2) Check the number of filters (outf) and noise-floor estimates (outxx)
    % 3) Check that each output AO contains the correct data.
    %
    % </AlgoDescription>

    atest = true;
    if stest
      % <AlgoCode>
      % Check we have the correct number of outputs
      if numel(out)   ~= numel(avec), atest = false; end
      if numel(outf)  ~= numel(avec), atest = false; end
      if numel(outxx) ~= numel(avec), atest = false; end
      % Check the output data
      prefs = getappdata(0, 'LTPDApreferences');  
      swin = char(prefs.getMiscPrefs.getDefaultWindow);
      for kk = 1:numel(avec)
        pl_psd = plist('Nfft', length(avec(kk).y), 'Win', specwin(swin), 'Order', -1, 'Scale', 'ASD');
        axx = psd(avec(kk), pl_psd);
        nxx = smoother(axx, plist('width', 20, 'hc', 0.8));
        w   = 1./nxx;
        ff  = mfir(w, plist('Win', fwin, 'N', N));
        res = filter(avec(kk), ff);
        if ~isequal(res.x, out(kk).x), atest = false; end
        if ~isequal(res.y, out(kk).y), atest = false; end
      end
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_02

  %% UTP_03

  % <TestDescription>
  %
  % Tests that the firwhiten method works with a matrix of AOs as input.
  %
  % </TestDescription>
  function result = utp_03

    % <SyntaxDescription>
    %
    % Test that the firwhiten method works for a matrix of AOs as input.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      amat = [at1 at5 at6; at5 at6 at1];
      N     = 512;
      fwin  = specwin('Hanning', N+1);
      [out, outf, outxx] = firwhiten(amat, plist('Ntaps', N, 'FIRwin', fwin));
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check the number of elements in 'out'
    % 2) Check the number of filters (outf) and noise-floor estimates (outxx)
    % 3) Check that each output AO contains the correct data.
    %
    % </AlgoDescription>

    atest = true;
    if stest
      % <AlgoCode>
      % Check we have the correct number of outputs
      if numel(out)   ~= numel(amat), atest = false; end
      if numel(outf)  ~= numel(amat), atest = false; end
      if numel(outxx) ~= numel(amat), atest = false; end
      % Check the output data
      prefs = getappdata(0, 'LTPDApreferences');  
      swin = char(prefs.getMiscPrefs.getDefaultWindow);
      for kk = 1:numel(amat)
        pl_psd = plist('Nfft', length(amat(kk).y), 'Win', specwin(swin), 'Order', -1, 'Scale', 'ASD');
        axx = psd(amat(kk), pl_psd);
        nxx = smoother(axx, plist('width', 20, 'hc', 0.8));
        w   = 1./nxx;
        ff  = mfir(w, plist('Win', fwin, 'N', N));
        res = filter(amat(kk), ff);
        if ~isequal(res.x, out(kk).x), atest = false; end
        if ~isequal(res.y, out(kk).y), atest = false; end
      end
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_03

  %% UTP_04

  % <TestDescription>
  %
  % Tests that the firwhiten method works with a list of AOs as input.
  %
  % </TestDescription>
  function result = utp_04

    % <SyntaxDescription>
    %
    % Test that the firwhiten method works for a list of AOs as input.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      N     = 512;
      fwin  = specwin('Hanning', N+1);
      [out, outf, outxx] = firwhiten(at1,at5,at6, plist('Ntaps', N, 'FIRwin', fwin));
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check the number of elements in 'out'
    % 2) Check the number of filters (outf) and noise-floor estimates (outxx)
    % 3) Check that each output AO contains the correct data.
    %
    % </AlgoDescription>

    atest = true;
    aoin  = [at1, at5, at6];
    if stest
      % <AlgoCode>
      % Check we have the correct number of outputs
      if numel(out)   ~= 3, atest = false; end
      if numel(outf)  ~= 3, atest = false; end
      if numel(outxx) ~= 3, atest = false; end
      % Check the output data
      prefs = getappdata(0, 'LTPDApreferences');  
      swin = char(prefs.getMiscPrefs.getDefaultWindow);
      for kk = 1:numel(aoin)
        pl_psd = plist('Nfft', length(aoin(kk).y), 'Win', specwin(swin), 'Order', -1, 'Scale', 'ASD');
        axx = psd(aoin(kk), pl_psd);
        nxx = smoother(axx, plist('width', 20, 'hc', 0.8));
        w   = 1./nxx;
        ff  = mfir(w, plist('Win', fwin, 'N', N));
        res = filter(aoin(kk), ff);
        if ~isequal(res.x, out(kk).x), atest = false; end
        if ~isequal(res.y, out(kk).y), atest = false; end
      end
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_04

  %% UTP_05

  % <TestDescription>
  %
  % Tests that the firwhiten method works with a mix of different shaped AOs as
  % input.
  %
  % </TestDescription>
  function result = utp_05

    % <SyntaxDescription>
    %
    % Test that the firwhiten method works with an input of matrices and vectors
    % and single AOs.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      N     = 512;
      fwin  = specwin('Hanning', N+1);
      pl    = plist('Ntaps', N, 'FIRwin', fwin);
      [out, outf, outxx] = firwhiten(at1,[at5 at6],at5,[at5 at1; at6 at1],at6, pl);
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check the number of elements in 'out'
    % 2) Check the number of filters (outf) and noise-floor estimates (outxx)
    % 3) Check that each output AO contains the correct data.
    %
    % </AlgoDescription>

    atest = true;
    aoin  = [at1, reshape([at5 at6], 1, []), at5, reshape([at5 at1; at6 at1], 1, []), at6];
    if stest
      % <AlgoCode>
      % Check we have the correct number of outputs
      if numel(out)   ~= 9, atest = false; end
      if numel(outf)  ~= 9, atest = false; end
      if numel(outxx) ~= 9, atest = false; end
      % Check the output data
      prefs = getappdata(0, 'LTPDApreferences');  
      swin = char(prefs.getMiscPrefs.getDefaultWindow);
      for kk = 1:numel(aoin)
        pl_psd = plist('Nfft', length(aoin(kk).y), 'Win', specwin(swin), 'Order', -1, 'Scale', 'ASD');
        axx = psd(aoin(kk), pl_psd);
        nxx = smoother(axx, plist('width', 20, 'hc', 0.8));
        w   = 1./nxx;
        ff  = mfir(w, plist('Win', fwin, 'N', N));
        res = filter(aoin(kk), ff);
        if ~isequal(res.x, out(kk).x), atest = false; end
        if ~isequal(res.y, out(kk).y), atest = false; end
      end
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_05

  %% UTP_06

  % <TestDescription>
  %
  % Tests that the firwhiten method properly applies history.
  %
  % </TestDescription>
  function result = utp_06

    % <SyntaxDescription>
    %
    % Test that the result of applying the firwhiten method can be processed back
    % to an m-file.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      N     = 512;
      fwin  = specwin('Hanning', N+1);
      pl    = plist('Ntaps', N, 'FIRwin', fwin);
      out  = firwhiten(at5, pl);
      mout = rebuild(out);
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check that the last entry in the history of 'out' corresponds to
    %    'firwhiten'.
    % 2) Check that the re-built object is the same object as 'out'.
    %
    % </AlgoDescription>

    atest = true;
    if stest
      % <AlgoCode>
      % Check the last step in the history of 'out'
      if ~strcmp(out.hist.methodInfo.mname, 'firwhiten'), atest = false; end
      % Check the re-built object
      if ~eq(mout, out, ple4), atest = false; end
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_06

  %% UTP_07

  % <TestDescription>
  %
  % Tests that the firwhiten method can modify the input AO.
  %
  % </TestDescription>
  function result = utp_07

    % <SyntaxDescription>
    %
    % Test that the firwhiten method can modify the input AO by calling
    % with no output.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      N    = 512;
      fwin = specwin('Hanning', N+1);
      pl   = plist('Ntaps', N, 'FIRwin', fwin);
      % copy at1 to work with
      ain  = ao(at1);
      % modify ain
      aout = ain.firwhiten(pl);
      ain.firwhiten(pl);
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check that 'at1' and 'ain' are now different.
    % 2) Check that 'ain' is firwhiten(at1).
    %
    % </AlgoDescription>

    atest = true;
    if stest
      % <AlgoCode>
      % Check that firwhiten modified the input by comparing to the copy
      if eq(ao(at1), ain, ple1), atest = false; end
      % Check that firwhiten doesn't modified the input for the function notation
      if ~eq(aout, ain, ple1), atest = false; end
      % Check that the modified input is the firwhiten of the copy
      % Check the output data of ain
      prefs = getappdata(0, 'LTPDApreferences');  
      swin = char(prefs.getMiscPrefs.getDefaultWindow);
      pl_psd = plist('Nfft', length(at1.y), 'Win', specwin(swin), 'Order', -1, 'Scale', 'ASD');
      axx = psd(at1, pl_psd);
      nxx = smoother(axx, plist('width', 20, 'hc', 0.8));
      w   = 1./nxx;
      ff  = mfir(w, plist('Win', fwin, 'N', N));
      res = filter(at1, ff);
      if ~isequal(res.x, ain.x), atest = false; end
      if ~isequal(res.y, ain.y), atest = false; end
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_07

  %% UTP_08

  % <TestDescription>
  %
  % Tests that the firwhiten method keeps the data shape of the input object.
  %
  % </TestDescription>
  function result = utp_08

    % <SyntaxDescription>
    %
    % Test that the firwhiten method keeps the data shape of the input object. The
    % input AO must be an AO with row data and an AO with column data.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      N    = 512;
      fwin = specwin('Hanning', N+1);
      pl   = plist('Ntaps', N, 'FIRwin', fwin);
      out1   = firwhiten(at5, pl);
      out2   = firwhiten(at6, pl);
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check that the shpe of the data doesn't change.
    %
    % </AlgoDescription>

    atest = true;
    if stest
      % <AlgoCode>
      % Check the shape of the output data
      if size(out1.data.y,2) ~= 1, atest = false; end
      if size(out2.data.y,1) ~= 1, atest = false; end
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_08

  %% UTP_09

  % <TestDescription>
  %
  % Tests that the firwhiten method with a complex plist.
  %
  % </TestDescription>
  function result = utp_09

    % <SyntaxDescription>
    %
    % Test that the result of applying the firwhiten method with a complex plist
    % can be processed back to a m-file.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      N     = 512;
      Nfft  = 100;
      order = 1;
      fwin  = specwin('Hanning', N+1);
      swin  = specwin('Kaiser', 10, 100);
      pl    = plist('Ntaps', N, 'FIRwin', fwin, 'win', swin, 'Nfft', Nfft, 'order', order);
      [out, outf, outxx] = firwhiten(at5, pl);
      mout = rebuild(out);
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Check the output data
    % 2) Check the output filter
    % 3) Check the noise-floor estimates
    % 4) Check that the re-built object is the same object as 'out'.
    %
    % </AlgoDescription>

    atest = true;
    if stest
      % <AlgoCode>
      % Check the last step in the history of 'out'
      if ~strcmp(out.hist.methodInfo.mname, 'firwhiten'), atest = false; end
      % Check the re-built object
      if ~eq(mout, out, ple2), atest = false; end

      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_09
  
  %% UTP_10

  % <TestDescription>
  %
  % Test the spectral falttening capability of firwhiten method.
  %
  % </TestDescription>
  function result = utp_10

    % <SyntaxDescription>
    %
    % Test that the application of the firwhiten method enhances the
    % spectral flatness of input data.
    %
    % </SyntaxDescription>

    try
      % <SyntaxCode>
      % Making test data
      fs = at5.fs;
      pzm = pzmodel(2, [pz(0.1, 2) pz(0.5, 1)] , [pz(1) pz(2.55, 2)]);
      ft = miir(pzm,plist('fs',fs));
      af = filter(at5, ft); % Colored noise
      
      % Whitening
      N     = 512;
      Nfft  = 100;
      order = 1;
      fwin  = specwin('Hanning', N+1);
      swin  = specwin('Kaiser', 10, 100);
      pl    = plist('Ntaps', N, 'FIRwin', fwin, 'win', swin, 'Nfft', Nfft, 'order', order);
      out = firwhiten(af, pl);
      
      % </SyntaxCode>
      stest = true;
    catch err
      disp(err.message)
      stest = false;
    end

    % <AlgoDescription>
    %
    % 1) Calculate PSD of input and whitened data
    % 2) Compare relative spectral flatness coefficients
    %
    % </AlgoDescription>

    atest = true;
    if stest
      % <AlgoCode>
      % Check the output data
%       pl_psd = plist('Nfft', Nfft, 'Win', swin, 'Order', order, 'Scale', 'PSD');
      axx = af.psd;
      awxx = out.psd;
      
      % Claculating flatness
      sf1 = utils.math.spflat(axx.data.y);
      sf2 = utils.math.spflat(awxx.data.y);
      
      % Checking flatness
      if sf1>sf2, atest = false; end
     
      % </AlgoCode>
    else
      atest = false;
    end

    % Return a result structure
    result = utp_prepare_result(atest, stest, dbstack, mfilename);
  end % END UTP_10
  
  

end
