##  Copyright (C) 2014  Daniel Kraft <d@domob.eu>
##  GNU Octave level-set package.
##
##  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  {Function File} {@var{res} =} ls_disjoint (@var{phi1}, @var{phi2})
## @deftypefnx  {Function File} {@var{res} =} ls_disjoint (@var{phi}, ...)
## 
## Check if all the sets described by the given level-set functions
## are disjoint.
##
## @seealso{ls_inside, ls_equal, is_issubset, ls_check}
## @end deftypefn

function res = ls_disjoint (varargin)
  if (length (varargin) < 1)
    print_usage ();
  endif

  % The algorithm is like this:  Go over the list of sets once
  % and keep a "running union" of the sets already processed.  Check
  % that each new set is disjoint to this union.
  total = varargin{1};
  for i = 2 : length (varargin)
    phi = varargin{i};
    if (~all (size (total) == size (phi)))
      error ("size mismatch in the arguments");
    endif

    common = (ls_inside (phi) & ls_inside (total));
    if (any (common(:)))
      res = false;
      return;
    endif

    total = ls_union (total, phi);
  endfor

  % No intersection found.
  res = true;
endfunction

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tests.

% Test for error conditions.
%!error <Invalid call to>
%!  ls_disjoint ()
%!error <size mismatch in the arguments>
%!  ls_disjoint (1, -2, [1, 2])

% Basic test with some constructed examples.
%!test
%!  assert (ls_disjoint ([-1, 0, 1], [0, 0, 0], [1, 0, -1]));
%!  assert (~ls_disjoint ([Inf, -Inf, 1], [-1, -1, 1]));
%!  assert (~ls_disjoint ([-1, -1, 1], [0, 0, 0], [1, -1, -1]));

% Test in 2D with some circles.
%!test
%!  n = 50;
%!  x = linspace (-10, 10, n);
%!  [XX, YY] = meshgrid (x, x);
%!
%!  phi1 = (XX - 2).^2 + (YY - 2).^2 - 2^2;
%!  phi2 = (XX + 2).^2 + (YY + 2).^2 - 2^2;
%!  phi3 = XX.^2 + YY.^2 - 2^2;
%!
%!  assert (ls_disjoint (phi1, phi2));
%!  assert (~ls_disjoint (phi1, phi3));
%!  assert (~ls_disjoint (phi2, phi3));
%!  assert (~ls_disjoint (phi1, phi2, phi3));
