1########################################################################
2##
3## Copyright (C) 2000-2021 The Octave Project Developers
4##
5## See the file COPYRIGHT.md in the top-level directory of this
6## distribution or <https://octave.org/copyright/>.
7##
8## This file is part of Octave.
9##
10## Octave is free software: you can redistribute it and/or modify it
11## under the terms of the GNU General Public License as published by
12## the Free Software Foundation, either version 3 of the License, or
13## (at your option) any later version.
14##
15## Octave is distributed in the hope that it will be useful, but
16## WITHOUT ANY WARRANTY; without even the implied warranty of
17## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18## GNU General Public License for more details.
19##
20## You should have received a copy of the GNU General Public License
21## along with Octave; see the file COPYING.  If not, see
22## <https://www.gnu.org/licenses/>.
23##
24########################################################################
25
26## -*- texinfo -*-
27## @deftypefn  {} {} cplxpair (@var{z})
28## @deftypefnx {} {} cplxpair (@var{z}, @var{tol})
29## @deftypefnx {} {} cplxpair (@var{z}, @var{tol}, @var{dim})
30## Sort the numbers @var{z} into complex conjugate pairs ordered by increasing
31## real part.
32##
33## The negative imaginary complex numbers are placed first within each pair.
34## All real numbers (those with
35## @code{abs (imag (@var{z})) / abs (@var{z}) < @var{tol}}) are placed after
36## the complex pairs.
37##
38## @var{tol} is a weighting factor in the range [0, 1) which determines the
39## tolerance of the matching.  The default value is @code{100 * eps} and the
40## resulting tolerance for a given complex pair is
41## @code{@var{tol} * abs (@var{z}(i)))}.
42##
43## By default the complex pairs are sorted along the first non-singleton
44## dimension of @var{z}.  If @var{dim} is specified, then the complex pairs are
45## sorted along this dimension.
46##
47## Signal an error if some complex numbers could not be paired.  Signal an
48## error if all complex numbers are not exact conjugates (to within @var{tol}).
49## Note that there is no defined order for pairs with identical real parts but
50## differing imaginary parts.
51## @c Set example in small font to prevent overfull line
52##
53## @smallexample
54## cplxpair (exp (2i*pi*[0:4]'/5)) == exp (2i*pi*[3; 2; 4; 1; 0]/5)
55## @end smallexample
56## @end deftypefn
57
58## 2006-05-12 David Bateman - Modified for NDArrays
59
60function y = cplxpair (z, tol, dim)
61
62  if (nargin < 1 || nargin > 3)
63    print_usage ();
64  endif
65
66  if (isempty (z))
67    y = zeros (size (z));
68    return;
69  endif
70
71  cls = ifelse (isa (z, "single"), "single", "double");
72  if (nargin < 2 || isempty (tol))
73    tol = 100*eps (cls);
74  elseif (! isscalar (tol) || tol < 0 || tol >= 1)
75    error ("cplxpair: TOL must be a scalar number in the range 0 <= TOL < 1");
76  endif
77
78  nd = ndims (z);
79  if (nargin < 3)
80    ## Find the first singleton dimension.
81    sz = size (z);
82    (dim = find (sz > 1, 1)) || (dim = 1);
83  else
84    dim = floor (dim);
85    if (dim < 1 || dim > nd)
86      error ("cplxpair: invalid dimension DIM");
87    endif
88  endif
89
90  ## Move dimension to analyze to first position, and convert to a 2-D matrix.
91  perm = [dim:nd, 1:dim-1];
92  z = permute (z, perm);
93  sz = size (z);
94  n = sz(1);
95  m = prod (sz) / n;
96  z = reshape (z, n, m);
97
98  ## Sort the sequence in terms of increasing real values.
99  [~, idx] = sort (real (z), 1);
100  z = z(idx + n * ones (n, 1) * [0:m-1]);
101
102  ## Put the purely real values at the end of the returned list.
103  [idxi, idxj] = find (abs (imag (z)) ./ (abs (z) + realmin (cls)) <= tol);
104  ## Force values detected to be real within tolerance to actually be real.
105  z(idxi + n*(idxj-1)) = real (z(idxi + n*(idxj-1)));
106  q = sparse (idxi, idxj, 1, n, m);
107  nr = sum (q, 1);
108  [~, idx] = sort (q, 1);
109  midx = idx + rows (idx) * ones (rows (idx), 1) * [0:columns(idx)-1];
110  z = z(midx);
111  y = z;
112
113  ## For each remaining z, place the value and its conjugate at the start of
114  ## the returned list, and remove them from further consideration.
115  for j = 1:m
116    p = n - nr(j);
117    for i = 1:2:p
118      if (i+1 > p)
119        error ("cplxpair: could not pair all complex numbers");
120      endif
121      [v, idx] = min (abs (z(i+1:p,j) - conj (z(i,j))));
122      if (v >= tol * abs (z(i,j)))
123        error ("cplxpair: could not pair all complex numbers");
124      endif
125      ## For pairs, select the one with positive imaginary part and use it and
126      ## it's conjugate, but list the negative imaginary pair first.
127      if (imag (z(i,j)) > 0)
128        y([i, i+1],j) = [conj(z(i,j)), z(i,j)];
129      else
130        y([i, i+1],j) = [conj(z(idx+i,j)), z(idx+i,j)];
131      endif
132      z(idx+i,j) = z(i+1,j);
133    endfor
134  endfor
135
136  ## Reshape the output matrix.
137  y = ipermute (reshape (y, sz), perm);
138
139endfunction
140
141
142%!demo
143%! [ cplxpair(exp(2i*pi*[0:4]'/5)), exp(2i*pi*[3; 2; 4; 1; 0]/5) ]
144
145%!assert (isempty (cplxpair ([])))
146%!assert (cplxpair (1), 1)
147%!assert (cplxpair ([1+1i, 1-1i]), [1-1i, 1+1i])
148%!assert (cplxpair ([1+1i, 1+1i, 1, 1-1i, 1-1i, 2]), ...
149%!                  [1-1i, 1+1i, 1-1i, 1+1i, 1, 2])
150%!assert (cplxpair ([1+1i; 1+1i; 1; 1-1i; 1-1i; 2]), ...
151%!                  [1-1i; 1+1i; 1-1i; 1+1i; 1; 2])
152%!assert (cplxpair ([0, 1, 2]), [0, 1, 2])
153
154%!shared z,y
155%! z = exp (2i*pi*[4; 3; 5; 2; 6; 1; 0]/7);
156%! z(2) = conj(z(1));
157%! z(4) = conj(z(3));
158%! z(6) = conj(z(5));
159%!assert (cplxpair (z(randperm (7))), z)
160%!assert (cplxpair (z(randperm (7))), z)
161%!assert (cplxpair (z(randperm (7))), z)
162%!assert (cplxpair ([z(randperm (7)), z(randperm (7))]), [z,z])
163%!assert (cplxpair ([z(randperm (7)), z(randperm (7))],[],1), [z,z])
164%!assert (cplxpair ([z(randperm (7)).'; z(randperm (7)).'],[],2), [z.';z.'])
165%! y = [ -1-1i; -1+1i;-3; -2; 1; 2; 3];
166%!assert (cplxpair ([z(randperm (7)), y(randperm (7))]), [z,y])
167%!assert (cplxpair ([z(randperm (7)), y(randperm (7)),z(randperm (7))]), [z,y,z])
168
169## Test tolerance
170%!assert (cplxpair ([2000 * (1+eps) + 4j; 2000 * (1-eps) - 4j]), ...
171%!        [(2000 - 4j); (2000 + 4j)], 100*eps(200))
172%!error <could not pair>
173%! cplxpair ([2000 * (1+eps) + 4j; 2000 * (1-eps) - 4j], 0);
174%!error <could not pair>
175%! cplxpair ([2e6 + j; 2e6 - j; 1e-9 * (1 + j); 1e-9 * (1 - 2j)]);
176
177## Test input validation
178%!error cplxpair ()
179%!error cplxpair (1,2,3,4)
180%!error <cplxpair: TOL must be .* scalar number> cplxpair (1, ones (2,2))
181%!error <cplxpair: TOL must be .* in the range 0 <= TOL < 1> cplxpair (1, -1)
182%!error <cplxpair: TOL must be .* in the range 0 <= TOL < 1> cplxpair (1, -1)
183%!error <invalid dimension DIM> cplxpair (1, [], 3)
184