GNU Octave  6.2.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
convhulln.cc
Go to the documentation of this file.
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 /*
27 29. July 2000 - Kai Habel: first release
28 2002-04-22 Paul Kienzle
29 * Use warning(...) function rather than writing to cerr
30 2006-05-01 Tom Holroyd
31 * add support for consistent winding in all dimensions; output is
32 * guaranteed to be simplicial.
33 */
34 
35 #if defined (HAVE_CONFIG_H)
36 # include "config.h"
37 #endif
38 
39 #include <limits>
40 #include <string>
41 
42 #include "Array.h"
43 #include "dMatrix.h"
44 #include "oct-locbuf.h"
45 #include "unwind-prot.h"
46 
47 #include "defun-dld.h"
48 #include "error.h"
49 #include "errwarn.h"
50 #include "ov.h"
51 
52 #if defined (HAVE_QHULL)
53 
54 # include "oct-qhull.h"
55 
56 # if defined (NEED_QHULL_VERSION)
57 char qh_version[] = "convhulln.oct 2007-07-24";
58 # endif
59 
60 static void
61 close_fcn (FILE *f)
62 {
63  std::fclose (f);
64 }
65 
66 static void
68 {
69  qh_freeqhull (! qh_ALL);
70 
71  int curlong, totlong;
72  qh_memfreeshort (&curlong, &totlong);
73 
74  if (curlong || totlong)
75  warning ("convhulln: did not free %d bytes of long memory (%d pieces)",
76  totlong, curlong);
77 }
78 
79 static bool
81 {
82  if (sizeof (octave_idx_type) > sizeof (int))
83  {
84  int maxval = std::numeric_limits<int>::max ();
85 
86  if (dim > maxval || n > maxval)
87  error ("%s: dimension too large for Qhull", who);
88  }
89 
90  return true;
91 }
92 
93 #endif
94 
95 DEFUN_DLD (convhulln, args, nargout,
96  doc: /* -*- texinfo -*-
97 @deftypefn {} {@var{h} =} convhulln (@var{pts})
98 @deftypefnx {} {@var{h} =} convhulln (@var{pts}, @var{options})
99 @deftypefnx {} {[@var{h}, @var{v}] =} convhulln (@dots{})
100 Compute the convex hull of the set of points @var{pts}.
101 
102 @var{pts} is a matrix of size [n, dim] containing n points in a space of
103 dimension dim.
104 
105 The hull @var{h} is an index vector into the set of points and specifies
106 which points form the enclosing hull.
107 
108 An optional second argument, which must be a string or cell array of
109 strings, contains options passed to the underlying qhull command. See the
110 documentation for the Qhull library for details
111 @url{http://www.qhull.org/html/qh-quick.htm#options}.
112 The default options depend on the dimension of the input:
113 
114 @itemize
115 @item 2D, 3D, 4D: @var{options} = @code{@{"Qt"@}}
116 
117 @item 5D and higher: @var{options} = @code{@{"Qt", "Qx"@}}
118 @end itemize
119 
120 If @var{options} is not present or @code{[]} then the default arguments are
121 used. Otherwise, @var{options} replaces the default argument list.
122 To append user options to the defaults it is necessary to repeat the
123 default arguments in @var{options}. Use a null string to pass no arguments.
124 
125 If the second output @var{v} is requested the volume of the enclosing
126 convex hull is calculated.
127 @seealso{convhull, delaunayn, voronoin}
128 @end deftypefn */)
129 {
130 #if defined (HAVE_QHULL)
131 
132  int nargin = args.length ();
133 
134  if (nargin < 1 || nargin > 2)
135  print_usage ();
136 
138 
139  Matrix points (args(0).matrix_value ());
140  const octave_idx_type dim = points.columns ();
141  const octave_idx_type num_points = points.rows ();
142 
143  if (! octave_qhull_dims_ok (dim, num_points, "convhulln"))
144  return retval;
145 
146  points = points.transpose ();
147 
148  std::string options;
149 
150  if (dim <= 4)
151  options = " Qt";
152  else
153  options = " Qt Qx";
154 
155  if (nargin == 2)
156  {
157  if (args(1).is_string ())
158  options = ' ' + args(1).string_value ();
159  else if (args(1).isempty ())
160  ; // Use default options.
161  else if (args(1).iscellstr ())
162  {
163  options = "";
164 
165  Array<std::string> tmp = args(1).cellstr_value ();
166 
167  for (octave_idx_type i = 0; i < tmp.numel (); i++)
168  options += ' ' + tmp(i);
169  }
170  else
171  error ("convhulln: OPTIONS must be a string, cell array of strings, or empty");
172  }
173 
174  boolT ismalloc = false;
175 
177 
178  // Replace the outfile pointer with stdout for debugging information.
179 #if defined (OCTAVE_HAVE_WINDOWS_FILESYSTEM) && ! defined (OCTAVE_HAVE_POSIX_FILESYSTEM)
180  FILE *outfile = std::fopen ("NUL", "w");
181 #else
182  FILE *outfile = std::fopen ("/dev/null", "w");
183 #endif
184  FILE *errfile = stderr;
185 
186  if (! outfile)
187  error ("convhulln: unable to create temporary file for output");
188 
189  frame.add_fcn (close_fcn, outfile);
190 
191  // qh_new_qhull command and points arguments are not const...
192 
193  std::string cmd = "qhull" + options;
194 
195  OCTAVE_LOCAL_BUFFER (char, cmd_str, cmd.length () + 1);
196 
197  strcpy (cmd_str, cmd.c_str ());
198 
199  int exitcode = qh_new_qhull (dim, num_points, points.fortran_vec (),
200  ismalloc, cmd_str, outfile, errfile);
201 
202  frame.add_fcn (free_qhull_memory);
203 
204  if (exitcode)
205  error ("convhulln: qhull failed");
206 
207  bool nonsimp_seen = false;
208 
209  octave_idx_type nf = qh num_facets;
210 
211  Matrix idx (nf, dim + 1);
212 
213  facetT *facet;
214 
215  octave_idx_type i = 0;
216 
217  FORALLfacets
218  {
219  octave_idx_type j = 0;
220 
221  if (! (nonsimp_seen || facet->simplicial || qh hull_dim == 2))
222  {
223  nonsimp_seen = true;
224 
225  if (cmd.find ("QJ") != std::string::npos)
226  // Should never happen with QJ.
227  error ("convhulln: qhull failed: option 'QJ' returned non-simplicial facet");
228  }
229 
230  if (dim == 3)
231  {
232  setT *vertices = qh_facet3vertex (facet);
233 
234  vertexT *vertex, **vertexp;
235 
236  FOREACHvertex_ (vertices)
237  idx(i, j++) = 1 + qh_pointid(vertex->point);
238 
239  qh_settempfree (&vertices);
240  }
241  else
242  {
243  if (facet->toporient ^ qh_ORIENTclock)
244  {
245  vertexT *vertex, **vertexp;
246 
247  FOREACHvertex_ (facet->vertices)
248  idx(i, j++) = 1 + qh_pointid(vertex->point);
249  }
250  else
251  {
252  vertexT *vertex, **vertexp;
253 
254  FOREACHvertexreverse12_ (facet->vertices)
255  idx(i, j++) = 1 + qh_pointid(vertex->point);
256  }
257  }
258  if (j < dim)
259  warning ("convhulln: facet %" OCTAVE_IDX_TYPE_FORMAT
260  " only has %" OCTAVE_IDX_TYPE_FORMAT
261  " vertices", i, j);
262 
263  i++;
264  }
265 
266  // Remove extra dimension if all facets were simplicial.
267 
268  if (! nonsimp_seen)
269  idx.resize (nf, dim, 0.0);
270 
271  if (nargout == 2)
272  {
273  // Calculate volume of convex hull, taken from qhull src/geom2.c.
274 
275  realT area;
276  realT dist;
277 
278  FORALLfacets
279  {
280  if (! facet->normal)
281  continue;
282 
283  if (facet->upperdelaunay && qh ATinfinity)
284  continue;
285 
286  facet->f.area = area = qh_facetarea (facet);
287  facet->isarea = True;
288 
289  if (qh DELAUNAY)
290  {
291  if (facet->upperdelaunay == qh UPPERdelaunay)
292  qh totarea += area;
293  }
294  else
295  {
296  qh totarea += area;
297  qh_distplane (qh interior_point, facet, &dist);
298  qh totvol += -dist * area/ qh hull_dim;
299  }
300  }
301 
302  retval(1) = octave_value (qh totvol);
303  }
304 
305  retval(0) = idx;
306 
307  return retval;
308 
309 #else
310 
311  octave_unused_parameter (args);
312  octave_unused_parameter (nargout);
313 
314  err_disabled_feature ("convhulln", "Qhull");
315 
316 #endif
317 }
318 
319 /*
320 %!testif HAVE_QHULL
321 %! cube = [0 0 0;1 0 0;1 1 0;0 1 0;0 0 1;1 0 1;1 1 1;0 1 1];
322 %! [h, v] = convhulln (cube, "Qt");
323 %! assert (size (h), [12 3]);
324 %! h = sortrows (sort (h, 2), [1:3]);
325 %! assert (h, [1 2 4; 1 2 6; 1 4 8; 1 5 6; 1 5 8; 2 3 4; 2 3 7; 2 6 7; 3 4 7; 4 7 8; 5 6 7; 5 7 8]);
326 %! assert (v, 1, 10*eps);
327 %! [h2, v2] = convhulln (cube); # Test default option = "Qt"
328 %! assert (size (h2), size (h));
329 %! h2 = sortrows (sort (h2, 2), [1:3]);
330 %! assert (h2, h);
331 %! assert (v2, v, 10*eps);
332 
333 %!testif HAVE_QHULL
334 %! cube = [0 0 0;1 0 0;1 1 0;0 1 0;0 0 1;1 0 1;1 1 1;0 1 1];
335 %! [h, v] = convhulln (cube, "QJ");
336 %! assert (size (h), [12 3]);
337 %! assert (sortrows (sort (h, 2), [1:3]), [1 2 4; 1 2 5; 1 4 5; 2 3 4; 2 3 6; 2 5 6; 3 4 8; 3 6 7; 3 7 8; 4 5 8; 5 6 8; 6 7 8]);
338 %! assert (v, 1.0, 1e6*eps);
339 
340 %!testif HAVE_QHULL
341 %! tetrahedron = [1 1 1;-1 -1 1;-1 1 -1;1 -1 -1];
342 %! [h, v] = convhulln (tetrahedron);
343 %! h = sortrows (sort (h, 2), [1 2 3]);
344 %! assert (h, [1 2 3;1 2 4; 1 3 4; 2 3 4]);
345 %! assert (v, 8/3, 10*eps);
346 
347 %!testif HAVE_QHULL
348 %! triangle = [0 0; 1 1; 1 0; 1 2];
349 %! h = convhulln (triangle);
350 %! assert (size (h), [3 2]);
351 */
charNDArray max(char d, const charNDArray &m)
Definition: chNDArray.cc:230
octave_idx_type columns(void) const
Definition: Array.h:424
octave_idx_type numel(void) const
Number of elements in the array.
Definition: Array.h:377
octave_idx_type rows(void) const
Definition: Array.h:415
const T * fortran_vec(void) const
Size of the specified dimension.
Definition: Array.h:583
Definition: dMatrix.h:42
Matrix transpose(void) const
Definition: dMatrix.h:135
void resize(octave_idx_type nr, octave_idx_type nc, double rfv=0)
Definition: dMatrix.h:151
void add_fcn(void(*fcn)(Params...), Args &&... args)
static void close_fcn(FILE *f)
Definition: convhulln.cc:61
static bool octave_qhull_dims_ok(octave_idx_type dim, octave_idx_type n, const char *who)
Definition: convhulln.cc:80
static void free_qhull_memory()
Definition: convhulln.cc:67
#define DEFUN_DLD(name, args_name, nargout_name, doc)
Macro to define an at run time dynamically loadable builtin function.
Definition: defun-dld.h:61
OCTINTERP_API void print_usage(void)
Definition: defun.cc:53
void warning(const char *fmt,...)
Definition: error.cc:1050
void error(const char *fmt,...)
Definition: error.cc:968
void err_disabled_feature(const std::string &fcn, const std::string &feature, const std::string &pkg)
Definition: errwarn.cc:53
F77_RET_T const F77_DBLE const F77_DBLE * f
octave_idx_type n
Definition: mx-inlines.cc:753
std::FILE * fopen(const std::string &filename, const std::string &mode)
Definition: lo-sysdep.cc:295
#define OCTAVE_LOCAL_BUFFER(T, buf, size)
Definition: oct-locbuf.h:44
return octave_value(v1.char_array_value() . concat(v2.char_array_value(), ra_idx),((a1.is_sq_string()||a2.is_sq_string()) ? '\'' :'"'))
octave_value::octave_value(const Array< char > &chm, char type) return retval
Definition: ov.cc:811