## Copyright (C) 2016 John W. Eaton
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or (at
## your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING.  If not, see
## <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn {} {@var{R} =} corrcoef (@var{X})
## @deftypefnx {} {@var{R} =} corrcoef (@var{X}, @var{Y})
## @deftypefnx {} {[@var{R}, @var{P}] =} corrcoef (@dots{})
## @deftypefnx {} {[@var{R}, @var{P}, @var{LCI}, @var{HCI}] =} corrcoef (@dots{})
## @deftypefnx {} {[@dots{}] =} corrcoef (@dots{}, @var{Param}, @var{Value}, @dots{})
## Compute a matrix of correlation coefficients.
##
## @var{X} is an array where each column contains a variable.
##
## If provided, @var{Y} is a vector of the same size than @var{X} and
## corrcoef([X(:), Y(:)]) is returned.
##
## @var{R} is a matrix of Pearson's product moment correlation
## coefficients for each pair of variables.
##
## @var{P} is a matrix of pair-wise p-values testing for the null
## hypothesis of a correlation coefficient of zero.
##
## @var{LCI} and @var{HCI} are matrices containing, respectively, the
## lower and higher bounds of the 95% confidence interval of each
## correlation coefficient.
##
## @var{Param}, @var{Value} are pairs of optional parameters and values.
## Options are:
## 
## @table @asis
## @item @qcode{"alpha"}
## Confidence level used for the definition of the bounds of the confidence
## interval, @var{LCI} and @var{HCI}. Default is 0.05, i.e. 95% confidence
## interval.
## 
## @item @qcode{"rows"}
## Handling of NaN values.  Acceptable values are "all", "complete" and
## "pairwise". Default is "all". With "complete", only the rows without
## NaN values are considered. With "pairwise", the selection of NaN-free
## rows is made for each pair of variables.
## 
## @end table
##
## @seealso{corr, cov, cor_test}
## @end deftypefn

## Author: jwe

function [R, P, LCI, HCI] = corrcoef (X, varargin)

  if (nargin == 0)
    print_usage ();
  endif

  alpha = 0.05;
  rows = "all";
  
  if (nargin > 1)
    if (isnumeric (varargin{1}))
      X = [X(:) varargin{1}(:)];
      varargin(1) = [];
    endif
    for i=1:2:numel (varargin)
      if (ischar (varargin{i}))
        parameter = varargin{i};
      else
        error ("Wrong type argument '%s'.",class (varargin{i}));
      endif
      if (numel (varargin) < i+1)
        error ("Parameter '%s' missing value.", parameter);
      else
        value = varargin{i+1};
      endif
      switch (lower (parameter))
        case "alpha"
          if (isnumeric (value) && numel (value) == 1 && value >=0 && value <= 1) 
            alpha = value;
          else
            error ("'alpha' is a number between 0 and 1.");
          endif
        case "rows"
          if (ischar (value))
            switch lower (value)
              case {"all", "complete", "pairwise"}
                rows = lower (value);
              otherwise
                error ("'rows' is either 'all', 'complete' or 'pairwise'.");
            endswitch
          else
            error ("'rows' is a string.");
          endif
        otherwise
          error ("Unknown option '%s'.", parameter);
      endswitch
    endfor
  endif
  
  if (strcmp (rows, "complete"))
    X(any (isnan (X), 2), :) = [];
  endif
  
  
  if (isempty (X) || (numel (X) == 1))
    R = P = LCI = HCI = NaN;
    return;
  endif
  
  if (size (X, 1) == 1)
    X = X';
  endif
  [M, N] = size (X);
  R = eye (N);
  if (nargout > 1)
    P = eye (N);
  endif
  if (strcmp (rows, "pairwise"))
    Mpw = M * ones(N);
  endif
  for i=1:N
    if (any (isnan (X(:,i))) && !strcmp (rows, "pairwise"))
      R(i,i) = NaN;
      if (nargout > 1)
        P(i,i) = NaN;
      endif
    endif
    for j=i+1:N
      Xi = X(:,i);
      Xj = X(:,j);
      if (strcmp (rows, "pairwise"))
        idx = any (isnan ([Xi Xj]), 2);
        Xi(idx) = Xj(idx) = [];
        Mpw(i,j) = Mpw(j,i) = M - nnz (idx);
      endif
      R(i,j) = R(j,i) = corr (Xi, Xj);
      if (nargout > 1)
        T = cor_test (Xi, Xj, "!=", "pearson");
        P(i,j) = P(j,i) = T.pval;
      endif
    endfor
  endfor

  if (nargout > 2)
    if (strcmp (rows, "pairwise"))
      M = Mpw;
    endif
    CI = sqrt (2) * erfinv (1-alpha) ./ sqrt (M-3);
    LCI = tanh (atanh (R) - CI);
    HCI = tanh (atanh (R) + CI);
  endif

endfunction


%!test
%! X = rand (5);
%! R = corrcoef (X);
%! assert (size (R) == [5, 5]);

%!test
%! X = [1 2 3];
%! R = corrcoef (X);
%! assert (size (R) == [1, 1]);

%!test
%! X = [];
%! R = corrcoef (X);
%! assert (isnan (R));

%!test
%! X = [NaN];
%! R = corrcoef (X);
%! assert (isnan (R));

%!test
%! X = [1];
%! R = corrcoef (X);
%! assert (isnan (R));

%!test
%! X = [NaN NaN];
%! R = corrcoef (X);
%! assert (size(R) == [1, 1] && isnan (R));

%!test
%! X = rand (5);
%! [R, P] = corrcoef (X);
%! assert (size (R) == [5, 5] && size(P) == [5 5]);

%!test
%! X = rand (5,1);
%! Y = rand (5,1);
%! R1 = corrcoef (X, Y);
%! R2 = corrcoef ([X, Y]);
%! assert (R1, R2, eps);

%!test
%!error corrcoef ();
%!error corrcoef (1, 2, 3);
%!error corrcoef (1, 2, 'no');
%!error corrcoef (1, 2, 'rows');
