source: branches/numpy/anuga/utilities/polygon_ext.c @ 6415

Last change on this file since 6415 was 6410, checked in by rwilson, 15 years ago

numpy changes.

File size: 15.3 KB
Line 
1// Python - C extension for polygon module.
2//
3// To compile (Python2.3):
4//  gcc -c polygon_ext.c -I/usr/include/python2.3 -o polygon_ext.o -Wall -O
5//  gcc -shared polygon_ext.o  -o polygon_ext.so
6//
7// See the module polygon.py
8//
9//
10// Ole Nielsen, GA 2004
11//
12// NOTE: We use long* instead of int* for numeric arrays as this will work both
13//       for 64 as well as 32 bit systems
14
15
16#include "Python.h"
17#include "numpy/arrayobject.h"
18#include "math.h"
19
20#include "util_ext.h"
21
22
23double dist(double x,
24            double y) {
25 
26  return sqrt(x*x + y*y);
27}
28
29
30int __point_on_line(double x, double y,
31                    double x0, double y0,
32                    double x1, double y1,
33                    double rtol,
34                    double atol) {
35  /*Determine whether a point is on a line segment
36
37    Input: x, y, x0, x0, x1, y1: where
38        point is given by x, y
39        line is given by (x0, y0) and (x1, y1)
40
41  */
42
43  double a0, a1, a_normal0, a_normal1, b0, b1, len_a, len_b;
44  double nominator, denominator;
45  int is_parallel;
46
47  a0 = x - x0;
48  a1 = y - y0;
49
50  a_normal0 = a1;
51  a_normal1 = -a0;
52
53  b0 = x1 - x0;
54  b1 = y1 - y0;
55
56  nominator = fabs(a_normal0*b0 + a_normal1*b1);
57  denominator = b0*b0 + b1*b1;
58 
59  // Determine if line is parallel to point vector up to a tolerance
60  is_parallel = 0;
61  if (denominator == 0.0) {
62    // Use absolute tolerance
63    if (nominator <= atol) {
64      is_parallel = 1;
65    }
66  } else {
67    // Denominator is positive - use relative tolerance
68    if (nominator/denominator <= rtol) {
69      is_parallel = 1;
70    }   
71  }
72   
73  if (is_parallel) {
74    // Point is somewhere on the infinite extension of the line
75    // subject to specified absolute tolerance
76
77    len_a = dist(a0, a1); //sqrt(a0*a0 + a1*a1);
78    len_b = dist(b0, b1); //sqrt(b0*b0 + b1*b1);
79
80    if (a0*b0 + a1*b1 >= 0 && len_a <= len_b) {
81      return 1;
82    } else {
83      return 0;
84    }
85  } else {
86    return 0;
87  }
88}
89
90
91
92/*
93WORK IN PROGRESS TO OPTIMISE INTERSECTION
94int __intersection(double x0, double y0,
95                   double x1, double y1) {
96
97
98    x0 = line0[0,0]; y0 = line0[0,1]
99    x1 = line0[1,0]; y1 = line0[1,1]
100
101    x2 = line1[0,0]; y2 = line1[0,1]
102    x3 = line1[1,0]; y3 = line1[1,1]
103
104    denom = (y3-y2)*(x1-x0) - (x3-x2)*(y1-y0)
105    u0 = (x3-x2)*(y0-y2) - (y3-y2)*(x0-x2)
106    u1 = (x2-x0)*(y1-y0) - (y2-y0)*(x1-x0)
107       
108    if allclose(denom, 0.0):
109        # Lines are parallel - check if they coincide on a shared a segment
110
111        if allclose( [u0, u1], 0.0 ):
112            # We now know that the lines if continued coincide
113            # The remaining check will establish if the finite lines share a segment
114
115            line0_starts_on_line1 = line0_ends_on_line1 =\
116            line1_starts_on_line0 = line1_ends_on_line0 = False
117               
118            if point_on_line([x0, y0], line1):
119                line0_starts_on_line1 = True
120
121            if point_on_line([x1, y1], line1):
122                line0_ends_on_line1 = True
123 
124            if point_on_line([x2, y2], line0):
125                line1_starts_on_line0 = True
126
127            if point_on_line([x3, y3], line0):
128                line1_ends_on_line0 = True                               
129
130            if not(line0_starts_on_line1 or line0_ends_on_line1\
131               or line1_starts_on_line0 or line1_ends_on_line0):
132                # Lines are parallel and would coincide if extended, but not as they are.
133                return 3, None
134
135
136            # One line fully included in the other. Use direction of included line
137            if line0_starts_on_line1 and line0_ends_on_line1:
138                # Shared segment is line0 fully included in line1
139                segment = array([[x0, y0], [x1, y1]])               
140
141            if line1_starts_on_line0 and line1_ends_on_line0:
142                # Shared segment is line1 fully included in line0
143                segment = array([[x2, y2], [x3, y3]])
144           
145
146            # Overlap with lines are oriented the same way
147            if line0_starts_on_line1 and line1_ends_on_line0:
148                # Shared segment from line0 start to line 1 end
149                segment = array([[x0, y0], [x3, y3]])
150
151            if line1_starts_on_line0 and line0_ends_on_line1:
152                # Shared segment from line1 start to line 0 end
153                segment = array([[x2, y2], [x1, y1]])                               
154
155
156            # Overlap in opposite directions - use direction of line0
157            if line0_starts_on_line1 and line1_starts_on_line0:
158                # Shared segment from line0 start to line 1 end
159                segment = array([[x0, y0], [x2, y2]])
160
161            if line0_ends_on_line1 and line1_ends_on_line0:
162                # Shared segment from line0 start to line 1 end
163                segment = array([[x3, y3], [x1, y1]])               
164
165               
166            return 2, segment
167        else:
168            # Lines are parallel but they do not coincide
169            return 4, None #FIXME (Ole): Add distance here instead of None
170           
171    else:
172        # Lines are not parallel or coinciding
173        u0 = u0/denom
174        u1 = u1/denom       
175
176        x = x0 + u0*(x1-x0)
177        y = y0 + u0*(y1-y0)
178
179        # Sanity check - can be removed to speed up if needed
180        assert allclose(x, x2 + u1*(x3-x2))
181        assert allclose(y, y2 + u1*(y3-y2))       
182
183        # Check if point found lies within given line segments
184        if 0.0 <= u0 <= 1.0 and 0.0 <= u1 <= 1.0:
185            # We have intersection
186
187            return 1, array([x, y])
188        else:
189            # No intersection
190            return 0, None
191
192
193}
194*/
195
196
197
198int __interpolate_polyline(int number_of_nodes,
199                           int number_of_points,
200                           double* data,
201                           double* polyline_nodes,
202                           long* gauge_neighbour_id,
203                           double* interpolation_points,                               
204                           double* interpolated_values,
205                           double rtol,
206                           double atol) {
207                           
208  int j, i, neighbour_id;
209  double x0, y0, x1, y1, x, y;
210  double segment_len, segment_delta, slope, alpha;
211
212  for (j=0; j<number_of_nodes; j++) { 
213
214    neighbour_id = gauge_neighbour_id[j];
215       
216    // FIXME(Ole): I am convinced that gauge_neighbour_id can be discarded, but need to check with John J.
217    // Keep it for now (17 Jan 2009)
218    // When gone, we can simply interpolate between neighbouring nodes, i.e. neighbour_id = j+1.
219    // and the test below becomes something like: if j < number_of_nodes... 
220       
221    if (neighbour_id >= 0) {
222      x0 = polyline_nodes[2*j];
223      y0 = polyline_nodes[2*j+1];
224     
225      x1 = polyline_nodes[2*neighbour_id];
226      y1 = polyline_nodes[2*neighbour_id+1];     
227     
228           
229      segment_len = dist(x1-x0, y1-y0);
230      segment_delta = data[neighbour_id] - data[j];           
231      slope = segment_delta/segment_len;
232           
233      for (i=0; i<number_of_points; i++) {               
234        x = interpolation_points[2*i];
235        y = interpolation_points[2*i+1];       
236       
237        if (__point_on_line(x, y, x0, y0, x1, y1, rtol, atol)) {
238          alpha = dist(x-x0, y-y0);
239          interpolated_values[i] = slope*alpha + data[j];
240        }
241      }
242    }
243  }
244                           
245  return 0;                         
246}                                                     
247
248
249int __separate_points_by_polygon(int M,     // Number of points
250                                int N,     // Number of polygon vertices
251                                double* points,
252                                double* polygon,
253                                long* indices,  // M-Array for storage indices
254                                int closed,
255                                int verbose) {
256
257  double minpx, maxpx, minpy, maxpy, x, y, px_i, py_i, px_j, py_j, rtol=0.0, atol=0.0;
258  int i, j, k, outside_index, inside_index, inside;
259
260  //Find min and max of poly used for optimisation when points
261  //are far away from polygon
262 
263  //FIXME(Ole): Pass in rtol and atol from Python
264
265  minpx = polygon[0]; maxpx = minpx;
266  minpy = polygon[1]; maxpy = minpy;
267
268  for (i=0; i<N; i++) {
269    px_i = polygon[2*i];
270    py_i = polygon[2*i + 1];
271
272    if (px_i < minpx) minpx = px_i;
273    if (px_i > maxpx) maxpx = px_i;
274    if (py_i < minpy) minpy = py_i;
275    if (py_i > maxpy) maxpy = py_i;
276  }
277
278  //Begin main loop (for each point)
279  inside_index = 0;    //Keep track of points inside
280  outside_index = M-1; //Keep track of points outside (starting from end)   
281  if (verbose){
282     printf("Separating %d points\n", M);
283  } 
284  for (k=0; k<M; k++) {
285    if (verbose){
286      if (k %((M+10)/10)==0) printf("Doing %d of %d\n", k, M);
287    }
288   
289    x = points[2*k];
290    y = points[2*k + 1];
291
292    inside = 0;
293
294    //Optimisation
295    if ((x > maxpx) || (x < minpx) || (y > maxpy) || (y < minpy)) {
296      //Nothing
297    } else {   
298      //Check polygon
299      for (i=0; i<N; i++) {
300        //printf("k,i=%d,%d\n", k, i);
301        j = (i+1)%N;
302
303        px_i = polygon[2*i];
304        py_i = polygon[2*i+1];
305        px_j = polygon[2*j];
306        py_j = polygon[2*j+1];
307
308        //Check for case where point is contained in line segment
309        if (__point_on_line(x, y, px_i, py_i, px_j, py_j, rtol, atol)) {
310          if (closed == 1) {
311            inside = 1;
312          } else {
313            inside = 0;
314          }
315          break;
316        } else {
317          //Check if truly inside polygon
318          if ( ((py_i < y) && (py_j >= y)) ||
319               ((py_j < y) && (py_i >= y)) ) {
320            if (px_i + (y-py_i)/(py_j-py_i)*(px_j-px_i) < x)
321              inside = 1-inside;
322          }
323        }
324      }
325    } 
326    if (inside == 1) {
327      indices[inside_index] = k;
328      inside_index += 1;
329    } else {
330      indices[outside_index] = k;
331      outside_index -= 1;   
332    }
333  } // End k
334
335  return inside_index;
336}
337
338
339
340// Gateways to Python
341PyObject *_point_on_line(PyObject *self, PyObject *args) {
342  //
343  // point_on_line(x, y, x0, y0, x1, y1)
344  //
345
346  double x, y, x0, y0, x1, y1, rtol, atol;
347  int res;
348  PyObject *result;
349
350  // Convert Python arguments to C
351  if (!PyArg_ParseTuple(args, "dddddddd", &x, &y, &x0, &y0, &x1, &y1, &rtol, &atol)) {
352    PyErr_SetString(PyExc_RuntimeError, 
353                    "point_on_line could not parse input");   
354    return NULL;
355  }
356
357
358  // Call underlying routine
359  res = __point_on_line(x, y, x0, y0, x1, y1, rtol, atol);
360
361  // Return values a and b
362  result = Py_BuildValue("i", res);
363  return result;
364}
365
366
367
368// Gateways to Python
369PyObject *_interpolate_polyline(PyObject *self, PyObject *args) {
370  //
371  // _interpolate_polyline(data, polyline_nodes, gauge_neighbour_id, interpolation_points
372  //                       interpolated_values):
373  //
374
375 
376  PyArrayObject
377    *data,
378    *polyline_nodes,
379    *gauge_neighbour_id,
380    *interpolation_points,
381    *interpolated_values;
382
383  double rtol, atol; 
384  int number_of_nodes, number_of_points, res;
385 
386  // Convert Python arguments to C
387  if (!PyArg_ParseTuple(args, "OOOOOdd",
388                        &data,
389                        &polyline_nodes,
390                        &gauge_neighbour_id,
391                        &interpolation_points,
392                        &interpolated_values,
393                        &rtol,
394                        &atol)) {
395   
396    PyErr_SetString(PyExc_RuntimeError, 
397                    "_interpolate_polyline could not parse input");
398    return NULL;
399  }
400
401  // check that numpy array objects arrays are C contiguous memory
402  CHECK_C_CONTIG(data);
403  CHECK_C_CONTIG(polyline_nodes);
404  CHECK_C_CONTIG(gauge_neighbour_id);
405  CHECK_C_CONTIG(interpolation_points);
406  CHECK_C_CONTIG(interpolated_values);
407
408  number_of_nodes = polyline_nodes -> dimensions[0];  // Number of nodes in polyline
409  number_of_points = interpolation_points -> dimensions[0];   //Number of points
410 
411
412  // Call underlying routine
413  res = __interpolate_polyline(number_of_nodes,
414                               number_of_points,
415                               (double*) data -> data,
416                               (double*) polyline_nodes -> data,
417                               (long*) gauge_neighbour_id -> data,
418                               (double*) interpolation_points -> data,                         
419                               (double*) interpolated_values -> data,
420                               rtol,
421                               atol);                                                 
422
423  // Return
424  return Py_BuildValue(""); 
425}
426
427
428
429/*
430PyObject *_intersection(PyObject *self, PyObject *args) {
431  //
432  // intersection(x0, y0, x1, y1)
433  //
434
435  double x, y, x0, y0, x1, y1;
436  int res;
437  PyObject *result;
438
439  // Convert Python arguments to C
440  if (!PyArg_ParseTuple(args, "dddddd", &x, &y, &x0, &y0, &x1, &y1)) {
441    PyErr_SetString(PyExc_RuntimeError,
442                    "point_on_line could not parse input");   
443    return NULL;
444  }
445
446
447  // Call underlying routine
448  res = __intersection(x, y, x0, y0, x1, y1);
449
450  // Return values a and b
451  result = Py_BuildValue("i", res);
452  return result;
453}
454*/
455
456
457PyObject *_separate_points_by_polygon(PyObject *self, PyObject *args) {
458  //def separate_points_by_polygon(points, polygon, closed, verbose, one_point):
459  //  """Determine whether points are inside or outside a polygon
460  //
461  //  Input:
462  //     point - Tuple of (x, y) coordinates, or list of tuples
463  //     polygon - list of vertices of polygon
464  //     closed - (optional) determine whether points on boundary should be
465  //     regarded as belonging to the polygon (closed = True)
466  //     or not (closed = False)
467
468  //
469  //  Output:
470  //     indices: array of same length as points with indices of points falling
471  //     inside the polygon listed from the beginning and indices of points
472  //     falling outside listed from the end.
473  //     
474  //     count: count of points falling inside the polygon
475  //     
476  //     The indices of points inside are obtained as indices[:count]
477  //     The indices of points outside are obtained as indices[count:]       
478  //
479  //  Examples:
480  //     separate_polygon( [[0.5, 0.5], [1, -0.5], [0.3, 0.2]] )
481  //     will return the indices [0, 2, 1] as only the first and the last point
482  //     is inside the unit square
483  //
484  //  Remarks:
485  //     The vertices may be listed clockwise or counterclockwise and
486  //     the first point may optionally be repeated.
487  //     Polygons do not need to be convex.
488  //     Polygons can have holes in them and points inside a hole is
489  //     regarded as being outside the polygon.
490  //
491  //
492  //  Algorithm is based on work by Darel Finley,
493  //  http://www.alienryderflex.com/polygon/
494  //
495  //
496
497  PyArrayObject
498    *points,
499    *polygon,
500    *indices;
501
502  int closed, verbose; //Flags
503  int count, M, N;
504
505  // Convert Python arguments to C
506  if (!PyArg_ParseTuple(args, "OOOii",
507                        &points,
508                        &polygon,
509                        &indices,
510                        &closed,
511                        &verbose)) {
512   
513
514    PyErr_SetString(PyExc_RuntimeError, 
515                    "separate_points_by_polygon could not parse input");
516    return NULL;
517  }
518
519  // check that points, polygon and indices arrays are C contiguous
520  CHECK_C_CONTIG(points);
521  CHECK_C_CONTIG(polygon);
522  CHECK_C_CONTIG(indices);
523
524  M = points -> dimensions[0];   //Number of points
525  N = polygon -> dimensions[0];  //Number of vertices in polygon
526
527  //FIXME (Ole): This isn't send to Python's sys.stdout
528  if (verbose) printf("Got %d points and %d polygon vertices\n", M, N);
529 
530  //Call underlying routine
531  count = __separate_points_by_polygon(M, N,
532                                       (double*) points -> data,
533                                       (double*) polygon -> data,
534                                       (long*) indices -> data,
535                                       closed, verbose);
536 
537  //NOTE: return number of points inside..
538  return Py_BuildValue("i", count);
539}
540
541
542
543// Method table for python module
544static struct PyMethodDef MethodTable[] = {
545  /* The cast of the function is necessary since PyCFunction values
546   * only take two PyObject* parameters, and rotate() takes
547   * three.
548   */
549
550  {"_point_on_line", _point_on_line, METH_VARARGS, "Print out"},
551  //{"_intersection", _intersection, METH_VARARGS, "Print out"}, 
552  {"_separate_points_by_polygon", _separate_points_by_polygon, 
553                                 METH_VARARGS, "Print out"},
554  {"_interpolate_polyline", _interpolate_polyline, 
555                                 METH_VARARGS, "Print out"},                             
556  {NULL, NULL, 0, NULL}   /* sentinel */
557};
558
559
560
561// Module initialisation
562void initpolygon_ext(void){
563  Py_InitModule("polygon_ext", MethodTable);
564
565  import_array();     //Necessary for handling of NumPY structures
566}
567
568
569
Note: See TracBrowser for help on using the repository browser.