%function nb = bsspartitionsize(n,ndim)
function npart = bsspartitionsize(x)
%BSSPARTITIONSIZE - Compute optimal number of histogram bins for the data.
%
% INPUTS:
%
%    x:
%       The data to be used for the B-Spline density estimation. This
%       must be a column oriented array with each row representing a data
%       point, X(NDATA,NDIM) in size. Values of X outside the estimation
%       bounds are ignored.
%
% OUTPUTS:
%
%    nb:
%       An estimate of the optimal number of uniform width bins for a
%       B-spline series using n data points.
%
%       Note that multipliers were determined empirically. The cube root is
%       a theoretical result.
%

%
% Copyright 2014-2022 Biometrics Northwest LLC
%


%
% Modified: 2022-12-04
% Author : Kevin R. Gehringer
%
%    Changed the input from number of points and dimension to the data
%    matrix. This simplified a variety of things, including removing a
%    variety of input validation tests.
%
% Modified: 2018-08-28
% Author : Kevin R. Gehringer
%
%     Modified the automatically generated partition sizes making them
%     larger for dimensions greater than one to improve the PDF agreement
%     when not specifying a custom partition size.
%
% Modified: 2016-10-26
% Author : Kevin R. Gehringer
%
%   Changed all of the multipliers to improve the smoothness of continuous
%   distributions slightly.  There are still too many, but erring on the
%   side of undersmoothing is the right way to go.
%
% Modified: 2016-04-02
% Author : Kevin R. Gehringer
%
%   Changed the multiplier on N^(-1/3) from 2 to 3. This improves the 1-D
%   approximation.
%
% Created: 2014-11-25
% Author : Kevin R. Gehringer
%

[n,ndim] = size(x);

switch ndim
    case 1
        npart = 1+floor(2.0*n.^(1/3));
    case 2
        npart = repmat(1+floor(1.5*n.^(1/3)),ndim,1);
    case 3
        npart = repmat(1+floor(1.3*n.^(1/3)),ndim,1);
    otherwise
        npart = repmat(1+floor(1.1*n.^(1/3)),ndim,1);
end

std_x  = std(x)';
if ( any(std_x > 1))
    npart = (1+floor((1/2)*std_x)).*npart;
end

