## Copyright (C) 2016 Andreas Stahel
## Copyright (C) 2022-2023 Andreas Bertsatos <abertsatos@biol.uoa.gr>
##
## This file is part of the statistics package for GNU Octave.
##
## This program 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.
##
## This program 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
## this program; if not, see <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn  {statistics} {@var{y} =} pdf (@var{name}, @var{x}, @var{A})
## @deftypefnx {statistics} {@var{y} =} pdf (@var{name}, @var{x}, @var{A}, @var{B})
## @deftypefnx {statistics} {@var{y} =} pdf (@var{name}, @var{x}, @var{A}, @var{B}, @var{C})
##
## Return the PDF of a univariate distribution evaluated at @var{x}.
##
## @code{pdf} is a wrapper for the univariate cumulative distribution functions
## available in the statistics package.  See the corresponding functions' help
## to learn the signification of the parameters after @var{x}.
##
## @code{@var{y} = pdf (@var{name}, @var{x}, @var{A})} returns the CDF for the
## one-parameter distribution family specified by @var{name} and the
## distribution parameter @var{A}, evaluated at the values in @var{x}.
##
## @code{@var{y} = pdf (@var{name}, @var{x}, @var{A}, @var{B})} returns the CDF
## for the two-parameter distribution family specified by @var{name} and the
## distribution parameters @var{A} and @var{B}, evaluated at the values in
## @var{x}.
##
## @code{@var{y} = pdf (@var{name}, @var{x}, @var{A}, @var{B}, @var{C})} returns
## the CDF for the three-parameter distribution family specified by @var{name}
## and the distribution parameters @var{A}, @var{B}, and @var{C}, evaluated at
## the values in @var{x}.
##
## @var{name} must be a char string of the name or the abbreviation of the
## desired cumulative distribution function as listed in the following table.
## The last column shows the number of required parameters that should be parsed
## after @var{x} to the desired PDF.
##
## @multitable @columnfractions 0.4 0.2 0.3
## @headitem Distribution Name @tab Abbreviation @tab Input Parameters
## @item @qcode{'Beta'} @tab @qcode{'beta'} @tab 2
## @item @qcode{'Binomial'} @tab @qcode{'bino'} @tab 2
## @item @qcode{'Birnbaum-Saunders'} @tab @qcode{'bisa'} @tab 2
## @item @qcode{'Burr'} @tab @qcode{'burr'} @tab 3
## @item @qcode{'Cauchy'} @tab @qcode{'cauchy'} @tab 2
## @item @qcode{'Chi-squared'} @tab @qcode{'chi2'} @tab 1
## @item @qcode{'Extreme Value'} @tab @qcode{'ev'} @tab 2
## @item @qcode{'Exponential'} @tab @qcode{'exp'} @tab 1
## @item @qcode{'F-Distribution'} @tab @qcode{'f'} @tab 2
## @item @qcode{'Gamma'} @tab @qcode{'gam'} @tab 2
## @item @qcode{'Geometric'} @tab @qcode{'geo'} @tab 1
## @item @qcode{'Generalized Extreme Value'} @tab @qcode{'gev'} @tab 3
## @item @qcode{'Generalized Pareto'} @tab @qcode{'gp'} @tab 3
## @item @qcode{'Gumbel'} @tab @qcode{'gumbel'} @tab 2
## @item @qcode{'Half-normal'} @tab @qcode{'hn'} @tab 2
## @item @qcode{'Hypergeometric'} @tab @qcode{'hyge'} @tab 3
## @item @qcode{'Inverse Gaussian'} @tab @qcode{'invg'} @tab 2
## @item @qcode{'Laplace'} @tab @qcode{'laplace'} @tab 2
## @item @qcode{'Logistic'} @tab @qcode{'logi'} @tab 2
## @item @qcode{'Log-Logistic'} @tab @qcode{'logl'} @tab 2
## @item @qcode{'Lognormal'} @tab @qcode{'logn'} @tab 2
## @item @qcode{'Nakagami'} @tab @qcode{'naka'} @tab 2
## @item @qcode{'Negative Binomial'} @tab @qcode{'nbin'} @tab 2
## @item @qcode{'Noncentral F-Distribution'} @tab @qcode{'ncf'} @tab 3
## @item @qcode{'Noncentral Student T'} @tab @qcode{'nct'} @tab 2
## @item @qcode{'Noncentral Chi-Squared'} @tab @qcode{'ncx2'} @tab 2
## @item @qcode{'Normal'} @tab @qcode{'norm'} @tab 2
## @item @qcode{'Poisson'} @tab @qcode{'poiss'} @tab 1
## @item @qcode{'Rayleigh'} @tab @qcode{'rayl'} @tab 1
## @item @qcode{'Rician'} @tab @qcode{'rice'} @tab 2
## @item @qcode{'Student T'} @tab @qcode{'t'} @tab 1
## @item @qcode{'location-scale T'} @tab @qcode{'tls'} @tab 3
## @item @qcode{'Triangular'} @tab @qcode{'tri'} @tab 3
## @item @qcode{'Discrete Uniform'} @tab @qcode{'unid'} @tab 1
## @item @qcode{'Uniform'} @tab @qcode{'unif'} @tab 2
## @item @qcode{'Von Mises'} @tab @qcode{'vm'} @tab 2
## @item @qcode{'Weibull'} @tab @qcode{'wbl'} @tab 2
## @end multitable
##
## Distribution names are matched ignoring case, spaces and hyphens, so that
## @qcode{'Extreme Value'}, @qcode{'ExtremeValue'} and @qcode{'extreme-value'}
## all select the same distribution, and the same set of names is accepted by
## @code{cdf}, @code{pdf}, @code{icdf}, @code{random}, @code{makedist},
## @code{fitdist} and @code{mle}.
##
## This accepts more names than MATLAB.  MATLAB takes the spaced and the
## squashed spelling but refuses the hyphenated one, so
## @qcode{'Birnbaum-Saunders'} and @qcode{'Log-Logistic'} are errors there;
## Octave has always accepted them and continues to.  MATLAB also accepts
## @qcode{'tLocationScale'} in @code{makedist} while refusing it in
## @code{cdf} for the same distribution; Octave accepts it, and
## @qcode{'location-scale T'}, everywhere.  Code written against MATLAB's
## names therefore runs unchanged, but code relying on these names will not
## port back.
##
## @seealso{cdf, icdf, random, betapdf, binopdf, bisapdf, burrpdf, cauchypdf,
## chi2pdf, evpdf, exppdf, fpdf, gampdf, geopdf, gevpdf, gppdf, gumbelpdf,
## hnpdf, hygepdf, invgpdf, laplacepdf, logipdf, loglpdf, lognpdf, nakapdf,
## nbinpdf, ncfpdf, nctpdf, ncx2pdf, normpdf, poisspdf, raylpdf, ricepdf, tpdf,
## tlspdf, tripdf, unidpdf, unifpdf, vmpdf, wblpdf}
## @end deftypefn

function y = pdf (name, x, varargin)

  ## implemented functions
  persistent allDF = { ...
    {'beta'     , 'Beta'},                      @betapdf,      2, ...
    {'bino'     , 'Binomial'},                  @binopdf,      2, ...
    {'bisa'     , 'Birnbaum-Saunders'},         @bisapdf,      2, ...
    {'burr'     , 'Burr'},                      @burrpdf,      3, ...
    {'cauchy'   , 'Cauchy'},                    @cauchypdf,    2, ...
    {'chi2'     , 'Chi-squared'},               @chi2pdf,      1, ...
    {'ev'       , 'Extreme Value'},             @evpdf,        2, ...
    {'exp'      , 'Exponential'},               @exppdf,       1, ...
    {'f'        , 'F-Distribution'},            @fpdf,         2, ...
    {'gam'      , 'Gamma'},                     @gampdf,       2, ...
    {'geo'      , 'Geometric'},                 @geopdf,       1, ...
    {'gev'      , 'Generalized Extreme Value'}, @gevpdf,       3, ...
    {'gp'       , 'Generalized Pareto'},        @gppdf,        3, ...
    {'gumbel'   , 'Gumbel'},                    @gumbelpdf,    2, ...
    {'hn'       , 'Half-normal'},               @hnpdf,        2, ...
    {'hyge'     , 'Hypergeometric'},            @hygepdf,      3, ...
    {'invg'     , 'Inverse Gaussian'},          @invgpdf,      2, ...
    {'laplace'  , 'Laplace'},                   @laplacepdf,   2, ...
    {'logi'     , 'Logistic'},                  @logipdf,      2, ...
    {'logl'     , 'Log-Logistic'},              @loglpdf,      2, ...
    {'logn'     , 'Lognormal'},                 @lognpdf,      2, ...
    {'naka'     , 'Nakagami'},                  @nakapdf,      2, ...
    {'nbin'     , 'Negative Binomial'},         @nbinpdf,      2, ...
    {'ncf'      , 'Noncentral F-Distribution'}, @ncfpdf,       3, ...
    {'nct'      , 'Noncentral Student T'},      @nctpdf,       2, ...
    {'ncx2'     , 'Noncentral Chi-squared'},    @ncx2pdf,      2, ...
    {'norm'     , 'Normal'},                    @normpdf,      2, ...
    {'poiss'    , 'Poisson'},                   @poisspdf,     1, ...
    {'rayl'     , 'Rayleigh'},                  @raylpdf,      1, ...
    {'rice'     , 'Rician'},                    @ricepdf,      2, ...
    {'t'        , 'Student T'},                 @tpdf,         1, ...
    {'tls', 'location-scale T', 'tLocationScale'}, @tlspdf,       3, ...
    {'tri'      , 'Triangular'},                @tripdf,       3, ...
    {'unid'     , 'Discrete Uniform'},          @unidpdf,      1, ...
    {'unif'     , 'Uniform'},                   @unifpdf,      2, ...
    {'vm'       , 'Von Mises'},                 @vmpdf,        2, ...
    {'wbl'      , 'Weibull'},                   @wblpdf,       2};

  if (! ischar (name))
    error ("pdf: distribution NAME must a char string.");
  endif

  ## Check X being numeric and real
  if (! isnumeric (x))
    error ("pdf: X must be numeric.");
  elseif (! isreal (x))
    error ("pdf: values in X must be real.");
  endif

  ## Get number of arguments
  nargs = numel (varargin);

  ## Get available functions
  pdfnames = allDF(1:3:end);
  pdfhandl = allDF(2:3:end);
  pdf_args = allDF(3:3:end);

  ## Search for PDF function
  ## Match on the folded key so that every spelling of a name resolves
  key = __distname_key__ (name);
  idx = cellfun (@(x) any (strcmp (key, cellfun (@__distname_key__, x, ...
                                   'UniformOutput', false))), pdfnames);

  if (any (idx))

    if (nargs == pdf_args{idx})
      ## Check that all distribution parameters are numeric
      if (! all (cellfun (@(x)isnumeric (x), (varargin))))
        error ("pdf: distribution parameters must be numeric.");
      endif
      ## Call appropriate iCDF
      y = feval (pdfhandl{idx}, x, varargin{:});

    else
      if (pdf_args{idx} == 1)
        error ("pdf: %s distribution requires 1 parameter.", name);
      else
        error ("pdf: %s distribution requires %d parameters.", ...
               name, pdf_args{idx});
      endif

    endif

  else
    error ("pdf: %s distribution is not implemented in Statistics.", name);
  endif

endfunction

## Test results
%!shared x
%! x = [1:5];
%!assert_equal (pdf ('Beta', x, 5, 2), betapdf (x, 5, 2))
%!assert_equal (pdf ('beta', x, 5, 2), betapdf (x, 5, 2))
%!assert_equal (pdf ('Binomial', x, 5, 2), binopdf (x, 5, 2))
%!assert_equal (pdf ('bino', x, 5, 2), binopdf (x, 5, 2))
%!assert_equal (pdf ('Birnbaum-Saunders', x, 5, 2), bisapdf (x, 5, 2))
%!assert_equal (pdf ('bisa', x, 5, 2), bisapdf (x, 5, 2))
%!assert_equal (pdf ('Burr', x, 5, 2, 2), burrpdf (x, 5, 2, 2))
%!assert_equal (pdf ('burr', x, 5, 2, 2), burrpdf (x, 5, 2, 2))
%!assert_equal (pdf ('Cauchy', x, 5, 2), cauchypdf (x, 5, 2))
%!assert_equal (pdf ('cauchy', x, 5, 2), cauchypdf (x, 5, 2))
%!assert_equal (pdf ('Chi-squared', x, 5), chi2pdf (x, 5))
%!assert_equal (pdf ('chi2', x, 5), chi2pdf (x, 5))
%!assert_equal (pdf ('Extreme Value', x, 5, 2), evpdf (x, 5, 2))
%!assert_equal (pdf ('ev', x, 5, 2), evpdf (x, 5, 2))
%!assert_equal (pdf ('Exponential', x, 5), exppdf (x, 5))
%!assert_equal (pdf ('exp', x, 5), exppdf (x, 5))
%!assert_equal (pdf ('F-Distribution', x, 5, 2), fpdf (x, 5, 2))
%!assert_equal (pdf ('f', x, 5, 2), fpdf (x, 5, 2))
%!assert_equal (pdf ('Gamma', x, 5, 2), gampdf (x, 5, 2))
%!assert_equal (pdf ('gam', x, 5, 2), gampdf (x, 5, 2))
%!assert_equal (pdf ('Geometric', x, 5), geopdf (x, 5))
%!assert_equal (pdf ('geo', x, 5), geopdf (x, 5))
%!assert_equal (pdf ('Generalized Extreme Value', x, 5, 2, 2), gevpdf (x, 5, 2, 2))
%!assert_equal (pdf ('gev', x, 5, 2, 2), gevpdf (x, 5, 2, 2))
%!assert_equal (pdf ('Generalized Pareto', x, 5, 2, 2), gppdf (x, 5, 2, 2))
%!assert_equal (pdf ('gp', x, 5, 2, 2), gppdf (x, 5, 2, 2))
%!assert_equal (pdf ('Gumbel', x, 5, 2), gumbelpdf (x, 5, 2))
%!assert_equal (pdf ('gumbel', x, 5, 2), gumbelpdf (x, 5, 2))
%!assert_equal (pdf ('Half-normal', x, 5, 2), hnpdf (x, 5, 2))
%!assert_equal (pdf ('hn', x, 5, 2), hnpdf (x, 5, 2))
%!assert_equal (pdf ('Hypergeometric', x, 5, 2, 2), hygepdf (x, 5, 2, 2))
%!assert_equal (pdf ('hyge', x, 5, 2, 2), hygepdf (x, 5, 2, 2))
%!assert_equal (pdf ('Inverse Gaussian', x, 5, 2), invgpdf (x, 5, 2))
%!assert_equal (pdf ('invg', x, 5, 2), invgpdf (x, 5, 2))
%!assert_equal (pdf ('Laplace', x, 5, 2), laplacepdf (x, 5, 2))
%!assert_equal (pdf ('laplace', x, 5, 2), laplacepdf (x, 5, 2))
%!assert_equal (pdf ('Logistic', x, 5, 2), logipdf (x, 5, 2))
%!assert_equal (pdf ('logi', x, 5, 2), logipdf (x, 5, 2))
%!assert_equal (pdf ('Log-Logistic', x, 5, 2), loglpdf (x, 5, 2))
%!assert_equal (pdf ('logl', x, 5, 2), loglpdf (x, 5, 2))
%!assert_equal (pdf ('Lognormal', x, 5, 2), lognpdf (x, 5, 2))
%!assert_equal (pdf ('logn', x, 5, 2), lognpdf (x, 5, 2))
%!assert_equal (pdf ('Nakagami', x, 5, 2), nakapdf (x, 5, 2))
%!assert_equal (pdf ('naka', x, 5, 2), nakapdf (x, 5, 2))
%!assert_equal (pdf ('Negative Binomial', x, 5, 2), nbinpdf (x, 5, 2))
%!assert_equal (pdf ('nbin', x, 5, 2), nbinpdf (x, 5, 2))
%!assert_equal (pdf ('Noncentral F-Distribution', x, 5, 2, 2), ncfpdf (x, 5, 2, 2))
%!assert_equal (pdf ('ncf', x, 5, 2, 2), ncfpdf (x, 5, 2, 2))
%!assert_equal (pdf ('Noncentral Student T', x, 5, 2), nctpdf (x, 5, 2))
%!assert_equal (pdf ('nct', x, 5, 2), nctpdf (x, 5, 2))
%!assert_equal (pdf ('Noncentral Chi-Squared', x, 5, 2), ncx2pdf (x, 5, 2))
%!assert_equal (pdf ('ncx2', x, 5, 2), ncx2pdf (x, 5, 2))
%!assert_equal (pdf ('Normal', x, 5, 2), normpdf (x, 5, 2))
%!assert_equal (pdf ('norm', x, 5, 2), normpdf (x, 5, 2))
%!assert_equal (pdf ('Poisson', x, 5), poisspdf (x, 5))
%!assert_equal (pdf ('poiss', x, 5), poisspdf (x, 5))
%!assert_equal (pdf ('Rayleigh', x, 5), raylpdf (x, 5))
%!assert_equal (pdf ('rayl', x, 5), raylpdf (x, 5))
%!assert_equal (pdf ('Rician', x, 5, 1), ricepdf (x, 5, 1))
%!assert_equal (pdf ('rice', x, 5, 1), ricepdf (x, 5, 1))
%!assert_equal (pdf ('Student T', x, 5), tpdf (x, 5))
%!assert_equal (pdf ('t', x, 5), tpdf (x, 5))
%!assert_equal (pdf ('location-scale T', x, 5, 1, 2), tlspdf (x, 5, 1, 2))
%!assert_equal (pdf ('tls', x, 5, 1, 2), tlspdf (x, 5, 1, 2))
%!assert_equal (pdf ('Triangular', x, 5, 2, 2), tripdf (x, 5, 2, 2))
%!assert_equal (pdf ('tri', x, 5, 2, 2), tripdf (x, 5, 2, 2))
%!assert_equal (pdf ('Discrete Uniform', x, 5), unidpdf (x, 5))
%!assert_equal (pdf ('unid', x, 5), unidpdf (x, 5))
%!assert_equal (pdf ('Uniform', x, 5, 2), unifpdf (x, 5, 2))
%!assert_equal (pdf ('unif', x, 5, 2), unifpdf (x, 5, 2))
%!assert_equal (pdf ('Von Mises', x, 5, 2), vmpdf (x, 5, 2))
%!assert_equal (pdf ('vm', x, 5, 2), vmpdf (x, 5, 2))
%!assert_equal (pdf ('Weibull', x, 5, 2), wblpdf (x, 5, 2))
%!assert_equal (pdf ('wbl', x, 5, 2), wblpdf (x, 5, 2))

## Test input validation
%!test
%! ## Every spelling of a name reaches the same distribution: case, spaces,
%! ## hyphens and underscores are all ignored.
%! for n = {'Extreme Value', 'ExtremeValue', 'extreme-value', 'EXTREME VALUE'}
%!   assert_equal (pdf (n{1}, 1, 2, 3), pdf ('ev', 1, 2, 3));
%! endfor

%!test
%! ## The name that makedist uses is accepted here too, and the reverse
%! assert_equal (pdf ('tLocationScale', 1, 2, 3, 4), pdf ('tls', 1, 2, 3, 4));

%!error<pdf: distribution NAME must a char string.> pdf (1)
%!error<pdf: distribution NAME must a char string.> pdf ({'beta'})
%!error<pdf: X must be numeric.> pdf ('beta', {[1 2 3 4 5]})
%!error<pdf: X must be numeric.> pdf ('beta', 'text')
%!error<pdf: values in X must be real.> pdf ('beta', 1+i)
%!error<pdf: distribution parameters must be numeric.> ...
%! pdf ('Beta', x, 'a', 2)
%!error<pdf: distribution parameters must be numeric.> ...
%! pdf ('Beta', x, 5, '')
%!error<pdf: distribution parameters must be numeric.> ...
%! pdf ('Beta', x, 5, {2})
%!error<pdf: chi2 distribution requires 1 parameter.> pdf ('chi2', x)
%!error<pdf: Beta distribution requires 2 parameters.> pdf ('Beta', x, 5)
%!error<pdf: Burr distribution requires 3 parameters.> pdf ('Burr', x, 5)
%!error<pdf: Burr distribution requires 3 parameters.> pdf ('Burr', x, 5, 2)
