##  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{phi} =} ls_union (@var{phi1}, @var{phi2})
## @deftypefnx  {Function File} {@var{phi} =} ls_union (@var{phi}, ...)
## 
## Calculate a level-set function for the union of the sets described
## by the argument level-set functions.
##
## @seealso{ls_complement, ls_intersect, ls_setdiff, ls_setxor, union}
## @end deftypefn

function res = ls_union (varargin)
  res = ls_union_intersect (@min, varargin, "ls_union");
endfunction

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

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

% Test that the union creates something which contains all pieces.
%!test
%!  n = 50;
%!  x = linspace (-10, 10, n);
%!  [XX, YY] = meshgrid (x, x);
%!
%!  phi1 = (XX - 3).^2 + (YY - 3).^2 - 2^2;
%!  phi2 = (XX + 3).^2 + (YY + 3).^2 - 2^2;
%!  phi3 = XX.^2 + YY.^2 - 2^2;
%!
%!  phi = ls_union (phi1, phi2, phi3);
%!  assert (ls_issubset (phi1, phi));
%!  assert (ls_issubset (phi2, phi));
%!  assert (ls_issubset (phi3, phi));
%!
%!  assert (ls_union (phi3), phi3);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Demo.

%!demo
%!  n = 100;
%!  x = linspace (-7, 7, n);
%!  [XX, YY] = meshgrid (x, x);
%!
%!  phi1 = (XX - 2 * cos (7/6 * pi)).^2 + (YY - 2 * sin (7/6 * pi)).^2 - 3^2;
%!  phi2 = (XX - 2 * cos (11/6 * pi)).^2 + (YY - 2 * sin (11/6 * pi)).^2 - 3^2;
%!  phi3 = XX.^2 + (YY - 2).^2 - 3^2;
%!  phi = ls_union (phi1, phi2, phi3);
%!
%!  figure ();
%!  subplot (1, 2, 1);
%!  hold ("on");
%!  contour (XX, YY, phi1, [0, 0], "k");
%!  contour (XX, YY, phi2, [0, 0], "k");
%!  contour (XX, YY, phi3, [0, 0], "k");
%!  hold ("off");
%!  axis ("equal");
%!
%!  subplot (1, 2, 2);
%!  hold ("on");
%!  imagesc (x, x, phi);
%!  set (gca (), "ydir", "normal");
%!  ls_sign_colourmap ();
%!  contour (XX, YY, phi, [0, 0], "k");
%!  hold ("off");
%!  axis ("equal");
