source: inundation/ga/storm_surge/pyvolution/shallow_water_ext.c @ 271

Last change on this file since 271 was 267, checked in by ole, 21 years ago

C implementation of balanced_deep_and_shallow.

File size: 17.6 KB
Line 
1// Python - C extension module for shallow_water.py
2//
3// To compile (Python2.3):
4//  gcc -c domain_ext.c -I/usr/include/python2.3 -o domain_ext.o -Wall -O
5//  gcc -shared domain_ext.o  -o domain_ext.so 
6//
7// or use python compile.py
8//
9// See the module shallow_water.py
10//
11//
12// Ole Nielsen, GA 2004
13   
14   
15#include "Python.h"
16#include "Numeric/arrayobject.h"
17#include "math.h"
18
19//Shared code snippets
20#include "util_ext.h"
21
22
23// Computational function for rotation
24int _rotate(double *q, double n1, double n2) {
25  /*Rotate the momentum component q (q[1], q[2])
26    from x,y coordinates to coordinates based on normal vector (n1, n2).
27   
28    Result is returned in array 3x1 r     
29    To rotate in opposite direction, call rotate with (q, n1, -n2)
30   
31    Contents of q are changed by this function */   
32
33
34  double q1, q2;
35 
36  //Shorthands
37  q1 = q[1];  //uh momentum
38  q2 = q[2];  //vh momentum
39
40  //Rotate
41  q[1] =  n1*q1 + n2*q2;
42  q[2] = -n2*q1 + n1*q2; 
43
44  return 0;
45} 
46
47
48       
49// Computational function for flux computation (using stage w=z+h)
50int flux_function(double *q_left, double *q_right, 
51                  double z_left, double z_right, 
52                  double n1, double n2, 
53                  double epsilon, double g, 
54                  double *edgeflux, double *max_speed) {
55 
56  /*Compute fluxes between volumes for the shallow water wave equation
57    cast in terms of the 'stage', w = h+z using
58    the 'central scheme' as described in
59   
60    Kurganov, Noelle, Petrova. 'Semidiscrete Central-Upwind Schemes For
61    Hyperbolic Conservation Laws and Hamilton-Jacobi Equations'.
62    Siam J. Sci. Comput. Vol. 23, No. 3, pp. 707-740.
63   
64    The implemented formula is given in equation (3.15) on page 714
65  */
66       
67  int i;
68       
69  double w_left, h_left, uh_left, vh_left, u_left;
70  double w_right, h_right, uh_right, vh_right, u_right;
71  double s_min, s_max, soundspeed_left, soundspeed_right;
72  double denom, z;
73  double q_left_copy[3], q_right_copy[3];   
74  double flux_right[3], flux_left[3];
75 
76  //Copy conserved quantities to protect from modification
77  for (i=0; i<3; i++) {
78    q_left_copy[i] = q_left[i];
79    q_right_copy[i] = q_right[i];
80  } 
81   
82  //Align x- and y-momentum with x-axis
83  _rotate(q_left_copy, n1, n2);
84  _rotate(q_right_copy, n1, n2);   
85
86  z = (z_left+z_right)/2; //Take average of field values
87
88  //Compute speeds in x-direction
89  w_left = q_left_copy[0];              // h+z
90  h_left = w_left-z;
91  uh_left = q_left_copy[1];
92
93  if (h_left < epsilon) {
94    h_left = 0.0;  //Could have been negative
95    u_left = 0.0;
96  } else { 
97    u_left = uh_left/h_left;
98  }
99 
100  w_right = q_right_copy[0];
101  h_right = w_right-z;
102  uh_right = q_right_copy[1];
103
104  if (h_right < epsilon) {
105    h_right = 0.0; //Could have been negative
106    u_right = 0.0;
107  } else { 
108    u_right = uh_right/h_right;
109  }
110
111  //Momentum in y-direction             
112  vh_left  = q_left_copy[2];
113  vh_right = q_right_copy[2];   
114       
115
116  //Maximal and minimal wave speeds
117  soundspeed_left  = sqrt(g*h_left); 
118  soundspeed_right = sqrt(g*h_right);
119   
120  s_max = max(u_left+soundspeed_left, u_right+soundspeed_right);
121  if (s_max < 0.0) s_max = 0.0; 
122 
123  s_min = min(u_left-soundspeed_left, u_right-soundspeed_right);
124  if (s_min > 0.0) s_min = 0.0;   
125 
126  //Flux formulas 
127  flux_left[0] = u_left*h_left;
128  flux_left[1] = u_left*uh_left + 0.5*g*h_left*h_left;
129  flux_left[2] = u_left*vh_left;
130 
131  flux_right[0] = u_right*h_right;
132  flux_right[1] = u_right*uh_right + 0.5*g*h_right*h_right;
133  flux_right[2] = u_right*vh_right;
134   
135
136  //Flux computation   
137  denom = s_max-s_min;
138  if (denom == 0.0) {
139    for (i=0; i<3; i++) edgeflux[i] = 0.0;
140    *max_speed = 0.0;
141  } else {   
142    for (i=0; i<3; i++) {
143      edgeflux[i] = s_max*flux_left[i] - s_min*flux_right[i];
144      edgeflux[i] += s_max*s_min*(q_right_copy[i]-q_left_copy[i]);
145      edgeflux[i] /= denom;
146    } 
147       
148    //Maximal wavespeed
149    *max_speed = max(fabs(s_max), fabs(s_min));
150   
151    //Rotate back       
152    _rotate(edgeflux, n1, -n2);
153  }
154  return 0;
155}
156       
157void _manning_friction(double g, double eps, int N, 
158                       double* w, double* uh, double* vh, 
159                       double* eta, double* xmom, double* ymom) {     
160
161  int k;
162  double S;
163 
164  for (k=0; k<N; k++) {
165    if (w[k] >= eps) {
166      S = -g * eta[k]*eta[k] * sqrt((uh[k]*uh[k] + vh[k]*vh[k]));
167      S /= pow(w[k], 7.0/3);     
168
169      //Update momentum
170      xmom[k] += S*uh[k];
171      ymom[k] += S*vh[k];
172    }
173  }
174 
175}
176           
177
178
179int _balance_deep_and_shallow(int N,
180                              double* wc,
181                              double* zc, 
182                              double* hc,                             
183                              double* wv, 
184                              double* zv, 
185                              double* hv,
186                              double* xmomc, 
187                              double* ymomc, 
188                              double* xmomv, 
189                              double* ymomv) { 
190 
191  int k, k3, i;
192  double dz, hmin, alpha;
193 
194  //Compute linear combination between constant levels and and
195  //levels parallel to the bed elevation.     
196 
197  for (k=0; k<N; k++) {
198    // Compute maximal variation in bed elevation
199    // This quantitiy is
200    //     dz = max_i abs(z_i - z_c)
201    // and it is independent of dimension
202    // In the 1d case zc = (z0+z1)/2
203    // In the 2d case zc = (z0+z1+z2)/3
204
205    k3 = 3*k;
206   
207    //FIXME: Try with this one precomputed
208    dz = 0.0;
209    hmin = hv[k3];
210    for (i=0; i<3; i++) {
211      dz = max(dz, fabs(zv[k3+i]-zc[k]));
212      hmin = min(hmin, hv[k3+i]);
213    }
214
215   
216    //Create alpha in [0,1], where alpha==0 means using shallow
217    //first order scheme and alpha==1 means using the stage w as
218    //computed by the gradient limiter (1st or 2nd order)
219    //
220    //If hmin > dz/2 then alpha = 1 and the bed will have no effect
221    //If hmin < 0 then alpha = 0 reverting to constant height above bed.
222   
223    if (dz > 0.0) 
224      alpha = max( min( 2*hmin/dz, 1.0), 0.0 );
225    else
226      alpha = 1.0;  //Flat bed
227
228
229    //Weighted balance between stage parallel to bed elevation
230    //(wvi = zvi + hc) and stage as computed by 1st or 2nd
231    //order gradient limiter
232    //(wvi = zvi + hvi) where i=0,1,2 denotes the vertex ids
233    //
234    //It follows that the updated wvi is
235    //  wvi := (1-alpha)*(zvi+hc) + alpha*(zvi+hvi) =
236    //  zvi + hc + alpha*(hvi - hc)
237    //
238    //Note that hvi = zc+hc-zvi in the first order case (constant).
239
240    if (alpha < 1) {         
241      for (i=0; i<3; i++) {
242        wv[k3+i] = zv[k3+i] + hc[k] + alpha*(hv[k3+i]-hc[k]);
243           
244     
245        //Update momentum as a linear combination of
246        //xmomc and ymomc (shallow) and momentum
247        //from extrapolator xmomv and ymomv (deep).
248        xmomv[k3+i] = (1-alpha)*xmomc[k] + alpha*xmomv[k3+i];           
249        ymomv[k3+i] = (1-alpha)*ymomc[k] + alpha*ymomv[k3+i];
250      } 
251    }
252  }         
253  return 0;
254}
255
256///////////////////////////////////////////////////////////////////
257// Gateways to Python
258
259PyObject *gravity(PyObject *self, PyObject *args) {
260  //
261  //  gravity(g, h, v, x, xmom, ymom)
262  //
263 
264 
265  PyArrayObject *h, *v, *x, *xmom, *ymom;
266  int k, i, N, k3, k6;
267  double g, avg_h, zx, zy;
268  double x0, y0, x1, y1, x2, y2, z0, z1, z2;
269   
270  if (!PyArg_ParseTuple(args, "dOOOOO",
271                        &g, &h, &v, &x, 
272                        &xmom, &ymom)) 
273    return NULL; 
274
275  N = h -> dimensions[0];
276  for (k=0; k<N; k++) {
277    k3 = 3*k;  // base index
278    k6 = 6*k;  // base index   
279   
280    avg_h = 0.0;
281    for (i=0; i<3; i++) {
282      avg_h += ((double *) h -> data)[k3+i];
283    }   
284    avg_h /= 3;
285       
286   
287    //Compute bed slope
288    x0 = ((double*) x -> data)[k6 + 0];
289    y0 = ((double*) x -> data)[k6 + 1];   
290    x1 = ((double*) x -> data)[k6 + 2];
291    y1 = ((double*) x -> data)[k6 + 3];       
292    x2 = ((double*) x -> data)[k6 + 4];
293    y2 = ((double*) x -> data)[k6 + 5];           
294
295
296    z0 = ((double*) v -> data)[k3 + 0];
297    z1 = ((double*) v -> data)[k3 + 1];
298    z2 = ((double*) v -> data)[k3 + 2];       
299
300    _gradient(x0, y0, x1, y1, x2, y2, z0, z1, z2, &zx, &zy);
301
302    //Update momentum
303    ((double*) xmom -> data)[k] += -g*zx*avg_h;
304    ((double*) ymom -> data)[k] += -g*zy*avg_h;       
305  }
306   
307  return Py_BuildValue("");
308}
309
310
311PyObject *manning_friction(PyObject *self, PyObject *args) {
312  //
313  // manning_friction(g, eps, w, uh, vh, eta, xmom_update, ymom_update)
314  //
315 
316 
317  PyArrayObject *w, *uh, *vh, *eta, *xmom, *ymom;
318  int N;
319  double g, eps;
320   
321  if (!PyArg_ParseTuple(args, "ddOOOOOO",
322                        &g, &eps, &w, &uh, &vh, &eta, 
323                        &xmom, &ymom)) 
324    return NULL; 
325
326  N = w -> dimensions[0];   
327  _manning_friction(g, eps, N,
328                    (double*) w -> data,
329                    (double*) uh -> data, 
330                    (double*) vh -> data, 
331                    (double*) eta -> data,
332                    (double*) xmom -> data, 
333                    (double*) ymom -> data);
334
335  return Py_BuildValue("");
336}                   
337
338PyObject *rotate(PyObject *self, PyObject *args, PyObject *kwargs) {
339  //
340  // r = rotate(q, normal, direction=1)
341  //
342  // Where q is assumed to be a Float numeric array of length 3 and
343  // normal a Float numeric array of length 2.
344
345 
346  PyObject *Q, *Normal;
347  PyArrayObject *q, *r, *normal;
348 
349  static char *argnames[] = {"q", "normal", "direction", NULL};
350  int dimensions[1], i, direction=1;
351  double n1, n2;
352
353  // Convert Python arguments to C 
354  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|i", argnames, 
355                                   &Q, &Normal, &direction)) 
356    return NULL; 
357
358  //Input checks (convert sequences into numeric arrays)
359  q = (PyArrayObject *) 
360    PyArray_ContiguousFromObject(Q, PyArray_DOUBLE, 0, 0);
361  normal = (PyArrayObject *) 
362    PyArray_ContiguousFromObject(Normal, PyArray_DOUBLE, 0, 0);
363 
364  //Allocate space for return vector r (don't DECREF)
365  dimensions[0] = 3;
366  r = (PyArrayObject *) PyArray_FromDims(1, dimensions, PyArray_DOUBLE);
367
368  //Copy
369  for (i=0; i<3; i++) {
370    ((double *) (r -> data))[i] = ((double *) (q -> data))[i]; 
371  }
372 
373  //Get normal and direction
374  n1 = ((double *) normal -> data)[0]; 
375  n2 = ((double *) normal -> data)[1];   
376  if (direction == -1) n2 = -n2;
377
378  //Rotate
379  _rotate((double *) r -> data, n1, n2);
380
381  //Release numeric arrays
382  Py_DECREF(q);   
383  Py_DECREF(normal);
384       
385  //return result using PyArray to avoid memory leak
386  return PyArray_Return(r);
387}   
388
389
390
391
392
393PyObject *compute_fluxes(PyObject *self, PyObject *args) {
394  /*Compute all fluxes and the timestep suitable for all volumes
395    in domain.
396
397    Compute total flux for each conserved quantity using "flux_function"
398
399    Fluxes across each edge are scaled by edgelengths and summed up
400    Resulting flux is then scaled by area and stored in
401    explicit_update for each of the three conserved quantities
402    level, xmomentum and ymomentum
403
404    The maximal allowable speed computed by the flux_function for each volume
405    is converted to a timestep that must not be exceeded. The minimum of
406    those is computed as the next overall timestep.
407   
408    Python call:
409    domain.timestep = compute_fluxes(timestep,
410                                     domain.epsilon,
411                                     domain.g,
412                                     domain.neighbours,
413                                     domain.neighbour_edges,
414                                     domain.normals,
415                                     domain.edgelengths,                       
416                                     domain.radii,
417                                     domain.areas,
418                                     Level.edge_values,
419                                     Xmom.edge_values,
420                                     Ymom.edge_values, 
421                                     Bed.edge_values,   
422                                     Level.boundary_values,
423                                     Xmom.boundary_values,
424                                     Ymom.boundary_values,
425                                     Level.explicit_update,
426                                     Xmom.explicit_update,
427                                     Ymom.explicit_update)
428       
429
430    Post conditions:
431      domain.explicit_update is reset to computed flux values
432      domain.timestep is set to the largest step satisfying all volumes.
433
434           
435  */
436
437 
438  PyArrayObject *neighbours, *neighbour_edges,
439    *normals, *edgelengths, *radii, *areas,
440    *level_edge_values, 
441    *xmom_edge_values, 
442    *ymom_edge_values, 
443    *bed_edge_values,   
444    *level_boundary_values,
445    *xmom_boundary_values,
446    *ymom_boundary_values,
447    *level_explicit_update,
448    *xmom_explicit_update,
449    *ymom_explicit_update;
450
451   
452  //Local variables 
453  double timestep, max_speed, epsilon, g;
454  double normal[2], ql[3], qr[3], zl, zr;
455  double flux[3], edgeflux[3]; //Work arrays for summing up fluxes
456
457  int number_of_elements, k, i, j, m, n;
458  int ki, nm, ki2; //Index shorthands
459 
460 
461  // Convert Python arguments to C 
462  if (!PyArg_ParseTuple(args, "dddOOOOOOOOOOOOOOOO",
463                        &timestep,
464                        &epsilon,
465                        &g,
466                        &neighbours, 
467                        &neighbour_edges,
468                        &normals, 
469                        &edgelengths, &radii, &areas,
470                        &level_edge_values, 
471                        &xmom_edge_values, 
472                        &ymom_edge_values, 
473                        &bed_edge_values,   
474                        &level_boundary_values,
475                        &xmom_boundary_values,
476                        &ymom_boundary_values,
477                        &level_explicit_update,
478                        &xmom_explicit_update,
479                        &ymom_explicit_update)) {
480    PyErr_SetString(PyExc_RuntimeError, "Input arguments failed");
481    return NULL;
482  }
483
484  number_of_elements = level_edge_values -> dimensions[0];
485 
486   
487  for (k=0; k<number_of_elements; k++) {
488
489    //Reset work array
490    for (j=0; j<3; j++) flux[j] = 0.0;
491                         
492    //Loop through neighbours and compute edge flux for each
493    for (i=0; i<3; i++) {
494      ki = k*3+i;
495      ql[0] = ((double *) level_edge_values -> data)[ki];
496      ql[1] = ((double *) xmom_edge_values -> data)[ki];
497      ql[2] = ((double *) ymom_edge_values -> data)[ki];           
498      zl =    ((double *) bed_edge_values -> data)[ki];                 
499     
500      //Quantities at neighbour on nearest face
501      n = ((int *) neighbours -> data)[ki];
502      if (n < 0) {
503        m = -n-1; //Convert negative flag to index
504        qr[0] = ((double *) level_boundary_values -> data)[m]; 
505        qr[1] = ((double *) xmom_boundary_values -> data)[m];   
506        qr[2] = ((double *) ymom_boundary_values -> data)[m];   
507        zr = zl; //Extend bed elevation to boundary
508      } else {   
509        m = ((int *) neighbour_edges -> data)[ki];
510       
511        nm = n*3+m;     
512        qr[0] = ((double *) level_edge_values -> data)[nm];
513        qr[1] = ((double *) xmom_edge_values -> data)[nm];
514        qr[2] = ((double *) ymom_edge_values -> data)[nm];           
515        zr =    ((double *) bed_edge_values -> data)[nm];                 
516      }
517     
518      // Outward pointing normal vector   
519      // normal = domain.normals[k, 2*i:2*i+2]
520      ki2 = 2*ki; //k*6 + i*2
521      normal[0] = ((double *) normals -> data)[ki2];
522      normal[1] = ((double *) normals -> data)[ki2+1];     
523
524      //Edge flux computation
525      flux_function(ql, qr, zl, zr, 
526                    normal[0], normal[1],
527                    epsilon, g, 
528                    edgeflux, &max_speed);
529
530                   
531      //flux -= edgeflux * edgelengths[k,i]
532      for (j=0; j<3; j++) { 
533        flux[j] -= edgeflux[j]*((double *) edgelengths -> data)[ki];
534      }
535     
536      //Update timestep
537      //timestep = min(timestep, domain.radii[k]/max_speed)
538      if (max_speed > epsilon) {
539        timestep = min(timestep, ((double *) radii -> data)[k]/max_speed);
540      }   
541    } // end for i
542   
543    //Normalise by area and store for when all conserved
544    //quantities get updated
545    // flux /= areas[k]
546    for (j=0; j<3; j++) { 
547      flux[j] /= ((double *) areas -> data)[k];
548    }
549
550    ((double *) level_explicit_update -> data)[k] = flux[0];
551    ((double *) xmom_explicit_update -> data)[k] = flux[1];
552    ((double *) ymom_explicit_update -> data)[k] = flux[2];       
553
554  } //end for k
555
556  return Py_BuildValue("d", timestep);
557}   
558
559
560
561PyObject *balance_deep_and_shallow(PyObject *self, PyObject *args) {
562  //
563  //    balance_deep_and_shallow(domain.number_of_elements,
564  //                             wc, zc, hc, wv, zv, hv,
565  //                             xmomc, ymomc, xmomv, ymomv)
566 
567
568  PyArrayObject
569    *wc,            //Level at centroids
570    *zc,            //Elevation at centroids   
571    *hc,            //Height at centroids       
572    *wv,            //Level at vertices
573    *zv,            //Elevation at vertices
574    *hv,            //Heights at vertices   
575    *xmomc,         //Momentums at centroids and vertices
576    *ymomc, 
577    *xmomv, 
578    *ymomv;   
579   
580  int N; //, err;
581 
582  // Convert Python arguments to C 
583  if (!PyArg_ParseTuple(args, "OOOOOOOOOO", 
584                        &wc, &zc, &hc, 
585                        &wv, &zv, &hv,
586                        &xmomc, &ymomc, &xmomv, &ymomv))
587    return NULL;
588
589  N = wc -> dimensions[0];
590   
591  _balance_deep_and_shallow(N,
592                            (double*) wc -> data,
593                            (double*) zc -> data, 
594                            (double*) hc -> data,                           
595                            (double*) wv -> data, 
596                            (double*) zv -> data, 
597                            (double*) hv -> data,
598                            (double*) xmomc -> data, 
599                            (double*) ymomc -> data, 
600                            (double*) xmomv -> data, 
601                            (double*) ymomv -> data); 
602 
603 
604  return Py_BuildValue(""); 
605}
606
607
608
609
610
611//////////////////////////////////////////     
612// Method table for python module
613static struct PyMethodDef MethodTable[] = {
614  /* The cast of the function is necessary since PyCFunction values
615   * only take two PyObject* parameters, and rotate() takes
616   * three.
617   */
618 
619  {"rotate", (PyCFunction)rotate, METH_VARARGS | METH_KEYWORDS, "Print out"},
620  {"compute_fluxes", compute_fluxes, METH_VARARGS, "Print out"},   
621  {"gravity", gravity, METH_VARARGS, "Print out"},     
622  {"manning_friction", manning_friction, METH_VARARGS, "Print out"},       
623  {"balance_deep_and_shallow", balance_deep_and_shallow, 
624   METH_VARARGS, "Print out"},         
625  //{"distribute_to_vertices_and_edges",
626  // distribute_to_vertices_and_edges, METH_VARARGS},   
627  //{"update_conserved_quantities",
628  // update_conserved_quantities, METH_VARARGS},       
629  //{"set_initialcondition",
630  // set_initialcondition, METH_VARARGS},   
631  {NULL, NULL}
632};
633       
634// Module initialisation   
635void initshallow_water_ext(void){
636  Py_InitModule("shallow_water_ext", MethodTable);
637 
638  import_array();     //Necessary for handling of NumPY structures 
639}
Note: See TracBrowser for help on using the repository browser.