function chi = chi_measure ( dim_num, n, z, ns, sample_routine )

%*****************************************************************************80
%
%% chi_measure() determines the pointset quality measure CHI.
%
%  Discussion:
%
%    The CHI measure of point distribution quality for a set Z of
%    N points in an DIM_NUM-dimensional region is defined as follows:
%
%    Assign every point X in the region to the nearest element
%    Z(I) of the point set.  For each Z(I), let H(I) be the maximum
%    distance between Z(I) and any point assigned to it by this process.
%
%    For each point Z(I), we determine the nearest distinct element of
%    the pointset by
%
%      GAMMA(I) = minimum ( 1 <= J <= N, I /= J ) distance ( Z(I), Z(J) )
%
%    Then
%
%      CHI(I) = 2 * H(I) / GAMMA(I)
%
%    and
%
%      CHI = maximum ( 1 <= I <= N ) CHI(I)
%
%    This quantity can be estimated by using sampling to pick a large
%    number of points in the region, rather than all of them.
%
%    For an ideally regular mesh, all the CHI(I)'s will be equal.
%    Any deviation from regularity increases the value of some entries
%    of CHI; thus, given two meshes, the one with a lower value of
%    CHI is to be recommended.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    01 November 2004
%
%  Author:
%
%    Max Gunzburger
%    John Burkardt
%
%  Reference:
%
%    Max Gunzburger, John Burkardt,
%    Uniformity Measures for Point Samples in Hypercubes.
%
%  Input:
%
%    integer DIM_NUM, the spatial dimension.
%
%    integer N, the number of points.
%
%    real Z(N,DIM_NUM), the points.
%
%    integer NS, the number of sample points.
%
%    character SAMPLE_ROUTINE, the name of the function to be used to
%    return sample points in the region.  The function must have the form
%      x = sample_routine ( dim_num, n )
%
%  Output:
%
%    real CHI, the CHI quality measure.
%
  h(1:n) = 0.0;

  for k = 1 : ns

    x = feval ( sample_routine, 1, dim_num );

    closest = find_closest ( dim_num, n, 1, x, z );

    dist = sum ( ( x(1,1:dim_num) - z(closest(1),1:dim_num) ).^2 );

    h(closest(1)) = max ( h(closest(1)), dist );

  end

  gamma = pointset_spacing ( dim_num, n, z );

  chi_vec(1:n) = 2.0 * sqrt ( h(1:n) ) ./ gamma(1:n);

  chi = max ( chi_vec(1:n) );

  return
end
