# source:trunk/anuga_core/source/anuga/utilities/polygon_ext.c@8017

Last change on this file since 8017 was 8017, checked in by steve, 13 years ago

Added code to pickup if elevation is discontinuous. compute_fluxes now produces an error in this case

File size: 20.2 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#define YES 1
23#define NO 0
24
25
26double dist(double x,
27            double y) {
28
29  return sqrt(x*x + y*y);
30}
31
32
33int __point_on_line(double x, double y,
34                    double x0, double y0,
35                    double x1, double y1,
36                    double rtol,
37                    double atol) {
38  /*Determine whether a point is on a line segment
39
40    Input: x, y, x0, x0, x1, y1: where
41        point is given by x, y
42        line is given by (x0, y0) and (x1, y1)
43
44  */
45
46  double a0, a1, a_normal0, a_normal1, b0, b1, len_a, len_b;
47  double nominator, denominator;
48  int is_parallel;
49
50  a0 = x - x0;
51  a1 = y - y0;
52
53  a_normal0 = a1;
54  a_normal1 = -a0;
55
56  b0 = x1 - x0;
57  b1 = y1 - y0;
58
59  nominator = fabs(a_normal0*b0 + a_normal1*b1);
60  denominator = b0*b0 + b1*b1;
61
62  // Determine if line is parallel to point vector up to a tolerance
63  is_parallel = 0;
64  if (denominator == 0.0) {
65    // Use absolute tolerance
66    if (nominator <= atol) {
67      is_parallel = 1;
68    }
69  } else {
70    // Denominator is positive - use relative tolerance
71    if (nominator/denominator <= rtol) {
72      is_parallel = 1;
73    }
74  }
75
76  if (is_parallel) {
77    // Point is somewhere on the infinite extension of the line
78    // subject to specified absolute tolerance
79
80    len_a = dist(a0, a1); //sqrt(a0*a0 + a1*a1);
81    len_b = dist(b0, b1); //sqrt(b0*b0 + b1*b1);
82
83    if (a0*b0 + a1*b1 >= 0 && len_a <= len_b) {
84      return 1;
85    } else {
86      return 0;
87    }
88  } else {
89    return 0;
90  }
91}
92
93
94//  public domain function by Darel Rex Finley, 2006
95//  http://www.alienryderflex.com/intersect/
96//
97//  Determines the intersection point of the line segment defined by points A and B
98//  with the line segment defined by points C and D.
99//
100//  Returns YES if the intersection point was found, and stores that point in X,Y.
101//  Returns NO if there is no determinable intersection point, in which case X,Y will
102//  be unmodified.
103
104int __lineSegmentIntersection(
105        double Ax, double Ay,
106        double Bx, double By,
107        double Cx, double Cy,
108        double Dx, double Dy,
109        double *X, double *Y) {
110
111    double distAB, theCos, theSin, newX, ABpos;
112
113    //  Fail if either line segment is zero-length.
114    if ( (Ax == Bx && Ay == By) || (Cx == Dx && Cy == Dy) ) return NO ;
115
116    //  Fail if the segments share an end-point.
117    if ( (Ax == Cx && Ay == Cy) || (Bx == Cx && By == Cy)
118            || (Ax == Dx && Ay == Dy) || (Bx == Dx && By == Dy) ) {
119        return NO;
120    }
121
122    //  (1) Translate the system so that point A is on the origin.
123    Bx -= Ax;
124    By -= Ay;
125    Cx -= Ax;
126    Cy -= Ay;
127    Dx -= Ax;
128    Dy -= Ay;
129
130    //  Discover the length of segment A-B.
131    distAB = sqrt(Bx * Bx + By * By);
132
133    //  (2) Rotate the system so that point B is on the positive X axis.
134    theCos = Bx / distAB;
135    theSin = By / distAB;
136    newX = Cx * theCos + Cy*theSin;
137    Cy = Cy * theCos - Cx*theSin;
138    Cx = newX;
139    newX = Dx * theCos + Dy*theSin;
140    Dy = Dy * theCos - Dx*theSin;
141    Dx = newX;
142
143    //  Fail if segment C-D doesn't cross line A-B.
144    if ( (Cy < 0. && Dy < 0.) || (Cy >= 0. && Dy >= 0.) ) return NO;
145
146    //  (3) Discover the position of the intersection point along line A-B.
147    ABpos = Dx + (Cx - Dx) * Dy / (Dy - Cy);
148
149    //  Fail if segment C-D crosses line A-B outside of segment A-B.
150    if (ABpos < 0. || ABpos > distAB) return NO;
151
152    //  (4) Apply the discovered position to line A-B in the original coordinate system.
153    *X = Ax + ABpos*theCos;
154    *Y = Ay + ABpos*theSin;
155
156    //  Success.
157    return YES;
158}
159
160/*
161WORK IN PROGRESS TO OPTIMISE INTERSECTION
162int __intersection(double x0, double y0,
163                   double x1, double y1) {
164
165
166    x0 = line0[0,0]; y0 = line0[0,1]
167    x1 = line0[1,0]; y1 = line0[1,1]
168
169    x2 = line1[0,0]; y2 = line1[0,1]
170    x3 = line1[1,0]; y3 = line1[1,1]
171
172    denom = (y3-y2)*(x1-x0) - (x3-x2)*(y1-y0)
173    u0 = (x3-x2)*(y0-y2) - (y3-y2)*(x0-x2)
174    u1 = (x2-x0)*(y1-y0) - (y2-y0)*(x1-x0)
175
176    if allclose(denom, 0.0):
177        # Lines are parallel - check if they coincide on a shared a segment
178
179        if allclose( [u0, u1], 0.0 ):
180            # We now know that the lines if continued coincide
181            # The remaining check will establish if the finite lines share a segment
182
183            line0_starts_on_line1 = line0_ends_on_line1 =\
184            line1_starts_on_line0 = line1_ends_on_line0 = False
185
186            if point_on_line([x0, y0], line1):
187                line0_starts_on_line1 = True
188
189            if point_on_line([x1, y1], line1):
190                line0_ends_on_line1 = True
191
192            if point_on_line([x2, y2], line0):
193                line1_starts_on_line0 = True
194
195            if point_on_line([x3, y3], line0):
196                line1_ends_on_line0 = True
197
198            if not(line0_starts_on_line1 or line0_ends_on_line1\
199               or line1_starts_on_line0 or line1_ends_on_line0):
200                # Lines are parallel and would coincide if extended, but not as they are.
201                return 3, None
202
203
204            # One line fully included in the other. Use direction of included line
205            if line0_starts_on_line1 and line0_ends_on_line1:
206                # Shared segment is line0 fully included in line1
207                segment = array([[x0, y0], [x1, y1]])
208
209            if line1_starts_on_line0 and line1_ends_on_line0:
210                # Shared segment is line1 fully included in line0
211                segment = array([[x2, y2], [x3, y3]])
212
213
214            # Overlap with lines are oriented the same way
215            if line0_starts_on_line1 and line1_ends_on_line0:
216                # Shared segment from line0 start to line 1 end
217                segment = array([[x0, y0], [x3, y3]])
218
219            if line1_starts_on_line0 and line0_ends_on_line1:
220                # Shared segment from line1 start to line 0 end
221                segment = array([[x2, y2], [x1, y1]])
222
223
224            # Overlap in opposite directions - use direction of line0
225            if line0_starts_on_line1 and line1_starts_on_line0:
226                # Shared segment from line0 start to line 1 end
227                segment = array([[x0, y0], [x2, y2]])
228
229            if line0_ends_on_line1 and line1_ends_on_line0:
230                # Shared segment from line0 start to line 1 end
231                segment = array([[x3, y3], [x1, y1]])
232
233
234            return 2, segment
235        else:
236            # Lines are parallel but they do not coincide
237            return 4, None #FIXME (Ole): Add distance here instead of None
238
239    else:
240        # Lines are not parallel or coinciding
241        u0 = u0/denom
242        u1 = u1/denom
243
244        x = x0 + u0*(x1-x0)
245        y = y0 + u0*(y1-y0)
246
247        # Sanity check - can be removed to speed up if needed
248        assert allclose(x, x2 + u1*(x3-x2))
249        assert allclose(y, y2 + u1*(y3-y2))
250
251        # Check if point found lies within given line segments
252        if 0.0 <= u0 <= 1.0 and 0.0 <= u1 <= 1.0:
253            # We have intersection
254
255            return 1, array([x, y])
256        else:
257            # No intersection
258            return 0, None
259
260
261}
262*/
263
264
265
266int __interpolate_polyline(int number_of_nodes,
267                           int number_of_points,
268                           double* data,
269                           double* polyline_nodes,
270                           long* gauge_neighbour_id,
271                           double* interpolation_points,
272                           double* interpolated_values,
273                           double rtol,
274                           double atol) {
275
276  int j, i, neighbour_id;
277  double x0, y0, x1, y1, x, y;
278  double segment_len, segment_delta, slope, alpha;
279
280  for (j=0; j<number_of_nodes; j++) {
281
282    neighbour_id = gauge_neighbour_id[j];
283
284    // FIXME(Ole): I am convinced that gauge_neighbour_id can be discarded, but need to check with John J.
285    // Keep it for now (17 Jan 2009)
286    // When gone, we can simply interpolate between neighbouring nodes, i.e. neighbour_id = j+1.
287    // and the test below becomes something like: if j < number_of_nodes...
288
289    if (neighbour_id >= 0) {
290      x0 = polyline_nodes[2*j];
291      y0 = polyline_nodes[2*j+1];
292
293      x1 = polyline_nodes[2*neighbour_id];
294      y1 = polyline_nodes[2*neighbour_id+1];
295
296
297      segment_len = dist(x1-x0, y1-y0);
298      segment_delta = data[neighbour_id] - data[j];
299      slope = segment_delta/segment_len;
300
301      for (i=0; i<number_of_points; i++) {
302        x = interpolation_points[2*i];
303        y = interpolation_points[2*i+1];
304
305        if (__point_on_line(x, y, x0, y0, x1, y1, rtol, atol)) {
306          alpha = dist(x-x0, y-y0);
307          interpolated_values[i] = slope*alpha + data[j];
308        }
309      }
310    }
311  }
312
313  return 0;
314}
315
316
317int __is_inside_triangle(double* point,
318                         double* triangle,
319                         int closed,
320                         double rtol,
321                         double atol) {
322
323  double vx, vy, v0x, v0y, v1x, v1y;
324  double a00, a10, a01, a11, b0, b1;
325  double denom, alpha, beta;
326
327  double x, y; // Point coordinates
328  int i, j, res;
329
330  x = point[0];
331  y = point[1];
332
333  // Quickly reject points that are clearly outside
334  if ((x < triangle[0]) &&
335      (x < triangle[2]) &&
336      (x < triangle[4])) return 0;
337
338  if ((x > triangle[0]) &&
339      (x > triangle[2]) &&
340      (x > triangle[4])) return 0;
341
342  if ((y < triangle[1]) &&
343      (y < triangle[3]) &&
344      (y < triangle[5])) return 0;
345
346  if ((y > triangle[1]) &&
347      (y > triangle[3]) &&
348      (y > triangle[5])) return 0;
349
350
351  // v0 = C-A
352  v0x = triangle[4]-triangle[0];
353  v0y = triangle[5]-triangle[1];
354
355  // v1 = B-A
356  v1x = triangle[2]-triangle[0];
357  v1y = triangle[3]-triangle[1];
358
359  // First check if point lies wholly inside triangle
360  a00 = v0x*v0x + v0y*v0y; // innerproduct(v0, v0)
361  a01 = v0x*v1x + v0y*v1y; // innerproduct(v0, v1)
362  a10 = a01;               // innerproduct(v1, v0)
363  a11 = v1x*v1x + v1y*v1y; // innerproduct(v1, v1)
364
365  denom = a11*a00 - a01*a10;
366
367  if (fabs(denom) > 0.0) {
368    // v = point-A
369    vx = x - triangle[0];
370    vy = y - triangle[1];
371
372    b0 = v0x*vx + v0y*vy; // innerproduct(v0, v)
373    b1 = v1x*vx + v1y*vy; // innerproduct(v1, v)
374
375    alpha = (b0*a11 - b1*a01)/denom;
376    beta = (b1*a00 - b0*a10)/denom;
377
378    if ((alpha > 0.0) && (beta > 0.0) && (alpha+beta < 1.0)) return 1;
379  }
380
381  if (closed) {
382    // Check if point lies on one of the edges
383
384    for (i=0; i<3; i++) {
385      j = (i+1) % 3; // Circular index into triangle array
386      res = __point_on_line(x, y,
387                            triangle[2*i], triangle[2*i+1],
388                            triangle[2*j], triangle[2*j+1],
389                            rtol, atol);
390      if (res) return 1;
391    }
392  }
393
394  // Default return if point is outside triangle
395  return 0;
396}
397
398
399int __separate_points_by_polygon(int M,     // Number of points
400                                 int N,     // Number of polygon vertices
401                                 double* points,
402                                 double* polygon,
403                                 long* indices,  // M-Array for storage indices
404                                 int closed,
405                                 int verbose) {
406
407  double minpx, maxpx, minpy, maxpy, x, y, px_i, py_i, px_j, py_j, rtol=0.0, atol=0.0;
408  int i, j, k, outside_index, inside_index, inside;
409
410  // Find min and max of poly used for optimisation when points
411  // are far away from polygon
412
413  // FIXME(Ole): Pass in rtol and atol from Python
414
415  minpx = polygon[0]; maxpx = minpx;
416  minpy = polygon[1]; maxpy = minpy;
417
418  for (i=0; i<N; i++) {
419    px_i = polygon[2*i];
420    py_i = polygon[2*i + 1];
421
422    if (px_i < minpx) minpx = px_i;
423    if (px_i > maxpx) maxpx = px_i;
424    if (py_i < minpy) minpy = py_i;
425    if (py_i > maxpy) maxpy = py_i;
426  }
427
428  // Begin main loop (for each point)
429  inside_index = 0;    // Keep track of points inside
430  outside_index = M-1; // Keep track of points outside (starting from end)
431  if (verbose){
432     printf("Separating %d points\n", M);
433  }
434  for (k=0; k<M; k++) {
435    if (verbose){
436      if (k %((M+10)/10)==0) printf("Doing %d of %d\n", k, M);
437    }
438
439    x = points[2*k];
440    y = points[2*k + 1];
441
442    inside = 0;
443
444    // Optimisation
445    if ((x > maxpx) || (x < minpx) || (y > maxpy) || (y < minpy)) {
446      // Nothing
447    } else {
448      // Check polygon
449      for (i=0; i<N; i++) {
450        j = (i+1)%N;
451
452        px_i = polygon[2*i];
453        py_i = polygon[2*i+1];
454        px_j = polygon[2*j];
455        py_j = polygon[2*j+1];
456
457        // Check for case where point is contained in line segment
458        if (__point_on_line(x, y, px_i, py_i, px_j, py_j, rtol, atol)) {
459          if (closed == 1) {
460            inside = 1;
461          } else {
462            inside = 0;
463          }
464          break;
465        } else {
466          //Check if truly inside polygon
467          if ( ((py_i < y) && (py_j >= y)) ||
468               ((py_j < y) && (py_i >= y)) ) {
469            if (px_i + (y-py_i)/(py_j-py_i)*(px_j-px_i) < x)
470              inside = 1-inside;
471          }
472        }
473      }
474    }
475    if (inside == 1) {
476      indices[inside_index] = k;
477      inside_index += 1;
478    } else {
479      indices[outside_index] = k;
480      outside_index -= 1;
481    }
482  } // End k
483
484  return inside_index;
485}
486
487
488
489// Gateways to Python
490PyObject *_point_on_line(PyObject *self, PyObject *args) {
491  //
492  // point_on_line(x, y, x0, y0, x1, y1)
493  //
494
495  double x, y, x0, y0, x1, y1, rtol, atol;
496  int res;
497  PyObject *result;
498
499  // Convert Python arguments to C
500  if (!PyArg_ParseTuple(args, "dddddddd", &x, &y, &x0, &y0, &x1, &y1, &rtol, &atol)) {
501    PyErr_SetString(PyExc_RuntimeError,
502                    "point_on_line could not parse input");
503    return NULL;
504  }
505
506
507  // Call underlying routine
508  res = __point_on_line(x, y, x0, y0, x1, y1, rtol, atol);
509
510  // Return values a and b
511  result = Py_BuildValue("i", res);
512  return result;
513}
514
515
516
517// Gateways to Python
518PyObject *_interpolate_polyline(PyObject *self, PyObject *args) {
519  //
520  // _interpolate_polyline(data, polyline_nodes, gauge_neighbour_id, interpolation_points
521  //                       interpolated_values):
522  //
523
524
525  PyArrayObject
526    *data,
527    *polyline_nodes,
528    *gauge_neighbour_id,
529    *interpolation_points,
530    *interpolated_values;
531
532  double rtol, atol;
533  int number_of_nodes, number_of_points, res;
534
535  // Convert Python arguments to C
536  if (!PyArg_ParseTuple(args, "OOOOOdd",
537                        &data,
538                        &polyline_nodes,
539                        &gauge_neighbour_id,
540                        &interpolation_points,
541                        &interpolated_values,
542                        &rtol,
543                        &atol)) {
544
545    PyErr_SetString(PyExc_RuntimeError,
546                    "_interpolate_polyline could not parse input");
547    return NULL;
548  }
549
550  // check that numpy array objects arrays are C contiguous memory
551  CHECK_C_CONTIG(data);
552  CHECK_C_CONTIG(polyline_nodes);
553  CHECK_C_CONTIG(gauge_neighbour_id);
554  CHECK_C_CONTIG(interpolation_points);
555  CHECK_C_CONTIG(interpolated_values);
556
557  number_of_nodes = polyline_nodes -> dimensions[0];  // Number of nodes in polyline
558  number_of_points = interpolation_points -> dimensions[0];   //Number of points
559
560
561  // Call underlying routine
562  res = __interpolate_polyline(number_of_nodes,
563                               number_of_points,
564                               (double*) data -> data,
565                               (double*) polyline_nodes -> data,
566                               (long*) gauge_neighbour_id -> data,
567                               (double*) interpolation_points -> data,
568                               (double*) interpolated_values -> data,
569                               rtol,
570                               atol);
571
572  // Return
573  return Py_BuildValue("");
574}
575
576
577
578
579PyObject *_is_inside_triangle(PyObject *self, PyObject *args) {
580  //
581  // _is_inside_triangle(point, triangle, int(closed), rtol, atol)
582  //
583
584
585  PyArrayObject
586    *point,
587    *triangle;
588
589  double rtol, atol;
590  int closed, res;
591
592  PyObject *result;
593
594  // Convert Python arguments to C
595  if (!PyArg_ParseTuple(args, "OOidd",
596                        &point,
597                        &triangle,
598                        &closed,
599                        &rtol,
600                        &atol)) {
601
602    PyErr_SetString(PyExc_RuntimeError,
603                    "_is_inside_triangle could not parse input");
604    return NULL;
605  }
606
607  // Call underlying routine
608  res = __is_inside_triangle((double*) point -> data,
609                             (double*) triangle -> data,
610                             closed,
611                             rtol,
612                             atol);
613
614
615  // Return result
616  result = Py_BuildValue("i", res);
617  return result;
618}
619
620
621
622/*
623PyObject *_intersection(PyObject *self, PyObject *args) {
624  //
625  // intersection(x0, y0, x1, y1)
626  //
627
628  double x, y, x0, y0, x1, y1;
629  int res;
630  PyObject *result;
631
632  // Convert Python arguments to C
633  if (!PyArg_ParseTuple(args, "dddddd", &x, &y, &x0, &y0, &x1, &y1)) {
634    PyErr_SetString(PyExc_RuntimeError,
635                    "point_on_line could not parse input");
636    return NULL;
637  }
638
639
640  // Call underlying routine
641  res = __intersection(x, y, x0, y0, x1, y1);
642
643  // Return values a and b
644  result = Py_BuildValue("i", res);
645  return result;
646}
647*/
648
649
650PyObject *_separate_points_by_polygon(PyObject *self, PyObject *args) {
651  //def separate_points_by_polygon(points, polygon, closed, verbose, one_point):
652  //  """Determine whether points are inside or outside a polygon
653  //
654  //  Input:
655  //     point - Tuple of (x, y) coordinates, or list of tuples
656  //     polygon - list of vertices of polygon
657  //     closed - (optional) determine whether points on boundary should be
658  //     regarded as belonging to the polygon (closed = True)
659  //     or not (closed = False)
660
661  //
662  //  Output:
663  //     indices: array of same length as points with indices of points falling
664  //     inside the polygon listed from the beginning and indices of points
665  //     falling outside listed from the end.
666  //
667  //     count: count of points falling inside the polygon
668  //
669  //     The indices of points inside are obtained as indices[:count]
670  //     The indices of points outside are obtained as indices[count:]
671  //
672  //  Examples:
673  //     separate_polygon( [[0.5, 0.5], [1, -0.5], [0.3, 0.2]] )
674  //     will return the indices [0, 2, 1] as only the first and the last point
675  //     is inside the unit square
676  //
677  //  Remarks:
678  //     The vertices may be listed clockwise or counterclockwise and
679  //     the first point may optionally be repeated.
680  //     Polygons do not need to be convex.
681  //     Polygons can have holes in them and points inside a hole is
682  //     regarded as being outside the polygon.
683  //
684  //
685  //  Algorithm is based on work by Darel Finley,
686  //  http://www.alienryderflex.com/polygon/
687  //
688  //
689
690  PyArrayObject
691    *points,
692    *polygon,
693    *indices;
694
695  int closed, verbose; //Flags
696  int count, M, N;
697
698  // Convert Python arguments to C
699  if (!PyArg_ParseTuple(args, "OOOii",
700                        &points,
701                        &polygon,
702                        &indices,
703                        &closed,
704                        &verbose)) {
705
706
707    PyErr_SetString(PyExc_RuntimeError,
708                    "separate_points_by_polygon could not parse input");
709    return NULL;
710  }
711
712  // check that points, polygon and indices arrays are C contiguous
713  CHECK_C_CONTIG(points);
714  CHECK_C_CONTIG(polygon);
715  CHECK_C_CONTIG(indices);
716
717  M = points -> dimensions[0];   //Number of points
718  N = polygon -> dimensions[0];  //Number of vertices in polygon
719
720  //FIXME (Ole): This isn't send to Python's sys.stdout
721  if (verbose) printf("Got %d points and %d polygon vertices\n", M, N);
722
723  //Call underlying routine
724  count = __separate_points_by_polygon(M, N,
725                                       (double*) points -> data,
726                                       (double*) polygon -> data,
727                                       (long*) indices -> data,
728                                       closed, verbose);
729
730  //NOTE: return number of points inside..
731  return Py_BuildValue("i", count);
732}
733
734
735
736// Method table for python module
737static struct PyMethodDef MethodTable[] = {
738  /* The cast of the function is necessary since PyCFunction values
739   * only take two PyObject* parameters, and rotate() takes
740   * three.
741   */
742
743  {"_point_on_line", _point_on_line, METH_VARARGS, "Print out"},
744  //{"_intersection", _intersection, METH_VARARGS, "Print out"},
745  {"_separate_points_by_polygon", _separate_points_by_polygon,
746                                 METH_VARARGS, "Print out"},
747  {"_interpolate_polyline", _interpolate_polyline,
748                                 METH_VARARGS, "Print out"},
749  {"_is_inside_triangle", _is_inside_triangle,
750                                 METH_VARARGS, "Print out"},
751  {NULL, NULL, 0, NULL}   /* sentinel */
752};
753
754
755
756// Module initialisation
757void initpolygon_ext(void){
758  Py_InitModule("polygon_ext", MethodTable);
759
760  import_array();     //Necessary for handling of NumPY structures
761}
762
763
764
Note: See TracBrowser for help on using the repository browser.