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