Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/analytic_dam_sudi.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/analytic_dam_sudi.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/analytic_dam_sudi.py	(revision 7906)
@@ -0,0 +1,143 @@
+
+
+class AnalyticDam:
+
+    def __init__(self, h0 = 5.0, h1 = 10.0, L = 2000.0):
+        from math import sqrt
+        
+        self.h0 = h0 # depth upstream (m)
+        self.h1 = h1 # depth downstream (m)
+        self.L  = L  # length of domain
+
+        g  = 9.81    # gravity (m/s^2)
+        
+        c0 = sqrt(g*h0) #left celerity
+        c1 = sqrt(g*h1) #right celerity
+        
+        zmin=-100.0
+        zmax=101.0
+        for i in range(100):
+            z=(zmin+zmax)/2.0
+            u2=z-c0*c0/4.0/z*(1.0+sqrt(1.0+8.0*z*z/c0/c0))
+            c2=c0*sqrt(0.5*(sqrt(1.0+8.0*z*z/c0/c0)-1.0))
+            func=2.0*c1/c0-u2/c0-2.0*c2/c0
+            if (func > 0.0):
+                zmin=z
+            else:
+                zmax=z
+            #print 'func=',func
+        if( abs(z) > 99.0):
+            print 'no convergence'
+
+        self.u2 = u2
+        self.c0 = c0
+        self.c1 = c1
+        self.c2 = c2
+        self.g = g
+        self.z = z
+
+
+
+    def __call__(self, C,t):
+        
+        from Numeric import Float
+        from numpy import zeros        
+        from math import sqrt
+    
+        #t  = 0.0     # time (s)
+        h0 = self.h0    
+        h1 = self.h1    
+        L = self.L 
+        n = len(C)    # number of cells
+
+        u2 = self.u2
+        c0 = self.c0
+        c1 = self.c1
+        c2 = self.c2
+        
+        g = self.g
+        z = self.z
+
+        u = zeros(n,Float)
+        h = zeros(n,Float)
+        uh = zeros(n,Float)
+        x = C-3*L/4.0
+        #x = zeros(n,Float)
+        #for i in range(n):
+        #    x[i] = C[i]-1000.0
+
+        # Upstream and downstream boundary conditions are set to the intial water
+        # depth for all time.
+
+        # Calculate Shock Speed
+        #h2 = 7.2692044
+        
+        #S2 = 2*h2/(h2-h0)*(sqrt(g*h1)-sqrt(g*h2))
+        #u2 = S2 - g*h0/(4*S2)*(1+sqrt(1+8*S2*S2/(g*h0)))
+
+        h2=h0/(1.0-u2/z)
+        x3=(u2-c2)*t
+        x2=z*t
+        x1=-c1*t
+        x1_ = -1*L/2.0-x1
+        x2_ = -1*L/2.0+2*x1
+        #x3_ = -1*L/2.0-x3
+        #t=50 
+        #x = (-L/2:L/2) 
+        for i in range(n):
+            # Calculate Analytical Solution at time t > 0
+            u3 = 2.0/3.0*(sqrt(g*h1)+x[i]/t) 
+            h3 = 4.0/(9.0*g)*(sqrt(g*h1)-x[i]/(2.0*t))*(sqrt(g*h1)-x[i]/(2.0*t))
+            u3_ = 2.0/3.0*((x[i]+L/2.0)/t-sqrt(g*h1))
+            h3_ = 1.0/(9.0*g)*((x[i]+L/2.0)/t+2*sqrt(g*h1))*((x[i]+L/2.0)/t+2*sqrt(g*h1))
+            #if t == 30:
+            #    x[i] = 500
+            #    print 'x2',x2
+            #    print 'x3',x3
+            #    print 'x1',x1
+            if ( x[i] <= x2_ ):
+                #print 'here x2_=', x2_
+                u[i] = 0.0
+                h[i] = 0.0
+                uh [i] = u[i]*h[i]
+            #elif ( x[i] <= x3_ ):
+            #    print 'here x3_=', x3_
+            #    u[i] = -1*u2 
+            #    h[i] = h2
+            #    uh[i] = u[i]*h[i]
+            elif ( x[i] <= x1_ ):
+                #print 'here x1_=', x1_
+                u[i] = u3_ 
+                h[i] = h3_
+                uh[i] = u[i]*h[i]
+            #else:
+            #    u[i] = 0.0 
+            #    h[i] = h0
+            #    uh[i] = u[i]*h[i]
+
+            #elif ( x[i] <= x1/2.0 ):
+            #    u[i] = 0.0 
+            #    h[i] = h1
+            #    uh[i] = u[i]*h[i]
+            elif ( x[i] <= x1 ):
+                #print 'here x1=', x1
+                u[i] = 0.0 
+                h[i] = h1
+                uh[i] = u[i]*h[i]
+            elif ( x[i] <= x3 ):
+                #print 'here x3=', x3
+                u[i] = u3 
+                h[i] = h3
+                uh[i] = u[i]*h[i]
+            elif ( x[i] < x2 ):
+                #print 'here x2=', x2
+                u[i] = u2 
+                h[i] = h2
+                uh[i] = u[i]*h[i]
+            else:
+                #print 'here the last section'
+                u[i] = 0.0 
+                h[i] = h0
+                uh[i] = u[i]*h[i]
+
+        return h , uh, u
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/comp_flux_ext_wellbalanced.c
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/comp_flux_ext_wellbalanced.c	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/comp_flux_ext_wellbalanced.c	(revision 7906)
@@ -0,0 +1,385 @@
+#include "Python.h"
+#include "Numeric/arrayobject.h"
+#include "math.h"
+#include <stdio.h>
+#include "util_ext.h"
+const double pi = 3.14159265358979;
+
+//Innermost flux function (using w=z+h)
+int _flux_function_wellbalanced(double *q_left, 
+								double *q_right,
+								double normals, 
+								double g, 
+								double epsilon,
+								double *edgeflux, 
+								double *max_speed) {		
+		int i;
+        double z_in, z_out;
+		double flux_in[2], flux_out[2];
+		double z_star, w_in, h_in, h_in_star, uh_in, soundspeed_in, u_in;
+		double w_out, h_out, h_out_star, uh_out, soundspeed_out, u_out;
+		double s_max, s_min, denom;
+		
+		w_in  = q_left[0];
+		uh_in = q_left[1];
+		uh_in = uh_in*normals;
+        z_in  = q_left[2];
+		h_in  = q_left[3];
+		u_in  = q_left[4];
+		u_in = u_in*normals;
+	
+		w_out  = q_right[0];
+		uh_out = q_right[1];
+		uh_out = uh_out*normals;
+        z_out  = q_right[2];
+		h_out  = q_right[3];
+		u_out  = q_right[4];
+		u_out = u_out*normals;
+		
+		//printf("------------------ \n");
+		//printf("w_in  = %f \n", w_in);
+		//printf("uh_in = %f \n", uh_in);
+		//printf("z_in  = %f \n", z_in);
+		//printf("h_in  = %f \n", h_in);
+		//printf("u_in  = %f \n", u_in);
+		//printf("------------------ \n");
+		//printf("w_out  = %f \n", w_out);
+		//printf("uh_out = %f \n", uh_out);
+		//printf("z_out  = %f \n", z_out);
+		//printf("h_out  = %f \n", h_out);
+		//printf("u_out  = %f \n", u_out);	  
+		//////if (z_left-z_right != 0.0 ) printf("z_l - z_r = %f \n",z_left-z_right);
+		
+        
+		z_star = max(z_in, z_out);		              											//equation(7)  
+				   
+		// Compute speeds in x-direction.
+		h_in_star = max(0.0, w_in-z_star);														//equation(8)
+		
+		//if (h_in_star < epsilon) {
+		//	u_in = 0.0; h_in_star = 0.0;
+		//}
+		//else {
+		//	u_in = uh_in/h_in_star;
+		//}
+		//if (h_in_star < epsilon) {
+		//h_in_star = 0.0;
+		//}
+		
+		h_out_star = max(0.0, w_out-z_star);													//equation(9)
+
+		//if (h_out_star < epsilon) {
+		//	u_out = 0.0; h_out_star = 0.0; 
+		//}
+		//else {
+		//	u_out = uh_out/h_out_star;
+		//}
+  
+		//printf("u_left = %g u_right = %g \n",u_left, u_right);
+		soundspeed_in = sqrt(g*h_in_star);
+		soundspeed_out = sqrt(g*h_out_star);
+		
+		s_max = max(u_in+soundspeed_in, u_out+soundspeed_out);
+		if (s_max < 0.0) s_max = 0.0;
+	
+		s_min = min(u_in-soundspeed_in, u_out-soundspeed_out);
+		if (s_min > 0.0) s_min = 0.0;
+		
+		
+		// Flux formulas
+		flux_in[0] = u_in*h_in_star;
+		flux_in[1] = u_in*u_in*h_in_star + 0.5*g*h_in_star*h_in_star;
+
+		flux_out[0] = u_out*h_out_star;
+		flux_out[1] = u_out*u_out*h_out_star + 0.5*g*h_out_star*h_out_star;
+
+		// Flux computation
+		denom = s_max-s_min;
+		
+		//printf("Edge Mass Flux = %f \n", edgeflux[0]);
+		//printf("Edge Momentum Flux = %f \n", edgeflux[1]);
+		
+	    if (denom < epsilon && z_out > z_in) {
+			for (i=0; i<2; i++) edgeflux[i] = 0.0;
+			// Maximal wavespeed		
+			edgeflux[1] = edgeflux[1] + (0.5*g*h_in*h_in - 0.5*g*h_in_star*h_in_star );
+			edgeflux[1] *= normals;
+			*max_speed = 0.0;
+			//printf("Part 1 \n");
+		} else if (denom < epsilon) {
+			for (i=0; i<2; i++) edgeflux[i] = 0.0;
+			// Maximal wavespeed
+			*max_speed = 0.0;		
+			//printf("Part 2 \n");
+		//} else if (w_out < z_in) {
+		//	for (i=0; i<2; i++) edgeflux[i] = 0.0;
+		//	*max_speed = 0.0;
+		} else {
+			edgeflux[0] = s_max*flux_in[0] - s_min*flux_out[0];
+			edgeflux[0] += s_max*s_min*(h_out_star-h_in_star);                
+			edgeflux[0] /= denom;
+			edgeflux[1] = s_max*flux_in[1] - s_min*flux_out[1];
+			edgeflux[1] += s_max*s_min*(flux_out[0]-flux_in[0]);               
+			edgeflux[1] /= denom;
+			edgeflux[1] = edgeflux[1] + (0.5*g*h_in*h_in - 0.5*g*h_in_star*h_in_star);
+			edgeflux[1] *= normals;
+			// Maximal wavespeed
+			*max_speed = max(fabs(s_max), fabs(s_min));
+			//printf("Part 3 \n");
+		}  
+		//printf("Edge Mass Flux = %f \n", edgeflux[0]);
+		//printf("Edge Momentum Flux = %f \n", edgeflux[1]);
+
+    return 0;		
+	}
+		
+		
+	
+	
+// Computational function for flux computation
+double _compute_fluxes_ext_wellbalanced(double timestep,
+		double epsilon,
+		double g,
+		
+		long* neighbours,
+		long* neighbour_vertices,
+		double* normals,
+		double* areas,
+		
+		double* stage_edge_values,
+		double* xmom_edge_values,
+		double* bed_edge_values,
+		double* height_edge_values,
+		double* vel_edge_values,
+		
+		double* stage_boundary_values,
+		double* xmom_boundary_values,
+		double* bed_boundary_values,
+		double* height_boundary_values,
+		double* vel_boundary_values,
+		
+		double* stage_explicit_update,
+		double* xmom_explicit_update,
+		double* bed_explicit_update,
+		double* height_explicit_update,
+		double* vel_explicit_update,
+		
+		int number_of_elements,
+		double* max_speed_array) {
+		
+		double flux[2], ql[5], qr[5], edgeflux[2];
+		double max_speed, normal;
+		int k, i, ki, n, m, nm=0;
+		
+		for (k=0; k<number_of_elements; k++) {
+			flux[0] = 0.0;
+			flux[1] = 0.0;
+			
+			//printf("==================================== \n");
+			//printf("==================================== \n");
+			//printf("cell_number = %i \n",k);
+			
+			for (i=0; i<2; i++) {
+				
+				//printf("......................... \n");
+				//printf("interface = %i \n",i);
+				
+				ki = k*2+i;
+				
+				ql[0] = stage_edge_values[ki];
+				ql[1] = xmom_edge_values[ki];
+				ql[2] = bed_edge_values[ki];
+                ql[3] = height_edge_values[ki];
+				ql[4] = vel_edge_values[ki];
+                
+				n = neighbours[ki];
+				//printf("neighbours[ki] = %li \n",neighbours[ki]);
+				if (n<0) {
+					m = -n-1;
+					qr[0] = stage_boundary_values[m];
+					qr[1] = xmom_boundary_values[m];
+					qr[2] = ql[2];																			
+					qr[3] = height_edge_values[m]; 														
+					qr[4] = vel_edge_values[m];																
+                    
+				} else {
+					m = neighbour_vertices[ki];
+					nm = n*2+m;
+					qr[0] = stage_edge_values[nm];
+					qr[1] = xmom_edge_values[nm];
+					qr[2] = bed_edge_values[nm];
+					qr[3] = height_edge_values[nm];															
+					qr[4] = vel_edge_values[nm];															
+				}
+				
+				//Added condition!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+				//if (qr[0] < ql[2]) {
+				//ql[4] = 0.0;
+				//vel_edge_values[ki] = 0.0;
+				//}				
+				//if (qr[2] > ql[2]) {
+				//ql[1] = 0.0;
+				//ql[4] = 0.0;
+				//}
+				
+				normal = normals[ki];
+				_flux_function_wellbalanced(ql, qr, normal, g, epsilon, edgeflux, &max_speed);
+				flux[0] -= edgeflux[0];
+				flux[1] -= edgeflux[1];
+				
+				// Update timestep based on edge i and possibly neighbour n
+				if (max_speed > epsilon) {
+	                // Original CFL calculation
+					timestep = min(timestep, 0.5*areas[k]/max_speed); //Here, CFL=1.0 is assumed.
+					if (n>=0) {
+						timestep = min(timestep, 0.5*areas[n]/max_speed); //Here, CFL=1.0 is assumed. 
+					}
+				}
+            } // End edge i (and neighbour n)
+			flux[0] /= areas[k];
+			stage_explicit_update[k] = flux[0];
+			flux[1] /= areas[k];
+			xmom_explicit_update[k] = flux[1];
+			
+			//printf("......................... \n");
+			//printf("areas = %f \n", areas[k]);
+			//printf("Mass Flux in this cell = %f \n",flux[0]);
+			//printf("Momentum Flux in this cell = %f \n",flux[1]);
+			//printf("stage_explicit_update in this cell = %f \n",stage_explicit_update[k]);
+			//printf("xmom_explicit_update in this cell = %f \n",xmom_explicit_update[k]);
+			
+			
+			//Keep track of maximal speeds
+			max_speed_array[k]=max_speed;
+		}
+		
+		return timestep;	
+	}
+	
+	
+	
+
+
+
+//=========================================================================
+// Python Glue
+//=========================================================================
+PyObject *compute_fluxes_ext_wellbalanced(PyObject *self, PyObject *args) {
+  
+    PyArrayObject 
+	*neighbours, 
+	*neighbour_vertices,
+	*normals, 
+	*areas,
+	
+	*stage_edge_values,
+	*xmom_edge_values,
+	*bed_edge_values,
+	*height_edge_values,
+	*vel_edge_values,
+	
+	*stage_boundary_values,
+	*xmom_boundary_values,
+	*bed_boundary_values,
+	*height_boundary_values,
+	*vel_boundary_values,
+	
+	*stage_explicit_update,
+	*xmom_explicit_update,
+	*bed_explicit_update,
+	*height_explicit_update,
+	*vel_explicit_update,
+	
+	*max_speed_array;
+    
+  double timestep, epsilon, g;
+  int number_of_elements;
+    
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "dddOOOOOOOOOOOOOOOOOOOiO",
+			&timestep,
+			&epsilon,
+			&g,
+			
+			&neighbours,
+			&neighbour_vertices,
+			&normals,
+			&areas,
+			
+			&stage_edge_values,
+			&xmom_edge_values,
+			&bed_edge_values,
+			&height_edge_values,
+			&vel_edge_values,
+			
+			&stage_boundary_values,
+			&xmom_boundary_values,
+			&bed_boundary_values,
+			&height_boundary_values,
+			&vel_boundary_values,
+			
+			&stage_explicit_update,
+			&xmom_explicit_update,
+			&bed_explicit_update,
+			&height_explicit_update,
+			&vel_explicit_update,
+			
+			&number_of_elements,
+			&max_speed_array)) {
+    PyErr_SetString(PyExc_RuntimeError, "comp_flux_ext_wellbalanced.c: compute_fluxes_ext_wellbalanced could not parse input");
+    return NULL;
+  }
+
+ 
+  // Call underlying flux computation routine and update 
+  // the explicit update arrays 
+  timestep = _compute_fluxes_ext_wellbalanced(timestep,
+				 epsilon,
+				 g,
+				 
+				 (long*) neighbours -> data,
+				 (long*) neighbour_vertices -> data,
+				 (double*) normals -> data,
+				 (double*) areas -> data,
+				 
+				 (double*) stage_edge_values -> data,
+				 (double*) xmom_edge_values -> data,
+				 (double*) bed_edge_values -> data,
+				 (double*) height_edge_values -> data,
+				 (double*) vel_edge_values -> data,
+				 
+				 (double*) stage_boundary_values -> data,
+				 (double*) xmom_boundary_values -> data,
+				 (double*) bed_boundary_values -> data,
+				 (double*) height_boundary_values -> data,
+				 (double*) vel_boundary_values -> data,
+				 
+				 (double*) stage_explicit_update -> data,
+				 (double*) xmom_explicit_update -> data,
+				 (double*) bed_explicit_update -> data,
+				 (double*) height_explicit_update -> data,
+				 (double*) vel_explicit_update -> data,
+				 
+				 number_of_elements,
+				 (double*) max_speed_array -> data);
+
+  // Return updated flux timestep
+  return Py_BuildValue("d", timestep);
+}
+
+
+
+//-------------------------------
+// Method table for python module
+//-------------------------------
+
+static struct PyMethodDef MethodTable[] = {
+  {"compute_fluxes_ext_wellbalanced", compute_fluxes_ext_wellbalanced, METH_VARARGS, "Print out"},
+  {NULL, NULL}
+};
+
+// Module initialisation
+void initcomp_flux_ext_wellbalanced(void){
+  Py_InitModule("comp_flux_ext_wellbalanced", MethodTable);
+  import_array();
+}
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile.py	(revision 7906)
@@ -0,0 +1,440 @@
+"""compile.py - compile Python C-extension
+
+   Commandline usage: 
+     python compile.py <filename>
+
+   Usage from within Python:
+     import compile
+     compile.compile(<filename>,..)
+
+   Ole Nielsen, Duncan Gray Oct 2001      
+"""     
+
+# FIXME (Ole): Although this script says it works with a range of compilers,
+# it has only really been used with gcc.
+
+import os, string, sys, types
+
+separation_line = '---------------------------------------'      
+ 
+def compile(FNs=None, CC=None, LD = None, SFLAG = None, verbose = 1):
+  """compile(FNs=None, CC=None, LD = None, SFLAG = None):
+  
+     Compile FN(s) using compiler CC (e.g. mpicc), 
+     Loader LD and shared flag SFLAG.
+     If CC is absent use default compiler dependent on platform
+     if LD is absent CC is used.
+     if SFLAG is absent platform default is used
+     FNs can be either one filename or a list of filenames
+     In the latter case, the first will be used to name so file.
+  """
+  
+  # Input check
+  #
+  assert not FNs is None, 'No filename provided'
+
+  if not type(FNs) == types.ListType:
+    FNs = [FNs]
+
+
+  libext = 'so' #Default extension (Unix)
+  libs = ''
+  version = sys.version[:3]
+  
+  # Determine platform and compiler
+  #
+  if sys.platform == 'sunos5':  #Solaris
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'G'
+      
+  elif sys.platform == 'osf1V5':  #Compaq AlphaServer
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'    
+      
+  elif sys.platform == 'linux2':  #Linux
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'    
+      
+  elif sys.platform == 'darwin':  #Mac OS X:
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'bundle -flat_namespace -undefined suppress'
+
+  elif sys.platform == 'cygwin':  #Cygwin (compilation same as linux)
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'
+    libext = 'dll'
+    libs = '/lib/python%s/config/libpython%s.dll.a' %(version,version)
+      
+  elif sys.platform == 'win32':  #Windows
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc.exe' #Some systems require this (a security measure?) 
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'
+     
+    # As of python2.5, .pyd is the extension for python extension
+    # modules.
+    if sys.version_info[0:2] >= (2, 5):
+      libext = 'pyd'
+    else:
+      libext = 'dll'
+
+    libs, is_found = set_python_dll_path()
+      
+  else:
+    if verbose: print "Unrecognised platform %s - revert to default"\
+                %sys.platform
+    
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = 'ld'
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'G'
+
+
+  # Verify that compiler can be executed
+  print 'Compiler: %s, version ' %compiler,
+  sys.stdout.flush()
+  s = '%s -dumpversion' %(compiler)
+  err = os.system(s)
+  print
+  
+  if err != 0:
+      msg = 'Unable to execute compiler: %s. ' %compiler
+      msg += 'Make sure it is available on the system path.\n'
+      msg += 'One way to check this is to run %s on ' %compiler
+      msg += 'the commandline.'
+      raise Exception, msg    
+
+  
+  # Find location of include files
+  #
+  if sys.platform == 'win32':  #Windows
+    python_include = os.path.join(sys.exec_prefix, 'include')    
+  else:  
+    python_include = os.path.join(os.path.join(sys.exec_prefix, 'include'),
+                                  'python' + version)
+
+  # Check existence of Python.h
+  #
+  headerfile = python_include + os.sep + 'Python.h'
+  try:
+    open(headerfile, 'r')
+  except:
+    raise """Did not find Python header file %s.
+    Make sure files for Python C-extensions are installed. 
+    In debian linux, for example, you need to install a
+    package called something like python2.3-dev""" %headerfile
+
+
+
+  # Add Python path + utilities to includelist (see ticket:31)
+  # Assume there is only one 'utilities' dir under path dirs
+  
+  utilities_include_dir = None
+  for pathdir in sys.path:
+
+    utilities_include_dir = pathdir + os.sep + 'utilities'
+    #print pathdir
+    #print utilities_include_dir
+    try:
+      os.stat(utilities_include_dir)
+    except OSError:
+      pass
+    else:
+      #print 'Found %s to be used as include dir' %utilities_include_dir
+      break
+
+  # This is hacky since it
+  # assumes the location of the compile_all that determines buildroot
+  try:
+    utilities_include_dir = buildroot + os.sep + "source" + os.sep + "anuga" \
+                            + os.sep + 'utilities'
+  except:
+    # This will make compile work locally
+    utilities_include_dir = '.'
+    utilities_include_dir = '../utilities'
+
+
+    
+  try:
+    os.stat(utilities_include_dir)
+  except OSError: 
+    utilities_include_dir = buildroot + os.sep + 'utilities'
+  
+  
+  
+  # Check filename(s)
+  #
+  object_files = ''
+  for FN in FNs:        
+    root, ext = os.path.splitext(FN)
+    if ext == '':
+      FN = FN + '.c'
+    elif ext.lower() != '.c':
+      raise Exception, "Unrecognised extension: " + FN
+    
+    try:
+      open(FN, 'r')
+    except:
+      raise Exception, "Could not open: " + FN
+
+    if not object_files: root1 = root  #Remember first filename        
+    object_files += root + '.o '  
+  
+  
+    # Compile
+    #
+    if utilities_include_dir is None:    
+      s = '%s -c %s -I"%s" -o "%s.o" -Wall -O3'\
+          %(compiler, FN, python_include, root)
+    else:
+      if FN == "triangle.c" or FN == "mesh_engine_c_layer.c":
+        s = '%s -c %s -I"%s" -I"%s" -o "%s.o" -O3 -DTRILIBRARY=1 -DNO_TIMER=1'\
+            %(compiler, FN, python_include, utilities_include_dir, root)
+      else:
+        s = '%s -c %s -I"%s" -I"%s" -o "%s.o" -Wall -O3'\
+            %(compiler, FN, python_include, utilities_include_dir, root)
+
+    if os.name == 'posix' and os.uname()[4] == 'x86_64':
+      #Extra flags for 64 bit architectures
+      #Second clause will always fail on Win32 because uname is UNIX specific
+      #but won't get past first clause
+
+      #FIXME: Which one?
+      #s += ' -fPIC'
+      s += ' -fPIC -m64' 
+      
+      
+    if verbose:
+      print s
+
+    # Doesn't work on Windows anyway  
+    #else:
+    #  s = s + ' 2> /dev/null' #Suppress errors
+    
+    try:
+      err = os.system(s)
+      if err != 0:
+          raise 'Attempting to compile %s failed - please try manually' %FN 
+    except:
+      raise 'Could not compile %s - please try manually' %FN  
+
+  
+  # Make shared library (*.so or *.dll)
+  if libs is "":
+    s = '%s -%s %s -o %s.%s -lm' %(loader, sharedflag, object_files, root1, libext)
+  else:
+    s = '%s -%s %s -o %s.%s "%s" -lm' %(loader, sharedflag, object_files, root1, libext, libs)
+    
+  if verbose:
+    print s
+
+  # Doesn't work on Windows anyway      
+  #else:
+  #  s = s + ' 2> /dev/null' #Suppress warnings
+  
+  try:  
+    err=os.system(s)
+    if err != 0:        
+        raise 'Attempting to link %s failed - please try manually' %root1     
+  except:
+    raise 'Could not link %s - please try manually' %root1
+    
+
+def can_use_C_extension(filename):
+    """Determine whether specified C-extension
+    can and should be used.
+    """
+
+    from anuga.config import use_extensions
+
+    from os.path import splitext
+
+    root, ext = splitext(filename)
+    
+    C=False
+    if use_extensions:
+        try:
+            s = 'import %s' %root
+            #print s
+            exec(s)
+        except:
+            try:
+                open(filename)
+            except:
+                msg = 'C extension %s cannot be opened' %filename
+                print msg                
+            else:    
+                print '------- Trying to compile c-extension %s' %filename
+            
+                try:
+                    compile(filename)
+                except:
+                    print 'WARNING: Could not compile C-extension %s'\
+                          %filename
+                else:
+                    try:
+                        exec('import %s' %root)
+                    except:
+                        msg = 'C extension %s seems to compile OK, '
+                        msg += 'but it can still not be imported.'
+                        raise msg
+                    else:
+                        C=True
+        else:
+            C=True
+            
+    if not C:
+        pass
+        print 'NOTICE: C-extension %s not used' %filename
+
+    return C
+
+
+def set_python_dll_path():
+  """ On windows, find which of the two usual hiding places the python
+  dll is located.
+
+  If the file can't be found, return None.
+  """
+  import sys
+  from os import access, F_OK
+  
+  version = sys.version[:3]
+  v = version.replace('.','')
+  dllfilename = 'python%s.dll' %(v)
+  libs = os.path.join(sys.exec_prefix,dllfilename)
+
+  is_found = True   
+  if access(libs,F_OK) == 0 :
+    # Sometimes python dll is hidden in %WINDIR%/system32
+    libs = os.path.join(os.environ.get('WINDIR', 'C:\WINNT'), 'system32',
+                        dllfilename)
+    if access(libs,F_OK) == 0 :
+      # could not find the dll
+      libs = os.path.join(sys.exec_prefix,dllfilename)
+      is_found = False
+  return libs, is_found
+
+def check_python_dll():
+  libs, is_found = set_python_dll_path()
+  if not is_found:
+    print "%s not found.\nPlease install.\nIt is available on the web." \
+              %(libs)
+    import sys; sys.exit()
+    
+      
+if __name__ == '__main__':
+  from os.path import splitext
+  
+  if sys.platform == 'win32':
+    check_python_dll()
+  if len(sys.argv) > 1:
+      files = sys.argv[1:]
+      for filename in files:
+          root, ext = splitext(filename)
+
+          if ext <> '.c':
+              print 'WARNING (compile.py): Skipping %s. I only compile C-files.' %filename
+      
+  else:  
+      #path = os.path.split(sys.argv[0])[0] or os.getcwd()
+      path = '.'
+      files = os.listdir(path)
+      
+      
+
+  for filename in files:
+      root, ext = splitext(filename)
+
+      if ext == '.c':
+          for x in ['.dll', '.so']:
+              try:
+                  os.remove(root + x)
+              except:
+                  pass
+
+          print separation_line
+          print 'Trying to compile c-extension %s in %s'\
+                %(filename, os.getcwd())
+          try:
+            if filename == 'triang.c': 
+              compile(['triang.c','triangle.c'])
+            elif  filename == 'mesh_engine_c_layer.c': 
+              compile(['mesh_engine_c_layer.c','triangle.c'])
+            else:
+              compile(filename)
+          except Exception, e:
+              msg = 'Could not compile C extension %s\n' %filename
+              msg += str(e)
+              raise Exception, msg
+          else:
+              print 'C extension %s OK' %filename
+          print    
+        
+
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_all.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_all.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_all.py	(revision 7906)
@@ -0,0 +1,17 @@
+import os
+
+buildroot = os.getcwd()
+
+#Attempt to compile all extensions
+
+##anuga_dir = '..' + os.sep + '..' + os.sep + '..' + os.sep + '..' + os.sep + '..'
+##utilities_dir = anuga_dir + os.sep + 'anuga_core' + os.sep + 'source' + os.sep + 'anuga' + os.sep + 'utilities'
+
+##execfile( utilities_dir + os.sep + 'compile.py')
+execfile( buildroot + os.sep + 'compile_using_numpy.py')
+
+
+
+os.chdir(buildroot)    
+
+    
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_using_Numeric.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_using_Numeric.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_using_Numeric.py	(revision 7906)
@@ -0,0 +1,446 @@
+"""compile.py - compile Python C-extension
+
+   Commandline usage: 
+     python compile.py <filename>
+
+   Usage from within Python:
+     import compile
+     compile.compile(<filename>,..)
+
+   Ole Nielsen, Duncan Gray Oct 2001      
+"""     
+
+# FIXME (Ole): Although this script says it works with a range of compilers,
+# it has only really been used with gcc.
+
+import os, string, sys, types
+
+separation_line = '---------------------------------------'      
+ 
+def compile(FNs=None, CC=None, LD = None, SFLAG = None, verbose = 1):
+  """compile(FNs=None, CC=None, LD = None, SFLAG = None):
+  
+     Compile FN(s) using compiler CC (e.g. mpicc), 
+     Loader LD and shared flag SFLAG.
+     If CC is absent use default compiler dependent on platform
+     if LD is absent CC is used.
+     if SFLAG is absent platform default is used
+     FNs can be either one filename or a list of filenames
+     In the latter case, the first will be used to name so file.
+  """
+  
+  # Input check
+  #
+  assert not FNs is None, 'No filename provided'
+
+  if not type(FNs) == types.ListType:
+    FNs = [FNs]
+
+
+  libext = 'so' #Default extension (Unix)
+  libs = ''
+  version = sys.version[:3]
+  
+  # Determine platform and compiler
+  #
+  if sys.platform == 'sunos5':  #Solaris
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'G'
+      
+  elif sys.platform == 'osf1V5':  #Compaq AlphaServer
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'    
+      
+  elif sys.platform == 'linux2':  #Linux
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'    
+      
+  elif sys.platform == 'darwin':  #Mac OS X:
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'bundle -flat_namespace -undefined suppress'
+
+  elif sys.platform == 'cygwin':  #Cygwin (compilation same as linux)
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'
+    libext = 'dll'
+    libs = '/lib/python%s/config/libpython%s.dll.a' %(version,version)
+      
+  elif sys.platform == 'win32':  #Windows
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc.exe' #Some systems require this (a security measure?) 
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'
+     
+    # As of python2.5, .pyd is the extension for python extension
+    # modules.
+    if sys.version_info[0:2] >= (2, 5):
+      libext = 'pyd'
+    else:
+      libext = 'dll'
+
+    libs, is_found = set_python_dll_path()
+      
+  else:
+    if verbose: print "Unrecognised platform %s - revert to default"\
+                %sys.platform
+    
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = 'ld'
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'G'
+
+
+  # Verify that compiler can be executed
+  print 'Compiler: %s, version ' %compiler,
+  sys.stdout.flush()
+  s = '%s -dumpversion' %(compiler)
+  err = os.system(s)
+  print
+  
+  if err != 0:
+      msg = 'Unable to execute compiler: %s. ' %compiler
+      msg += 'Make sure it is available on the system path.\n'
+      msg += 'One way to check this is to run %s on ' %compiler
+      msg += 'the commandline.'
+      raise Exception, msg    
+
+  
+  # Find location of include files
+  #
+  if sys.platform == 'win32':  #Windows
+    python_include = os.path.join(sys.exec_prefix, 'include')    
+  else:  
+    python_include = os.path.join(os.path.join(sys.exec_prefix, 'include'),
+                                  'python' + version)
+
+  # Check existence of Python.h
+  #
+  headerfile = python_include + os.sep + 'Python.h'
+  try:
+    open(headerfile, 'r')
+  except:
+    raise """Did not find Python header file %s.
+    Make sure files for Python C-extensions are installed. 
+    In debian linux, for example, you need to install a
+    package called something like python2.3-dev""" %headerfile
+
+
+
+  # Add Python path + utilities to includelist (see ticket:31)
+  # Assume there is only one 'utilities' dir under path dirs
+  
+  utilities_include_dir = None
+  for pathdir in sys.path:
+
+    utilities_include_dir = pathdir + os.sep + 'utilities'
+    #print pathdir
+    #print utilities_include_dir
+    try:
+      os.stat(utilities_include_dir)
+    except OSError:
+      pass
+    else:
+      #print 'Found %s to be used as include dir' %utilities_include_dir
+      break
+
+  # This is hacky since it
+  # assumes the location of the compile_all that determines buildroot
+  try:
+    utilities_include_dir = buildroot + os.sep + "source" + os.sep + "anuga" \
+                            + os.sep + 'utilities'
+  except:
+    # This will make compile work locally
+    utilities_include_dir = '.'
+    utilities_include_dir = '../utilities'
+
+
+    
+  try:
+    os.stat(utilities_include_dir)
+  except OSError: 
+    utilities_include_dir = buildroot + os.sep + 'utilities'
+  
+  
+  
+  # Check filename(s)
+  #
+  object_files = ''
+  for FN in FNs:        
+    root, ext = os.path.splitext(FN)
+    if ext == '':
+      FN = FN + '.c'
+    elif ext.lower() != '.c':
+      raise Exception, "Unrecognised extension: " + FN
+    
+    try:
+      open(FN, 'r')
+    except:
+      raise Exception, "Could not open: " + FN
+
+    if not object_files: root1 = root  #Remember first filename        
+    object_files += root + '.o '  
+  
+  
+    # Compile
+    #
+    if utilities_include_dir is None:    
+      s = '%s -c %s -I"%s" -o "%s.o" -Wall -O3'\
+          %(compiler, FN, python_include, root)
+    else:
+      if FN == "triangle.c" or FN == "mesh_engine_c_layer.c":
+        s = '%s -c %s -I"%s" -I"%s" -o "%s.o" -O3 -DTRILIBRARY=1 -DNO_TIMER=1'\
+            %(compiler, FN, python_include, utilities_include_dir, root)
+      elif FN == "polygon_ext.c":
+        # gcc 4.3.x is problematic with this file if '-O3' is used
+        s = '%s -c %s -I"%s" -I"%s" -o "%s.o" -Wall'\
+            %(compiler, FN, python_include, utilities_include_dir, root)
+      else:
+        s = '%s -c %s -I"%s" -I"%s" -o "%s.o" -Wall -O3'\
+            %(compiler, FN, python_include, utilities_include_dir, root)
+
+    if os.name == 'posix' and os.uname()[4] in ['x86_64', 'ia64']:
+      # Extra flags for 64 bit architectures.
+      #   AMD Opteron will give x86_64
+      #   Itanium will give ia64
+      #
+      # Second clause will always fail on Win32 because uname is UNIX specific
+      # but won't get past first clause
+
+      s += ' -fPIC' # Use position independent code for 64 bit archs
+      #s += ' -m64' # Used to be necessary for AMD Opteron
+      
+      
+    if verbose:
+      print s
+
+    # Doesn't work on Windows anyway  
+    #else:
+    #  s = s + ' 2> /dev/null' #Suppress errors
+    
+    try:
+      err = os.system(s)
+      if err != 0:
+          raise 'Attempting to compile %s failed - please try manually' %FN 
+    except:
+      raise 'Could not compile %s - please try manually' %FN  
+
+  
+  # Make shared library (*.so or *.dll)
+  if libs is "":
+    s = '%s -%s %s -o %s.%s -lm' %(loader, sharedflag, object_files, root1, libext)
+  else:
+    s = '%s -%s %s -o %s.%s "%s" -lm' %(loader, sharedflag, object_files, root1, libext, libs)
+    
+  if verbose:
+    print s
+
+  # Doesn't work on Windows anyway      
+  #else:
+  #  s = s + ' 2> /dev/null' #Suppress warnings
+  
+  try:  
+    err=os.system(s)
+    if err != 0:        
+        raise 'Attempting to link %s failed - please try manually' %root1     
+  except:
+    raise 'Could not link %s - please try manually' %root1
+    
+
+def can_use_C_extension(filename):
+    """Determine whether specified C-extension
+    can and should be used.
+    """
+
+    from anuga.config import use_extensions
+
+    from os.path import splitext
+
+    root, ext = splitext(filename)
+    
+    C=False
+    if use_extensions:
+        try:
+            s = 'import %s' %root
+            #print s
+            exec(s)
+        except:
+            try:
+                open(filename)
+            except:
+                msg = 'C extension %s cannot be opened' %filename
+                print msg                
+            else:    
+                print '------- Trying to compile c-extension %s' %filename
+            
+                try:
+                    compile(filename)
+                except:
+                    print 'WARNING: Could not compile C-extension %s'\
+                          %filename
+                else:
+                    try:
+                        exec('import %s' %root)
+                    except:
+                        msg = 'C extension %s seems to compile OK, '
+                        msg += 'but it can still not be imported.'
+                        raise msg
+                    else:
+                        C=True
+        else:
+            C=True
+            
+    if not C:
+        pass
+        print 'NOTICE: C-extension %s not used' %filename
+
+    return C
+
+
+def set_python_dll_path():
+  """ On windows, find which of the two usual hiding places the python
+  dll is located.
+
+  If the file can't be found, return None.
+  """
+  import sys
+  from os import access, F_OK
+  
+  version = sys.version[:3]
+  v = version.replace('.','')
+  dllfilename = 'python%s.dll' %(v)
+  libs = os.path.join(sys.exec_prefix,dllfilename)
+
+  is_found = True   
+  if access(libs,F_OK) == 0 :
+    # Sometimes python dll is hidden in %WINDIR%/system32
+    libs = os.path.join(os.environ.get('WINDIR', 'C:\WINNT'), 'system32',
+                        dllfilename)
+    if access(libs,F_OK) == 0 :
+      # could not find the dll
+      libs = os.path.join(sys.exec_prefix,dllfilename)
+      is_found = False
+  return libs, is_found
+
+def check_python_dll():
+  libs, is_found = set_python_dll_path()
+  if not is_found:
+    print "%s not found.\nPlease install.\nIt is available on the web." \
+              %(libs)
+    import sys; sys.exit()
+    
+      
+if __name__ == '__main__':
+  from os.path import splitext
+  
+  if sys.platform == 'win32':
+    check_python_dll()
+  if len(sys.argv) > 1:
+      files = sys.argv[1:]
+      for filename in files:
+          root, ext = splitext(filename)
+
+          if ext <> '.c':
+              print 'WARNING (compile.py): Skipping %s. I only compile C-files.' %filename
+      
+  else:  
+      #path = os.path.split(sys.argv[0])[0] or os.getcwd()
+      path = '.'
+      files = os.listdir(path)
+      
+      
+
+  for filename in files:
+      root, ext = splitext(filename)
+
+      if ext == '.c':
+          for x in ['.dll', '.so']:
+              try:
+                  os.remove(root + x)
+              except:
+                  pass
+
+          print separation_line
+          print 'Trying to compile c-extension %s in %s'\
+                %(filename, os.getcwd())
+          try:
+            if filename == 'triang.c': 
+              compile(['triang.c','triangle.c'])
+            elif  filename == 'mesh_engine_c_layer.c': 
+              compile(['mesh_engine_c_layer.c','triangle.c'])
+            else:
+              compile(filename)
+          except Exception, e:
+              msg = 'Could not compile C extension %s\n' %filename
+              msg += str(e)
+              raise Exception, msg
+          else:
+              print 'C extension %s OK' %filename
+          print    
+        
+
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_using_numpy.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_using_numpy.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/compile_using_numpy.py	(revision 7906)
@@ -0,0 +1,453 @@
+"""compile.py - compile Python C-extension
+
+   Commandline usage: 
+     python compile.py <filename>
+
+   Usage from within Python:
+     import compile
+     compile.compile(<filename>,..)
+
+   Ole Nielsen, Duncan Gray Oct 2001      
+"""     
+
+#NumPy ------------------------------------
+# Something like these lines recommended in "Converting from NUMARRAY to NUMPY"
+import numpy
+I_dirs = '-I"%s" ' % numpy.get_include()
+#NumPy ------------------------------------
+
+# FIXME (Ole): Although this script says it works with a range of compilers,
+# it has only really been used with gcc.
+
+import os, string, sys, types
+
+separation_line = '---------------------------------------'      
+ 
+def compile(FNs=None, CC=None, LD = None, SFLAG = None, verbose = 1):
+  """compile(FNs=None, CC=None, LD = None, SFLAG = None):
+  
+     Compile FN(s) using compiler CC (e.g. mpicc), 
+     Loader LD and shared flag SFLAG.
+     If CC is absent use default compiler dependent on platform
+     if LD is absent CC is used.
+     if SFLAG is absent platform default is used
+     FNs can be either one filename or a list of filenames
+     In the latter case, the first will be used to name so file.
+  """
+  
+  # Input check
+  #
+  assert not FNs is None, 'No filename provided'
+
+  if not type(FNs) == types.ListType:
+    FNs = [FNs]
+
+
+  libext = 'so' #Default extension (Unix)
+  libs = ''
+  version = sys.version[:3]
+  
+  # Determine platform and compiler
+  #
+  if sys.platform == 'sunos5':  #Solaris
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'G'
+      
+  elif sys.platform == 'osf1V5':  #Compaq AlphaServer
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'    
+      
+  elif sys.platform == 'linux2':  #Linux
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'    
+      
+  elif sys.platform == 'darwin':  #Mac OS X:
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'bundle -flat_namespace -undefined suppress'
+
+  elif sys.platform == 'cygwin':  #Cygwin (compilation same as linux)
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'
+    libext = 'dll'
+    libs = '/lib/python%s/config/libpython%s.dll.a' %(version,version)
+      
+  elif sys.platform == 'win32':  #Windows
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc.exe' #Some systems require this (a security measure?) 
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'
+     
+    # As of python2.5, .pyd is the extension for python extension
+    # modules.
+    if sys.version_info[0:2] >= (2, 5):
+      libext = 'pyd'
+    else:
+      libext = 'dll'
+
+    libs, is_found = set_python_dll_path()
+      
+  else:
+    if verbose: print "Unrecognised platform %s - revert to default"\
+                %sys.platform
+    
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = 'ld'
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'G'
+
+
+  # Verify that compiler can be executed
+  print 'Compiler: %s, version ' %compiler,
+  sys.stdout.flush()
+  s = '%s -dumpversion' %(compiler)
+  err = os.system(s)
+  print
+  
+  if err != 0:
+      msg = 'Unable to execute compiler: %s. ' %compiler
+      msg += 'Make sure it is available on the system path.\n'
+      msg += 'One way to check this is to run %s on ' %compiler
+      msg += 'the commandline.'
+      raise Exception, msg    
+
+  
+  # Find location of include files
+  #
+  if sys.platform == 'win32':  #Windows
+    python_include = os.path.join(sys.exec_prefix, 'include')    
+  else:  
+    python_include = os.path.join(os.path.join(sys.exec_prefix, 'include'),
+                                  'python' + version)
+
+  # Check existence of Python.h
+  #
+  headerfile = python_include + os.sep + 'Python.h'
+  try:
+    open(headerfile, 'r')
+  except:
+    raise """Did not find Python header file %s.
+    Make sure files for Python C-extensions are installed. 
+    In debian linux, for example, you need to install a
+    package called something like python2.3-dev""" %headerfile
+
+
+
+  # Add Python path + utilities to includelist (see ticket:31)
+  # Assume there is only one 'utilities' dir under path dirs
+  
+  utilities_include_dir = None
+  for pathdir in sys.path:
+
+    utilities_include_dir = pathdir + os.sep + 'utilities'
+    #print pathdir
+    #print utilities_include_dir
+    try:
+      os.stat(utilities_include_dir)
+    except OSError:
+      pass
+    else:
+      #print 'Found %s to be used as include dir' %utilities_include_dir
+      break
+
+  # This is hacky since it
+  # assumes the location of the compile_all that determines buildroot
+  try:
+    utilities_include_dir = buildroot + os.sep + "source" + os.sep + "anuga" \
+                            + os.sep + 'utilities'
+  except:
+    # This will make compile work locally
+    utilities_include_dir = '.'
+    utilities_include_dir = '../utilities'
+
+
+    
+  try:
+    os.stat(utilities_include_dir)
+  except OSError: 
+    utilities_include_dir = buildroot + os.sep + 'utilities'
+  
+  
+  
+  # Check filename(s)
+  #
+  object_files = ''
+  for FN in FNs:        
+    root, ext = os.path.splitext(FN)
+    if ext == '':
+      FN = FN + '.c'
+    elif ext.lower() != '.c':
+      raise Exception, "Unrecognised extension: " + FN
+    
+    try:
+      open(FN, 'r')
+    except:
+      raise Exception, "Could not open: " + FN
+
+    if not object_files: root1 = root  #Remember first filename        
+    object_files += root + '.o '  
+  
+  
+    # Compile
+    #
+    if utilities_include_dir is None:    
+      s = '%s -c %s -I"%s" -o "%s.o" -Wall -O3'\
+          %(compiler, FN, python_include, root)
+    else:
+      if FN == "triangle.c" or FN == "mesh_engine_c_layer.c":
+        s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -O3 -DTRILIBRARY=1 -DNO_TIMER=1'\
+            % (compiler, FN, I_dirs, python_include, utilities_include_dir, root)
+      elif FN == "polygon_ext.c":
+        # gcc 4.3.x is problematic with this file if '-O3' is used
+        s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -Wall'\
+            %(compiler, FN, I_dirs, python_include, utilities_include_dir, root)
+      else:
+        s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -Wall -O3'\
+            %(compiler, FN, I_dirs, python_include, utilities_include_dir, root)
+
+    if os.name == 'posix' and os.uname()[4] in ['x86_64', 'ia64']:
+      # Extra flags for 64 bit architectures.
+      #   AMD Opteron will give x86_64
+      #   Itanium will give ia64
+      #
+      # Second clause will always fail on Win32 because uname is UNIX specific
+      # but won't get past first clause
+
+      s += ' -fPIC' # Use position independent code for 64 bit archs
+      #s += ' -m64' # Used to be necessary for AMD Opteron
+      
+      
+    if verbose:
+      print s
+
+    # Doesn't work on Windows anyway  
+    #else:
+    #  s = s + ' 2> /dev/null' #Suppress errors
+    
+    try:
+      err = os.system(s)
+      if err != 0:
+          raise 'Attempting to compile %s failed - please try manually' %FN 
+    except:
+      raise 'Could not compile %s - please try manually' %FN  
+
+  
+  # Make shared library (*.so or *.dll)
+  if libs is "":
+    s = '%s -%s %s -o %s.%s -lm' %(loader, sharedflag, object_files, root1, libext)
+  else:
+    s = '%s -%s %s -o %s.%s "%s" -lm' %(loader, sharedflag, object_files, root1, libext, libs)
+    
+  if verbose:
+    print s
+
+  # Doesn't work on Windows anyway      
+  #else:
+  #  s = s + ' 2> /dev/null' #Suppress warnings
+  
+  try:  
+    err=os.system(s)
+    if err != 0:        
+        raise 'Attempting to link %s failed - please try manually' %root1     
+  except:
+    raise 'Could not link %s - please try manually' %root1
+    
+
+def can_use_C_extension(filename):
+    """Determine whether specified C-extension
+    can and should be used.
+    """
+
+    #from anuga.config import use_extensions
+    use_extensions = True
+
+    from os.path import splitext
+
+    root, ext = splitext(filename)
+    
+    C=False
+    if use_extensions:
+        try:
+            s = 'import %s' %root
+            #print s
+            exec(s)
+        except:
+            try:
+                open(filename)
+            except:
+                msg = 'C extension %s cannot be opened' %filename
+                print msg                
+            else:    
+                print '------- Trying to compile c-extension %s' %filename
+            
+                try:
+                    compile(filename)
+                except:
+                    print 'WARNING: Could not compile C-extension %s'\
+                          %filename
+                else:
+                    try:
+                        exec('import %s' %root)
+                    except:
+                        msg = 'C extension %s seems to compile OK, '
+                        msg += 'but it can still not be imported.'
+                        raise msg
+                    else:
+                        C=True
+        else:
+            C=True
+            
+    if not C:
+        pass
+        print 'NOTICE: C-extension %s not used' %filename
+
+    return C
+
+
+def set_python_dll_path():
+  """ On windows, find which of the two usual hiding places the python
+  dll is located.
+
+  If the file can't be found, return None.
+  """
+  import sys
+  from os import access, F_OK
+  
+  version = sys.version[:3]
+  v = version.replace('.','')
+  dllfilename = 'python%s.dll' %(v)
+  libs = os.path.join(sys.exec_prefix,dllfilename)
+
+  is_found = True   
+  if access(libs,F_OK) == 0 :
+    # Sometimes python dll is hidden in %WINDIR%/system32
+    libs = os.path.join(os.environ.get('WINDIR', 'C:\WINNT'), 'system32',
+                        dllfilename)
+    if access(libs,F_OK) == 0 :
+      # could not find the dll
+      libs = os.path.join(sys.exec_prefix,dllfilename)
+      is_found = False
+  return libs, is_found
+
+def check_python_dll():
+  libs, is_found = set_python_dll_path()
+  if not is_found:
+    print "%s not found.\nPlease install.\nIt is available on the web." \
+              %(libs)
+    import sys; sys.exit()
+    
+      
+if __name__ == '__main__':
+  from os.path import splitext
+  
+  if sys.platform == 'win32':
+    check_python_dll()
+  if len(sys.argv) > 1:
+      files = sys.argv[1:]
+      for filename in files:
+          root, ext = splitext(filename)
+
+          if ext <> '.c':
+              print 'WARNING (compile.py): Skipping %s. I only compile C-files.' %filename
+      
+  else:  
+      #path = os.path.split(sys.argv[0])[0] or os.getcwd()
+      path = '.'
+      files = os.listdir(path)
+      
+      
+
+  for filename in files:
+      root, ext = splitext(filename)
+
+      if ext == '.c':
+          for x in ['.dll', '.so']:
+              try:
+                  os.remove(root + x)
+              except:
+                  pass
+
+          print separation_line
+          print 'Trying to compile c-extension %s in %s'\
+                %(filename, os.getcwd())
+          try:
+            if filename == 'triang.c': 
+              compile(['triang.c','triangle.c'])
+            elif  filename == 'mesh_engine_c_layer.c': 
+              compile(['mesh_engine_c_layer.c','triangle.c'])
+            else:
+              compile(filename)
+          except Exception, e:
+              msg = 'Could not compile C extension %s\n' %filename
+              msg += str(e)
+              raise Exception, msg
+          else:
+              print 'C extension %s OK' %filename
+          print    
+        
+
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/config.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/config.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/config.py	(revision 7906)
@@ -0,0 +1,112 @@
+"""Module where global model parameters are set for anuga_1d
+"""
+
+epsilon = 1.0e-12#6#12
+h0 = 1.0e-16#12
+
+default_boundary_tag = 'exterior'
+
+
+time_format = '%d/%m/%y %H:%M:%S'
+
+min_timestep = 1.0e-6 #Should be computed based on geometry
+max_timestep = 1.0e3
+max_smallsteps = 50  # Max number of degenerate steps allowed b4 trying first order
+#This is how:
+#Define maximal possible speed in open water v_max, e.g. 500m/s (soundspeed?)
+#Then work out minimal internal distance in mesh r_min and set
+#min_timestep = r_min/v_max
+#
+#Max speeds are calculated in the flux function as
+#
+#lambda = v +/- sqrt(gh)
+#
+# so with 500 m/s, h ~ 500^2/g = 2500 m well out of the domain of the
+# shallow water wave equation
+#
+#The actual soundspeed can be as high as 1530m/s
+#(see http://staff.washington.edu/aganse/public.projects/clustering/clustering.html),
+#but that would only happen with h>225000m in this equation. Why ?
+#The maximal speed we specify is really related to the max speed
+#of surface pertubation
+#
+
+
+v_max = 100 #For use in domain_ext.c
+sound_speed = 500
+
+
+max_smallsteps = 50  #Max number of degenerate steps allowed b4 trying first order
+
+manning = 0.0  #Manning's friction coefficient
+g = 9.81       #Gravity
+#g(phi) = 9780313 * (1 + 0.0053024 sin(phi)**2 - 0.000 0059 sin(2*phi)**2) micro m/s**2, where phi is the latitude
+#The 'official' average is 9.80665
+
+
+
+
+eta_w = 3.0e-3 #Wind stress coefficient
+rho_a = 1.2e-3 #Atmospheric density
+rho_w = 1023   #Fluid density [kg/m^3] (rho_w = 1023 for salt water)
+
+
+#Betas [0;1] control the allowed steepness of gradient for second order
+#extrapolations. Values of 1 allow the steepes gradients while
+#lower values are more conservative. Values of 0 correspond to
+#1'st order extrapolations.
+#
+# Large values of beta_h may cause simulations to require more timesteps
+# as surface will 'hug' closer to the bed.
+# Small values of beta_h will make code faster, but one may experience
+# artificial momenta caused by discontinuities in water depths in
+# the presence of steep slopes. One example of this would be
+# stationary water 'lapping' upwards to a higher point on the coast.
+#
+#
+#
+#There are separate betas for the w-limiter and the h-limiter
+#
+#
+#
+#
+#Good values are:
+#beta_w = 0.9
+#beta_h = 0.2
+
+
+
+beta_w = 1.5
+beta_h = 0.2
+timestepping_method = 'euler'
+
+CFL = 1.0  #FIXME (ole): Is this in use yet??
+           #(Steve) yes, change domain.CFL to
+           #make changes
+
+
+pmesh_filename = '.\\pmesh'
+
+
+import os, sys
+
+if sys.platform == 'win32':
+    #default_datadir = 'C:\grohm_output'
+    default_datadir = '.'
+else:
+    #default_datadir = os.path.expanduser('~'+os.sep+'grohm_output')
+    default_datadir = '.'
+
+
+use_extensions = True    #Try to use C-extensions
+#use_extensions = False   #Do not use C-extensions
+
+use_psyco = True  #Use psyco optimisations
+#use_psyco = False  #Do not use psyco optimisations
+
+
+optimised_gradient_limiter = True #Use hardwired gradient limiter
+
+#Specific to shallow water W.E.
+minimum_allowed_height = 1.0e-6 #1.0e-6 #Water depth below which it is considered to be 0
+maximum_allowed_speed = 1000.0
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/dam_h_2sides_RUN.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/dam_h_2sides_RUN.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/dam_h_2sides_RUN.py	(revision 7906)
@@ -0,0 +1,117 @@
+import os
+from math import sqrt
+from sww_domain_shm import *
+from Numeric import Float
+from numpy import zeros
+#from analytic_dam_sudi import AnalyticDam
+#Note:apply analytical_sol given in debris avalanche solution
+from parameters import *
+
+N = int(N) # number of cells
+print "number of cells=",N
+#analytical_sol=AnalyticDam(h_0,h_1)
+boundary = {(0,0):'left', (N-1,1): 'right'}
+domain = Domain(points,boundary)
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.cfl = 1.0
+domain.limiter = "minmod"
+
+def stage(x):
+    y=zeros(len(x), Float)
+    for i in range (len(x)):
+        if x[i]<=L/4.0:
+            y[i]=bed_slope*x[i]#0.0
+        elif x[i]<=3*L/4.0:
+            y[i]=h_1
+        else:
+            y[i]=h_0
+    return y
+domain.set_quantity('stage',stage)
+
+def elevation(x):
+    y=zeros(len(x), Float)
+    for i in range (len(x)):
+        y[i] = bed_slope*x[i]
+    return y
+domain.set_quantity('elevation',elevation)
+
+### ================ Define the boundary function =========================
+#def f_right(t):
+#    z_r = bed_slope*(0.5*L)
+#    h_r = h_0 #+ bed_slope*cell_len
+#    w_r = z_r + h_r
+#    u_r = m*t   
+#    #['stage', 'xmomentum', 'elevation', 'height', 'velocity']
+#    return [w_r,  u_r*h_r,  z_r,  h_r,  u_r]
+
+#T_right = Time_boundary(domain,f_right)
+#D_right = Dirichlet_boundary([bed_slope*(0.5*L)+h_0,(m*domain.time)*h_0,bed_slope*(0.5*L),h_0,m*domain.time])
+#D_left = Dirichlet_boundary([-1.0*bed_slope*(0.5*L),  0.0,  -1.0*bed_slope*(0.5*L),  0.0,  0.0])
+D_right = Dirichlet_boundary([h_0,  0.0,  0.0,  h_0,  0.0])
+D_left = Dirichlet_boundary([0.0,  0.0,  0.0,  0.0,  0.0])
+domain.set_boundary({'left':D_left,'right':D_right})
+### ================  End of the definition of boundary function ===========
+
+X=domain.vertices
+C=domain.centroids
+import time
+yieldstep=finaltime=1.0
+t0=time.time()
+i=1
+
+while finaltime < 1.01:
+    for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+        domain.write_time()
+    finaltime = finaltime + 10.0 
+if t>0.0:
+    N = float(N)
+    StageC = domain.quantities['stage'].centroid_values
+    XmomC = domain.quantities['xmomentum'].centroid_values
+    VelC = domain.quantities['velocity'].centroid_values
+    #hC, uhC, uC = analytical_sol(C,domain.time)
+    #h_error = sum(abs(hC-StageC))/N
+    #uh_error = sum(abs(uhC-XmomC))/N
+    #u_error = sum(abs(uC-VelC))/N
+    #print "h_error %.10f" %(h_error)
+    #print "uh_error %.10f"%(uh_error)
+    #print "u_error %.10f" %(u_error)
+    #print 'That took %.2f seconds' %(time.time()-t0)
+    X = domain.vertices
+    StageQ = domain.quantities['stage'].vertex_values
+    XmomQ = domain.quantities['xmomentum'].vertex_values
+    VelQ = domain.quantities['velocity'].vertex_values
+    BedQ = domain.quantities['elevation'].vertex_values
+    #h, uh, u = analytical_sol(X.flat, domain.time)
+
+    SD = domain.shock_detector
+
+    from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+    hold(False)
+    plot1 = subplot(211)
+    #plot(X,h, X,StageQ, X,BedQ) #plot(X,h,'k-',X,StageQ,'k--')
+    plot(X,StageQ, X,BedQ)
+    plot1.set_ylim([-1,11])
+    plot1.set_xlim([0.0,2000.0])
+    legend(('Numerical solution', 'Bed elevation'),
+            'upper left', shadow=False)    
+    #xlabel('Position')
+    ylabel('Stage')
+    
+
+    plot2 = subplot(212)
+    plot(points,SD)
+    plot2.set_xlim([0.0,2000.0])
+    xlabel('Position')
+    ylabel('Smoothness indicator')
+
+    show()
+    
+    #filename = "%s%04i%s" %("dam_", i, ".eps")
+    #savefig(filename)
+    #finaltime = finaltime + 0.25
+    #print "finaltime=", finaltime
+    #i = i + 1
+    #print "The domain.limiter is", domain.limiter
+    #print 'That took %.2f seconds'%(time.time()-t0)
+    #print '============================================================================='
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/domain.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/domain.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/domain.py	(revision 7906)
@@ -0,0 +1,1437 @@
+"""Class Domain - 1D domains for finite-volume computations of
+   the shallow water wave equation
+
+
+   Copyright 2004
+   Ole Nielsen, Stephen Roberts, Duncan Gray, Christopher Zoppou
+   Geoscience Australia
+"""
+
+from generic_boundary_conditions import *
+
+
+class Domain:
+
+    def __init__(self,
+                 coordinates,
+                 boundary = None,
+                 conserved_quantities = None,
+                 evolved_quantities = None,
+                 other_quantities = None,
+                 tagged_elements = None):
+        """
+        Build 1D elements from x coordinates
+        """
+
+        from Numeric import Float, Int
+        from numpy import array, zeros       
+
+        from config import timestepping_method
+        from config import CFL
+        
+        #Store Points
+        self.coordinates = array(coordinates)
+
+
+        #Register number of Elements
+        self.number_of_elements = N = len(self.coordinates)-1
+
+        self.beta = 1.0
+        self.set_limiter("minmod_kurganov")
+        self.set_CFL(CFL)
+        self.set_timestepping_method(timestepping_method)
+
+        self.wet_nodes = zeros((N,2), Int) # should this be here
+
+        #Allocate space for neighbour and boundary structures
+        self.neighbours = zeros((N, 2), Int)
+        self.neighbour_vertices = zeros((N, 2), Int)
+        self.number_of_boundaries = zeros(N, Int)
+        self.surrogate_neighbours = zeros((N, 2), Int)
+        
+        #Allocate space for geometric quantities
+        self.vertices  = zeros((N, 2), Float)
+        self.centroids = zeros(N, Float)
+        self.areas     = zeros(N, Float)
+        self.max_speed_array = zeros(N, Float)
+        self.normals = zeros((N, 2), Float)
+        
+        for i in range(N):
+            xl = self.coordinates[i]
+            xr = self.coordinates[i+1]
+            self.vertices[i,0] = xl
+            self.vertices[i,1] = xr
+
+            centroid = (xl+xr)/2.0
+            self.centroids[i] = centroid
+
+            msg = 'Coordinates should be ordered, smallest to largest'
+            assert xr>xl, msg
+            
+            #The normal vectors
+            # - point outward from each edge
+            # - are orthogonal to the edge
+            # - have unit length
+            # - Are enumerated by left vertex then right vertex normals
+
+            nl = -1.0
+            nr =  1.0
+            self.normals[i,:] = [nl, nr]
+            self.areas[i] = (xr-xl)
+      
+            #Initialise Neighbours (-1 means that it is a boundary neighbour)
+            self.neighbours[i, :] = [-1, -1]
+            #Initialise vertex ids of neighbours
+            #In case of boundaries this slot is not used
+            self.neighbour_vertices[i, :] = [-1, -1]
+
+        self.build_vertexlist()
+
+        #Build neighbour structure
+        self.build_neighbour_structure()
+
+        #Build surrogate neighbour structure
+        self.build_surrogate_neighbour_structure()          
+
+        #Build boundary dictionary mapping (id, vertex) to symbolic tags
+        self.build_boundary_dictionary(boundary)
+
+        #Build tagged element  dictionary mapping (tag) to array of elements
+        self.build_tagged_elements_dictionary(tagged_elements)
+        
+        from quantity import Quantity, Conserved_quantity
+        
+        #List of quantity names entering the conservation equations
+        #(Must be a subset of quantities)
+        if conserved_quantities is None:
+            self.conserved_quantities = []
+        else:
+            self.conserved_quantities = conserved_quantities
+
+        if evolved_quantities is None:
+            self.evolved_quantities = self.conserved_quantities
+        else:
+            self.evolved_quantities = evolved_quantities
+
+        if other_quantities is None:
+            self.other_quantities = []
+        else:
+            self.other_quantities = other_quantities
+
+
+        #Build dictionary of Quantity instances keyed by quantity names
+        self.quantities = {}
+
+        #FIXME: remove later - maybe OK, though....
+        for name in self.evolved_quantities:
+            self.quantities[name] = Quantity(self)
+        for name in self.other_quantities:
+            self.quantities[name] = Quantity(self)
+
+        #Create an empty list for explicit forcing terms
+        self.forcing_terms = []
+
+        #Defaults
+        from config import max_smallsteps, beta_w, beta_h, epsilon, CFL
+        self.beta_w = beta_w
+        self.beta_h = beta_h
+        self.epsilon = epsilon
+
+        #FIXME: Maybe have separate orders for h-limiter and w-limiter?
+        #Or maybe get rid of order altogether and use beta_w and beta_h
+        self.default_order = 1
+        self.order = self.default_order
+
+        self.default_time_order = 1
+        self.time_order = self.default_time_order
+        
+        self.smallsteps = 0
+        self.max_smallsteps = max_smallsteps
+        self.number_of_steps = 0
+        self.number_of_first_order_steps = 0
+
+        #Model time
+        self.time = 0.0
+        self.finaltime = None
+        self.min_timestep = self.max_timestep = 0.0
+        self.starttime = 0 #Physical starttime if any (0 is 1 Jan 1970 00:00:00)
+        #Checkpointing and storage
+        from config import default_datadir
+        self.set_datadir(default_datadir)
+        self.filename = 'domain_avalanche'
+        self.checkpoint = False
+        self.shock_detector = zeros(N+1, Float)
+
+    def __len__(self):
+        return self.number_of_elements
+
+    def build_vertexlist(self):
+        """Build vertexlist index by vertex ids and for each entry (point id)
+        build a list of (triangles, vertex_id) pairs that use the point
+        as vertex.
+
+        Preconditions:
+          self.coordinates and self.triangles are defined
+
+        Postcondition:
+          self.vertexlist is built
+        """
+        from numpy import array
+
+        vertexlist = [None]*len(self.coordinates)
+        for i in range(self.number_of_elements):
+            a = i
+            b = i + 1
+
+            #Register the vertices v as lists of
+            #(triangle_id, vertex_id) tuples associated with them
+            #This is used for smoothing
+            #for vertex_id, v in enumerate([a,b,c]):
+            for vertex_id, v in enumerate([a,b]):
+                if vertexlist[v] is None:
+                    vertexlist[v] = []
+
+                vertexlist[v].append( (i, vertex_id) )
+
+        self.vertexlist = vertexlist
+
+        
+    def build_neighbour_structure(self):
+        """Update all registered triangles to point to their neighbours.
+
+        Also, keep a tally of the number of boundaries for each triangle
+
+        Postconditions:
+          neighbours and neighbour_edges is populated
+          neighbours and neighbour_vertices is populated
+          number_of_boundaries integer array is defined.
+        """
+
+        #Step 1:
+        #Build dictionary mapping from segments (2-tuple of points)
+        #to left hand side edge (facing neighbouring triangle)
+
+        N = self.number_of_elements
+        neighbourdict = {}
+        l_vertex = 0
+        r_vertex = 1
+        for i in range(N):
+
+            #Register all segments as keys mapping to current triangle
+            #and segment id
+            a = self.vertices[i,0]
+            b = self.vertices[i,1]
+            
+            neighbourdict[a,l_vertex] = (i, 0) #(id, vertex)
+            neighbourdict[b,r_vertex] = (i, 1) #(id, vertex)
+
+
+        #Step 2:
+        #Go through triangles again, but this time
+        #reverse direction of segments and lookup neighbours.
+        for i in range(N):
+            a = self.vertices[i,0]
+            b = self.vertices[i,1]
+            
+            self.number_of_boundaries[i] = 2
+            if neighbourdict.has_key((b,l_vertex)):
+                self.neighbours[i, 1] = neighbourdict[b,l_vertex][0]
+                self.neighbour_vertices[i, 1] = neighbourdict[b,l_vertex][1]
+                self.number_of_boundaries[i] -= 1
+
+            if neighbourdict.has_key((a,r_vertex)):
+                self.neighbours[i, 0] = neighbourdict[a,r_vertex][0]
+                self.neighbour_vertices[i, 0] = neighbourdict[a,r_vertex][1]
+                self.number_of_boundaries[i] -= 1
+
+    def build_surrogate_neighbour_structure(self):
+        """Build structure where each triangle edge points to its neighbours
+        if they exist. Otherwise point to the triangle itself.
+
+        The surrogate neighbour structure is useful for computing gradients
+        based on centroid values of neighbours.
+
+        Precondition: Neighbour structure is defined
+        Postcondition:
+          Surrogate neighbour structure is defined:
+          surrogate_neighbours: i0, i1, i2 where all i_k >= 0 point to
+          triangles.
+
+        """
+
+        N = self.number_of_elements
+        for i in range(N):
+            #Find all neighbouring volumes that are not boundaries
+            #for k in range(3):
+            for k in range(2):    
+                if self.neighbours[i, k] < 0:
+                    self.surrogate_neighbours[i, k] = i #Point this triangle
+                else:
+                    self.surrogate_neighbours[i, k] = self.neighbours[i, k]
+
+    def build_boundary_dictionary(self, boundary = None):
+        """Build or check the dictionary of boundary tags.
+         self.boundary is a dictionary of tags,
+         keyed by volume id and edge:
+         { (id, edge): tag, ... }
+
+         Postconditions:
+            self.boundary is defined.
+        """
+
+        from config import default_boundary_tag
+
+        if boundary is None:
+            boundary = {}
+            for vol_id in range(self.number_of_elements):
+                for vertex_id in range(0, 2):    
+                    if self.neighbours[vol_id, vertex_id] < 0:   
+                        boundary[(vol_id, vertex_id)] = default_boundary_tag
+        else:
+            #Check that all keys in given boundary exist
+            #for vol_id, edge_id in boundary.keys():
+            for vol_id, vertex_id in boundary.keys():    
+                msg = 'Segment (%d, %d) does not exist' %(vol_id, vertex_id)
+                a, b = self.neighbours.shape
+                assert vol_id < a and vertex_id < b, msg
+
+                #FIXME: This assert violates internal boundaries (delete it)
+                #msg = 'Segment (%d, %d) is not a boundary' %(vol_id, edge_id)
+                #assert self.neighbours[vol_id, edge_id] < 0, msg
+
+            #Check that all boundary segments are assigned a tag
+            for vol_id in range(self.number_of_elements):
+                for vertex_id in range(0, 2):    
+                    if self.neighbours[vol_id, vertex_id] < 0:    
+                        if not boundary.has_key( (vol_id, vertex_id) ):    
+                            msg = 'WARNING: Given boundary does not contain '
+                            msg += 'tags for vertex (%d, %d). '\
+                                   %(vol_id, vertex_id)
+                            msg += 'Assigning default tag (%s).'\
+                                   %default_boundary_tag
+                            boundary[ (vol_id, vertex_id) ] =\
+                                      default_boundary_tag
+
+        self.boundary = boundary
+
+    def build_tagged_elements_dictionary(self, tagged_elements = None):
+        """Build the dictionary of element tags.
+         self.tagged_elements is a dictionary of element arrays,
+         keyed by tag:
+         { (tag): [e1, e2, e3..] }
+
+         Postconditions:
+            self.element_tag is defined
+        """
+        from Numeric import Int
+        from numpy import array      
+
+        if tagged_elements is None:
+            tagged_elements = {}
+        else:
+            #Check that all keys in given boundary exist
+            for tag in tagged_elements.keys():
+                tagged_elements[tag] = array(tagged_elements[tag]).astype(Int)
+
+                msg = 'Not all elements exist. '
+                assert max(tagged_elements[tag]) < self.number_of_elements, msg
+        self.tagged_elements = tagged_elements
+
+
+    def set_quantities_to_be_stored(self, q):
+        """Specify which quantities will be stored in the sww file.
+
+        q must be either:
+          - the name of a quantity
+          - a list of quantity names
+          - None
+
+        In the two first cases, the named quantities will be stored at each
+        yieldstep
+        (This is in addition to the quantities elevation and friction)  
+        If q is None, storage will be switched off altogether.
+        """
+
+
+        if q is None:
+            self.quantities_to_be_stored = []            
+            self.store = False
+            return
+
+        if isinstance(q, basestring):
+            q = [q] # Turn argument into a list
+
+        #Check correcness    
+        for quantity_name in q:
+            msg = 'Quantity %s is not a valid conserved quantity' %quantity_name
+            assert quantity_name in self.conserved_quantities, msg 
+        
+        self.quantities_to_be_stored = q
+        
+
+
+
+
+    def get_boundary_tags(self):
+        """Return list of available boundary tags
+        """
+
+        tags = {}
+        for v in self.boundary.values():
+            tags[v] = 1
+
+        return tags.keys()
+        
+    def get_vertex_coordinates(self, obj = False):
+        """Return all vertex coordinates.
+        Return all vertex coordinates for all triangles as an Nx6 array
+        (ordered as x0, y0, x1, y1, x2, y2 for each triangle)
+
+        if obj is True, the x/y pairs are returned in a 3*N x 2 array.
+        FIXME, we might make that the default.
+        FIXME Maybe use keyword: continuous = False for this condition?
+
+        
+        """
+
+        if obj is True:
+            from numpy import concatenate, reshape
+            V = self.vertices
+            N = V.shape[0]
+            return reshape(V, (N, 2))
+        else:    
+            return self.vertices
+    
+    def get_conserved_quantities(self, vol_id, vertex=None):#, edge=None):
+        """Get conserved quantities at volume vol_id
+
+        If vertex is specified use it as index for vertex values
+        If edge is specified use it as index for edge values
+        If neither are specified use centroid values
+        If both are specified an exeception is raised
+
+        Return value: Vector of length == number_of_conserved quantities
+
+        """
+
+        from Numeric import Float
+        from numpy import zeros       
+        q = zeros( len(self.conserved_quantities), Float)
+        for i, name in enumerate(self.conserved_quantities):
+            Q = self.quantities[name]
+            if vertex is not None:
+                q[i] = Q.vertex_values[vol_id, vertex]
+            else:
+                q[i] = Q.centroid_values[vol_id]
+
+        return q
+
+
+    def get_evolved_quantities(self, vol_id, vertex=None):#, edge=None):
+        """Get evolved quantities at volume vol_id
+
+        If vertex is specified use it as index for vertex values
+        If edge is specified use it as index for edge values
+        If neither are specified use centroid values
+        If both are specified an exeception is raised
+
+        Return value: Vector of length == number_of_evolved quantities
+
+        """
+
+        from Numeric import Float
+        from numpy import zeros       
+        q = zeros( len(self.evolved_quantities), Float)
+
+        for i, name in enumerate(self.evolved_quantities):
+            Q = self.quantities[name]
+            if vertex is not None:
+                q[i] = Q.vertex_values[vol_id, vertex]
+            else:
+                q[i] = Q.centroid_values[vol_id]
+
+        return q
+        
+
+    def get_centroids(self):
+        """Return all coordinates of centroids
+        Return x coordinate of centroid for each element as a N array
+        """
+
+        return self.centroids
+
+    def get_vertices(self):
+        """Return all coordinates of centroids
+        Return x coordinate of centroid for each element as a N array
+        """
+
+        return self.vertices
+
+    def get_coordinate(self, elem_id, vertex=None):
+        """Return coordinate of centroid,
+        or left or right vertex.
+        Left vertex (vertex=0). Right vertex (vertex=1)
+        """
+
+        if vertex is None:
+            return self.centroids[elem_id]
+        else:
+            return self.vertices[elem_id,vertex]
+
+    def get_area(self, elem_id):
+        """Return area of element id
+        """
+
+        return self.areas[elem_id]
+
+    def get_quantity(self, name, location='vertices', indices = None):
+        """Get values for named quantity
+
+        name: Name of quantity
+
+        In case of location == 'centroids' the dimension values must
+        be a list of a Numerical array of length N, N being the number
+        of elements. Otherwise it must be of dimension Nx3.
+
+        Indices is the set of element ids that the operation applies to.
+
+        The values will be stored in elements following their
+        internal ordering.
+        """
+
+        return self.quantities[name].get_values( location, indices = indices)
+
+    def get_centroid_coordinates(self):
+        """Return all centroid coordinates.
+        Return all centroid coordinates for all triangles as an Nx2 array
+        (ordered as x0, y0 for each triangle)
+        """
+        return self.centroids
+
+
+    def get_timestepping_method(self):
+        return self.timestepping_method
+
+    def set_timestepping_method(self,timestepping_method):
+        
+        if timestepping_method in ['euler', 'rk2', 'rk3']:
+            self.timestepping_method = timestepping_method
+            return
+
+        msg = '%s is an incorrect timestepping type'% timestepping_method
+        raise Exception, msg
+
+
+    def set_quantity(self, name, *args, **kwargs):
+        """Set values for named quantity
+
+
+        One keyword argument is documented here:
+        expression = None, # Arbitrary expression
+
+        expression:
+          Arbitrary expression involving quantity names
+
+        See Quantity.set_values for further documentation.
+        """
+        #Do the expression stuff
+        if kwargs.has_key('expression'):
+            expression = kwargs['expression']
+            del kwargs['expression']
+
+            Q = self.create_quantity_from_expression(expression)
+            kwargs['quantity'] = Q
+        
+        #Assign values
+        self.quantities[name].set_values(*args, **kwargs)
+
+    def set_boundary(self, boundary_map):
+        """Associate boundary objects with tagged boundary segments.
+
+        Input boundary_map is a dictionary of boundary objects keyed
+        by symbolic tags to matched against tags in the internal dictionary
+        self.boundary.
+
+        As result one pointer to a boundary object is stored for each vertex
+        in the list self.boundary_objects.
+        More entries may point to the same boundary object
+
+        Schematically the mapping is from two dictionaries to one list
+        where the index is used as pointer to the boundary_values arrays
+        within each quantity.
+
+        self.boundary:          (vol_id, edge_id): tag
+        boundary_map (input):   tag: boundary_object
+        ----------------------------------------------
+        self.boundary_objects:  ((vol_id, edge_id), boundary_object)
+
+
+        Pre-condition:
+          self.boundary has been built.
+
+        Post-condition:
+          self.boundary_objects is built
+
+        If a tag from the domain doesn't appear in the input dictionary an
+        exception is raised.
+        However, if a tag is not used to the domain, no error is thrown.
+        FIXME: This would lead to implementation of a
+        default boundary condition
+
+        Note: If a segment is listed in the boundary dictionary and if it is
+        not None, it *will* become a boundary -
+        even if there is a neighbouring triangle.
+        This would be the case for internal boundaries
+
+        Boundary objects that are None will be skipped.
+
+        FIXME: If set_boundary is called multiple times and if Boundary
+        object is changed into None, the neighbour structure will not be
+        restored!!!
+        """
+
+        self.boundary_objects = []
+        self.boundary_map = boundary_map  #Store for use with eg. boundary_stats.
+
+        #FIXME: Try to remove the sorting and fix test_mesh.py
+        x = self.boundary.keys()
+        x.sort()
+
+        #Loop through edges that lie on the boundary and associate them with
+        #callable boundary objects depending on their tags
+        for k, (vol_id, vertex_id) in enumerate(x):
+            tag = self.boundary[ (vol_id, vertex_id) ]
+            if boundary_map.has_key(tag):
+                B = boundary_map[tag]  #Get callable boundary object
+                if B is not None:
+                    #self.boundary_objects.append( ((vol_id, edge_id), B) )
+                    #self.neighbours[vol_id, edge_id] = -len(self.boundary_objects)
+                    self.boundary_objects.append( ((vol_id, vertex_id), B) )
+                    self.neighbours[vol_id, vertex_id] = -len(self.boundary_objects)
+                else:
+                    pass
+                    #FIXME: Check and perhaps fix neighbour structure
+
+            else:
+                msg = 'ERROR (domain.py): Tag "%s" has not been ' %tag
+                msg += 'bound to a boundary object.\n'
+                msg += 'All boundary tags defined in domain must appear '
+                msg += 'in the supplied dictionary.\n'
+                msg += 'The tags are: %s' %self.get_boundary_tags()
+                raise msg
+
+
+
+    def check_integrity(self):
+        #Mesh.check_integrity(self)    
+        for quantity in self.conserved_quantities:
+            msg = 'Conserved quantities must be a subset of all quantities'
+            assert quantity in self.quantities, msg
+
+        for quantity in self.evolved_quantities:
+            msg = 'Evolved quantities must be a subset of all quantities'
+            assert quantity in self.quantities, msg            
+
+    def write_time(self):
+        print self.timestepping_statistics()
+
+    def get_time(self):
+        print self.time
+        
+
+    def timestepping_statistics(self):
+        """Return string with time stepping statistics for printing or logging
+        """
+
+        msg = ''
+        if self.min_timestep == self.max_timestep:
+            msg += 'Time = %.4f, delta t = %.8f, steps=%d (%d)'\
+                   %(self.time, self.min_timestep, self.number_of_steps,
+                     self.number_of_first_order_steps)
+        elif self.min_timestep > self.max_timestep:
+            msg += 'Time = %.4f, steps=%d (%d)'\
+                   %(self.time, self.number_of_steps,
+                     self.number_of_first_order_steps)
+        else:
+            msg += 'Time = %.4f, delta t in [%.8f, %.8f], steps=%d (%d)'\
+                   %(self.time, self.min_timestep,
+                     self.max_timestep, self.number_of_steps,
+                     self.number_of_first_order_steps)
+
+        return msg
+
+    def get_name(self):
+        return self.filename
+
+    def set_name(self, name):
+        self.filename = name
+
+    def get_datadir(self):
+        return self.datadir
+
+    def set_datadir(self, name):
+        self.datadir = name
+
+    def set_CFL(self, cfl):
+        if cfl > 1.0:
+            print 'WARNING: Setting CFL condition to %f which is greater than 1' % cfl
+        self.CFL = cfl
+
+    def get_CFL(self):
+        return self.CFL
+    
+    def set_filename(self, name):
+        self.filename = name
+
+    def get_filename(self):
+        return self.filename
+
+    def get_limiter(self):
+        return self.limiter
+
+    def set_limiter(self,limiter):
+
+        possible_limiters = \
+        ['pyvolution', 'minmod_steve', 'minmod', 'minmod_kurganov', 'superbee', 'vanleer', 'vanalbada']
+
+        if limiter in possible_limiters:
+            self.limiter = limiter
+            return
+
+        msg = '%s is an incorrect limiter type.\n'% limiter
+        msg += 'Possible types are: '+ ", ".join(["%s" % el for el in possible_limiters])
+        raise Exception, msg
+
+        
+    #--------------------------
+    # Main components of evolve
+    #--------------------------    
+
+    def evolve(self, yieldstep = None,
+               finaltime = None,
+               duration = None,
+               skip_initial_step = False):
+        """Evolve model through time starting from self.starttime.
+
+
+        yieldstep: Interval between yields where results are stored,
+                   statistics written and domain inspected or
+                   possibly modified. If omitted the internal predefined
+                   max timestep is used.
+                   Internally, smaller timesteps may be taken.
+
+        duration: Duration of simulation
+
+        finaltime: Time where simulation should end. This is currently
+        relative time.  So it's the same as duration.
+
+        If both duration and finaltime are given an exception is thrown.
+
+
+        skip_initial_step: Boolean flag that decides whether the first
+        yield step is skipped or not. This is useful for example to avoid
+        duplicate steps when multiple evolve processes are dove tailed.
+
+
+        Evolve is implemented as a generator and is to be called as such, e.g.
+
+        for t in domain.evolve(yieldstep, finaltime):
+            <Do something with domain and t>
+
+
+        All times are given in seconds
+
+        """
+
+        from config import min_timestep, max_timestep, epsilon
+
+        # FIXME: Maybe lump into a larger check prior to evolving
+        msg = 'Boundary tags must be bound to boundary objects before '
+        msg += 'evolving system, '
+        msg += 'e.g. using the method set_boundary.\n'
+        msg += 'This system has the boundary tags %s '\
+               %self.get_boundary_tags()
+        assert hasattr(self, 'boundary_objects'), msg
+
+        if yieldstep is None:
+            yieldstep = max_timestep
+        else:
+            yieldstep = float(yieldstep)
+
+        self._order_ = self.default_order
+
+        if finaltime is not None and duration is not None:
+            # print 'F', finaltime, duration
+            msg = 'Only one of finaltime and duration may be specified'
+            raise msg
+        else:
+            if finaltime is not None:
+                self.finaltime = float(finaltime)
+            if duration is not None:
+                self.finaltime = self.starttime + float(duration)
+
+        N = len(self) # Number of triangles
+        self.yieldtime = 0.0 # Track time between 'yields'
+
+        # Initialise interval of timestep sizes (for reporting only)
+        self.min_timestep = max_timestep
+        self.max_timestep = min_timestep
+        self.number_of_steps = 0
+        self.number_of_first_order_steps = 0
+
+
+        # Update ghosts
+        self.update_ghosts()
+
+        # Initial update of vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update extrema if necessary (for reporting)
+        self.update_extrema()
+        
+        # Initial update boundary values
+        self.update_boundary()
+
+        # Or maybe restore from latest checkpoint
+        if self.checkpoint is True:
+            self.goto_latest_checkpoint()
+
+        if skip_initial_step is False:
+            yield(self.time)  # Yield initial values
+
+        while True:
+
+            # Evolve One Step, using appropriate timestepping method
+            if self.get_timestepping_method() == 'euler':
+                self.evolve_one_euler_step(yieldstep,finaltime)
+                
+            elif self.get_timestepping_method() == 'rk2':
+                self.evolve_one_rk2_step(yieldstep,finaltime)
+
+            elif self.get_timestepping_method() == 'rk3':
+                self.evolve_one_rk3_step(yieldstep,finaltime)               
+            
+            # Update extrema if necessary (for reporting)
+            self.update_extrema()            
+            self.yieldtime += self.timestep
+            self.number_of_steps += 1
+            if self._order_ == 1:
+                self.number_of_first_order_steps += 1
+
+
+            # Yield results
+            if finaltime is not None and self.time >= finaltime-epsilon:
+
+                if self.time > finaltime:
+                    msg = 'WARNING (domain.py): time overshot finaltime. '
+                    msg += 'Contact Ole.Nielsen@ga.gov.au'
+                    raise Exception, msg
+                    
+
+                # Yield final time and stop
+                self.time = finaltime
+                yield(self.time)
+                break
+
+            if self.yieldtime >= yieldstep-0.5*min_timestep:
+                # Yield (intermediate) time and allow inspection of domain
+
+                if self.checkpoint is True:
+                    self.store_checkpoint()
+                    self.delete_old_checkpoints()
+
+                # Pass control on to outer loop for more specific actions
+                print "Test if passing here.....,Sudi."
+                yield(self.time)
+
+                # Reinitialise
+                self.yieldtime = 0.0
+                self.min_timestep = max_timestep
+                self.max_timestep = min_timestep
+                self.number_of_steps = 0
+                self.number_of_first_order_steps = 0
+
+                if finaltime is not None and self.time >= finaltime-0.5*min_timestep:
+                    break
+
+
+    def evolve_one_euler_step(self, yieldstep, finaltime):
+        """
+        One Euler Time Step
+        Q^{n+1} = E(h) Q^n
+        """
+
+        # Back up evolved (ALL) quantities, Sudi 13 July 2010
+        self.backup_evolved_quantities()
+
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Update time
+        self.time += self.timestep
+
+        # Detect shock, Sudi 13 July 2010
+        self.detect_shock()
+        
+
+
+    def evolve_one_rk2_step(self, yieldstep, finaltime):
+        """
+        One 2nd order RK timestep
+        Q^{n+1} = 0.5 Q^n + 0.5 E(h)^2 Q^n
+        """
+       
+        # Save initial conserved quantities values
+        self.backup_conserved_quantities()
+        
+        # Back up non_conserved (ehv) quantities, Sudi 13 July 2010
+        self.backup_ehv_quantities()        
+
+        #--------------------------------------
+        # First euler step
+        #--------------------------------------
+
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Update time
+        self.time += self.timestep
+
+        #------------------------------------
+        # Second Euler step                     
+        #------------------------------------
+            
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        #------------------------------------
+        # Combine initial and final values
+        # of conserved quantities and cleanup
+        #------------------------------------
+        
+        # Combine steps
+        self.saxpy_conserved_quantities(0.5, 0.5)
+
+        #-----------------------------------
+        # clean up vertex values
+        #-----------------------------------
+ 
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Detect shock, Sudi 13 July 2010
+        self.detect_shock()       
+
+
+
+    def evolve_one_rk3_step(self, yieldstep, finaltime):
+        """
+        One 3rd order RK timestep
+        Q^(1) = 3/4 Q^n + 1/4 E(h)^2 Q^n  (at time t^n + h/2)
+        Q^{n+1} = 1/3 Q^n + 2/3 E(h) Q^(1) (at time t^{n+1})
+        """
+
+        # Save initial initial conserved quantities values
+        self.backup_conserved_quantities()
+
+        # Back up non_conserved (ehv) quantities, Sudi 13 July 2010
+        self.backup_ehv_quantities()         
+
+        initial_time = self.time
+        
+        #--------------------------------------
+        # First euler step
+        #--------------------------------------
+
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Update time
+        self.time += self.timestep
+
+        #------------------------------------
+        # Second Euler step
+        #------------------------------------
+            
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        #------------------------------------
+        #Combine steps to obtain intermediate
+        #solution at time t^n + 0.5 h
+        #------------------------------------
+
+        # Combine steps
+        self.saxpy_conserved_quantities(0.25, 0.75)
+ 
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Set substep time
+        self.time = initial_time + self.timestep*0.5
+
+        #------------------------------------
+        # Third Euler step
+        #------------------------------------
+            
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        #------------------------------------
+        # Combine final and initial values
+        # and cleanup
+        #------------------------------------
+        
+        # Combine steps
+        self.saxpy_conserved_quantities(2.0/3.0, 1.0/3.0)
+ 
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Set new time
+        self.time = initial_time + self.timestep
+
+        # Detect shock, Sudi 13 July 2010
+        self.detect_shock()         
+        
+
+    def backup_conserved_quantities(self):
+        N = len(self) # Number_of_triangles
+
+        # Backup conserved_quantities centroid values
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            Q.backup_centroid_values()
+
+    def backup_evolved_quantities(self):
+        N = len(self) # Number_of_triangles
+
+        # Backup evolved_quantities centroid values
+        for name in self.evolved_quantities:
+            Q = self.quantities[name]
+            Q.backup_centroid_values()             
+
+    def backup_ehv_quantities(self):
+        N = len(self) # Number_of_triangles
+
+        # Backup NON-conserved_quantities centroid values
+        for name in ['elevation', 'height', 'velocity']:
+            Q = self.quantities[name]
+            Q.backup_centroid_values()
+
+    def detect_shock(self):
+        h_prev = self.quantities['height'].centroid_backup_values
+        h_now  = self.quantities['height'].centroid_values
+        u_prev = self.quantities['velocity'].centroid_backup_values
+        u_now  = self.quantities['velocity'].centroid_values
+        Ver = self.vertices
+        N = len(Ver)
+        E = self.shock_detector
+        E[0] = E[N] = E[N-1] = 0.0
+        #from parameters import points
+        for i in range(N-2):
+            k = i+1
+            interval = Ver[k]
+            dx = interval[1]-interval[0]
+            dt = self.timestep
+            E[k] = 0.5 * dx *(h_now[k] - h_prev[k] + h_now[k+1] - h_prev[k+1])
+            E[k] += 0.5 * dt *(h_prev[k+1]*u_prev[k+1] - h_prev[k]*u_prev[k]
+                               + h_now[k+1]*u_now[k+1] - h_now[k]*u_now[k])
+        self.shock_detector[:] = abs(E)
+
+    def saxpy_conserved_quantities(self,a,b):
+        N = len(self) #number_of_triangles
+
+        # Backup conserved_quantities centroid values
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            Q.saxpy_centroid_values(a,b)        
+    
+    def solve_inhomogenous_second_order(self,yieldstep, finaltime):
+
+        #Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+        #Compute forcing terms
+        self.compute_forcing_terms()
+        #Update conserved quantities
+        self.update_conserved_quantities(0.5*self.timestep)
+        #Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+        #Update boundary values
+        self.update_boundary()
+
+    def  solve_homogenous_second_order(self,yieldstep,finaltime):
+        """Use Shu Second order timestepping to update
+        conserved quantities
+
+        q^{n+1/2} = q^{n}+0.5*dt*F^{n}
+        q^{n+1} = q^{n}+dt*F^{n+1/2}
+        """
+        import copy
+        from Numeric import Float
+        from numpy import zeros        
+
+        N = self.number_of_elements
+
+        self.compute_fluxes()
+        #Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+        #Compute forcing terms
+        #NOT NEEDED FOR 2ND ORDER STRANG SPLIITING
+        #ADDING THIS WILL NEED TO REMOVE ZEROING IN COMPUTE_FORCING
+        #self.compute_forcing_terms()
+
+        QC = zeros((N,len(self.conserved_quantities)),Float)
+        QF = zeros((N,len(self.conserved_quantities)),Float)
+
+        i = 0
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            #Store the centroid values at time t^n
+            QC[:,i] = copy.copy(Q.centroid_values)
+            QF[:,i] = copy.copy(Q.explicit_update)
+            #Update conserved quantities
+            Q.update(self.timestep)
+            i+=1
+            
+        #Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+        #Update boundary values
+        self.update_boundary()
+        
+        self.compute_fluxes()
+        self.update_timestep(yieldstep, finaltime)
+        #Compute forcing terms
+        #NOT NEEDED FOR 2ND ORDER STRANG SPLIITING
+        #self.compute_forcing_terms()
+
+        i = 0
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            Q.centroid_values = QC[:,i]
+            Q.explicit_update = 0.5*(Q.explicit_update+QF[:,i]) 
+            #Update conserved quantities
+            Q.update(self.timestep)
+            i+=1
+        
+        #Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+        #Update boundary values
+        self.update_boundary()
+
+    def  solve_homogenous_second_order_harten(self,yieldstep,finaltime):
+        """Use Harten Second order timestepping to update
+        conserved quantities
+
+        q^{n+1/2} = q^{n}+0.5*dt*F^{n}
+        q^{n+1} = q^{n}+dt*F^{n+1/2}
+        """
+        import copy
+        from Numeric import Float
+        from numpy import zeros       
+
+        N = self.number_of_elements
+
+        self.compute_fluxes()
+        #Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+        #Compute forcing terms
+        #NOT NEEDED FOR 2ND ORDER STRANG SPLIITING
+        #ADDING THIS WILL NEED TO REMOVE ZEROING IN COMPUTE_FORCING
+        #self.compute_forcing_terms()
+
+        QC = zeros((N,len(self.conserved_quantities)),Float)
+
+        i = 0
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            #Store the centroid values at time t^n
+            QC[:,i] = copy.copy(Q.centroid_values)
+            #Update conserved quantities
+            Q.update(0.5*self.timestep)
+            i+=1
+            
+        #Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+        #Update boundary values
+        self.update_boundary()
+        
+        self.compute_fluxes()
+        self.update_timestep(yieldstep, finaltime)
+        #Compute forcing terms
+        #NOT NEEDED FOR 2ND ORDER STRANG SPLIITING
+        #self.compute_forcing_terms()
+
+        i = 0
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            Q.centroid_values = QC[:,i] 
+            #Update conserved quantities
+            Q.update(self.timestep)
+            i+=1
+        
+        #Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+        #Update boundary values
+        self.update_boundary()
+        
+    def distribute_to_vertices_and_edges(self):
+        """Extrapolate conserved quantities from centroid to
+        vertices and edge-midpoints for each volume
+
+        Default implementation is straight first order,
+        i.e. constant values throughout each element and
+        no reference to non-conserved quantities.
+        """
+
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            if self.order == 1:
+                Q.extrapolate_first_order()
+            elif self.order == 2:
+                Q.extrapolate_second_order()
+                #Q.limit()
+            else:
+                raise 'Unknown order'
+
+
+    def update_ghosts(self):
+        pass
+        """
+        n = len(self.quantities['stage'].vertex_values)
+        from parameters import bed_slope, cell_len        
+
+        self.quantities['stage'].centroid_values[n-1]     = self.quantities['stage'].boundary_values[1] - 0.5*bed_slope*cell_len
+        self.quantities['xmomentum'].centroid_values[n-1] = self.quantities['xmomentum'].boundary_values[1]
+        self.quantities['elevation'].centroid_values[n-1] = self.quantities['elevation'].boundary_values[1] - 0.5*bed_slope*cell_len
+        self.quantities['height'].centroid_values[n-1]    = self.quantities['height'].boundary_values[1]
+        self.quantities['velocity'].centroid_values[n-1]  = self.quantities['velocity'].boundary_values[1]
+        #Below is additional condition, after meeting Steve, to make smooth dry bed.
+        self.quantities['stage'].centroid_values[0]     = self.quantities['stage'].boundary_values[0] + 0.5*bed_slope*cell_len
+        self.quantities['xmomentum'].centroid_values[0] = self.quantities['xmomentum'].boundary_values[0]
+        self.quantities['elevation'].centroid_values[0] = self.quantities['elevation'].boundary_values[0] + 0.5*bed_slope*cell_len
+        self.quantities['height'].centroid_values[0]    = self.quantities['height'].boundary_values[0]
+        self.quantities['velocity'].centroid_values[0]  = self.quantities['velocity'].boundary_values[0]
+        """
+        
+    
+    def update_boundary(self):
+        """Go through list of boundary objects and update boundary values
+        for all conserved quantities on boundary.
+        """        
+        for i, ((vol_id, vertex_id), B) in enumerate(self.boundary_objects):
+            q = B.evaluate(vol_id, vertex_id)
+            for j, name in enumerate(self.evolved_quantities):
+                #print 'name %s j = %f \n'%(name,j)
+                Q = self.quantities[name]
+                Q.boundary_values[i] = q[j]
+        """
+        ##!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!        
+        for j, name in enumerate(self.evolved_quantities):
+            BV = self.quantities[name].boundary_values
+            VV = self.quantities[name].vertex_values
+            n = len(VV)
+            VV[0,0] = BV[0]
+            VV[n-1,1] = BV[1]
+
+        
+        #Below is for fixing the ghost cell.
+        from parameters import bed_slope, cell_len
+        n = len(self.quantities['stage'].vertex_values)
+        self.quantities['stage'].vertex_values[n-1,0]     = self.quantities['stage'].boundary_values[1] - bed_slope*cell_len
+        self.quantities['xmomentum'].vertex_values[n-1,0] = self.quantities['xmomentum'].boundary_values[1]
+        self.quantities['elevation'].vertex_values[n-1,0] = self.quantities['elevation'].boundary_values[1] - bed_slope*cell_len
+        self.quantities['height'].vertex_values[n-1,0]    = self.quantities['height'].boundary_values[1]
+        self.quantities['velocity'].vertex_values[n-1,0]  = self.quantities['velocity'].boundary_values[1]
+        #Below is additional condition, after meeting Steve, to make smooth dry bed.
+        self.quantities['stage'].vertex_values[0,1]     = self.quantities['stage'].boundary_values[0] + bed_slope*cell_len
+        self.quantities['xmomentum'].vertex_values[0,1] = self.quantities['xmomentum'].boundary_values[0]
+        self.quantities['elevation'].vertex_values[0,1] = self.quantities['elevation'].boundary_values[0] + bed_slope*cell_len
+        self.quantities['height'].vertex_values[0,1]    = self.quantities['height'].boundary_values[0]
+        self.quantities['velocity'].vertex_values[0,1]  = self.quantities['velocity'].boundary_values[0]
+        """
+        
+    def update_timestep(self, yieldstep, finaltime):
+
+        from config import min_timestep, max_timestep
+
+        # self.timestep is calculated from speed of characteristics
+        # Apply CFL condition here
+        timestep = min(self.CFL*self.flux_timestep, max_timestep)
+
+        #Record maximal and minimal values of timestep for reporting
+        self.max_timestep = max(timestep, self.max_timestep)
+        self.min_timestep = min(timestep, self.min_timestep)
+
+        #Protect against degenerate time steps
+        if timestep < min_timestep:
+
+            #Number of consecutive small steps taken b4 taking action
+            self.smallsteps += 1
+
+            if self.smallsteps > self.max_smallsteps:
+                self.smallsteps = 0 #Reset
+
+                if self.order == 1:
+                    msg = 'WARNING: Too small timestep %.16f reached '\
+                          %timestep
+                    msg += 'even after %d steps of 1 order scheme'\
+                           %self.max_smallsteps
+                    print msg
+                    timestep = min_timestep  #Try enforcing min_step
+
+                    #raise msg
+                else:
+                    #Try to overcome situation by switching to 1 order
+                    print "changing Order 1"
+                    self.order = 1
+
+        else:
+            self.smallsteps = 0
+            if self.order == 1 and self.default_order == 2:
+                self.order = 2
+
+
+        #Ensure that final time is not exceeded
+        if finaltime is not None and self.time + timestep > finaltime:
+            timestep = finaltime-self.time
+
+        #Ensure that model time is aligned with yieldsteps
+        if self.yieldtime + timestep > yieldstep:
+            timestep = yieldstep-self.yieldtime
+
+        self.timestep = timestep
+
+    def update_extrema(self):
+        pass
+
+    def compute_forcing_terms(self):
+        """If there are any forcing functions driving the system
+        they should be defined in Domain subclass and appended to
+        the list self.forcing_terms
+        """
+        #Clears explicit_update needed for second order method
+        if self.time_order == 2:
+            for name in self.conserved_quantities:
+                Q = self.quantities[name]
+                Q.explicit_update[:] = 0.0
+
+        for f in self.forcing_terms:
+            f(self)
+            
+
+    def update_derived_quantites(self):
+        pass
+    
+    #def update_conserved_quantities(self):
+    def update_conserved_quantities(self):
+        """Update vectors of conserved quantities using previously
+        computed fluxes specified forcing functions.
+        """
+
+        from Numeric import Float
+        from numpy import ones, sum, equal        
+
+        N = self.number_of_elements
+        d = len(self.conserved_quantities)
+
+        timestep = self.timestep
+
+        #Compute forcing terms
+        self.compute_forcing_terms()
+
+        #Update conserved_quantities
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            Q.update(timestep)
+
+
+
+if __name__ == "__main__":
+
+    points1 = [0.0, 1.0, 2.0, 3.0]
+    D1 = Domain(points1)
+
+    print D1.get_coordinate(0)
+    print D1.get_coordinate(0,1)
+    print 'Number of Elements = ',D1.number_of_elements
+
+    try:
+        print D1.get_coordinate(3)
+    except:
+        pass
+    else:
+        msg =  'Should have raised an out of bounds exception'
+        raise msg
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/generic_boundary_conditions.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/generic_boundary_conditions.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/generic_boundary_conditions.py	(revision 7906)
@@ -0,0 +1,553 @@
+"""boundary.py - Classes for implementing boundary conditions
+"""
+
+
+class Boundary:
+    """Base class for boundary conditions.
+       Specific boundary conditions must provide values for
+       the conserved_quantities
+
+       A boundary object has one neighbour; the one it
+       serves.
+    """
+
+    def __init__(self):
+        pass
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        msg = 'Generic class Boundary must be subclassed'
+        raise msg
+
+class Reflective_boundary(Boundary):
+    """Reflective boundary returns same conserved quantities as
+    those present in its neighbour volume but reflected.
+
+    This class is specific to the shallow water equation as it
+    works with the momentum quantities assumed to be the second
+    and third conserved quantities.
+    """
+
+    def __init__(self, domain = None):
+        Boundary.__init__(self)
+
+        if domain is None:
+            msg = 'Domain must be specified for reflective boundary'
+            raise msg
+
+        #Handy shorthands
+        self.normals  = domain.normals
+        self.stage    = domain.quantities['stage'].vertex_values
+        self.xmom     = domain.quantities['xmomentum'].vertex_values
+        self.bed      = domain.quantities['elevation'].vertex_values
+        self.height   = domain.quantities['height'].vertex_values
+        self.velocity = domain.quantities['velocity'].vertex_values
+
+        from Numeric import Float
+        from numpy import zeros      
+        self.evolved_quantities = zeros(5, Float)
+
+    def __repr__(self):
+        return 'Reflective_boundary'
+
+    def evaluate(self, vol_id, edge_id):
+        """Reflective boundaries reverses the outward momentum
+        of the volume they serve.
+        """
+        q = self.evolved_quantities
+        q[0] = self.stage[vol_id, edge_id]
+        q[1] = -self.xmom[vol_id, edge_id]
+        q[2] = self.bed[vol_id, edge_id]
+        q[3] = self.height[vol_id, edge_id]
+        q[4] = -self.velocity[vol_id, edge_id]
+        return q
+
+
+class Transmissive_boundary(Boundary):
+    """Transmissive boundary returns same conserved quantities as
+    those present in its neighbour volume.
+
+    Underlying domain must be specified when boundary is instantiated
+    """
+
+    def __init__(self, domain = None):
+        Boundary.__init__(self)
+
+        if domain is None:
+            msg = 'Domain must be specified for transmissive boundary'
+            raise msg
+
+        self.domain = domain
+
+    def __repr__(self):
+        return 'Transmissive_boundary(%s)' %self.domain
+
+    def evaluate(self, vol_id, vertex_id):
+        """Transmissive boundaries return the edge values
+        of the volume they serve.
+        """
+
+        q = self.domain.get_conserved_quantities(vol_id, vertex = vertex_id)#(vol_id, edge = edge_id)
+        return q
+
+
+class Dirichlet_boundary(Boundary):
+    """Dirichlet boundary returns constant values for the
+    conserved quantities
+    """
+
+
+    def __init__(self, conserved_quantities=None):
+        Boundary.__init__(self)
+
+        if conserved_quantities is None:
+            msg = 'Must specify one value for each conserved quantity'
+            raise msg
+
+        from Numeric import Float
+        from numpy import array       
+        self.conserved_quantities=array(conserved_quantities).astype(Float)
+
+    def __repr__(self):
+        return 'Dirichlet boundary (%s)' %self.conserved_quantities
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        return self.conserved_quantities
+
+
+
+class Time_boundary(Boundary):
+    """Time dependent boundary returns values for the
+    conserved quantities as a function of time.
+    Must specify domain to get access to model time and a function f(t)
+    which must return conserved quantities as a function time
+    """
+
+
+    def __init__(self, domain = None, f = None):
+        Boundary.__init__(self)
+
+        try:
+            q = f(0.0)
+        except Exception, e:
+            msg = 'Function for time boundary could not be executed:\n%s' %e
+            raise msg
+
+
+        from Numeric import Float
+        from numpy import array       
+        try:
+            q = array(q).astype(Float)
+        except:
+            msg = 'Return value from time boundary function could '
+            msg += 'not be converted into a Numeric array of floats.\n'
+            msg += 'Specified function should return either list or array.'
+            raise msg
+
+        msg = 'ERROR: Time boundary function must return a 1d list or array '
+        assert len(q.shape) == 1, msg
+
+        d = len(domain.evolved_quantities)
+
+        #print 'd = ',d
+        msg = 'Return value for f must be a list or an array of length %d' %d
+        assert len(q) == d, msg
+
+        self.f = f
+        self.domain = domain
+
+    def __repr__(self):
+        return 'Time boundary'
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        return self.f(self.domain.time)
+
+
+class File_boundary_time(Boundary):
+    """Boundary values obtained from file and interpolated.
+    conserved quantities as a function of time.
+
+    Assumes that file contains a time series.
+
+    No spatial info assumed.
+    """
+
+    #FIXME: Is this still necessary
+
+    def __init__(self, filename, domain):
+        import time
+        from numpy import array
+        from config import time_format
+        from util import File_function
+
+        Boundary.__init__(self)
+
+        self.F = File_function(filename, domain)
+        self.domain = domain
+
+        #Test
+        q = self.F(0)
+
+        d = len(domain.conserved_quantities)
+        msg = 'Values specified in file must be a list or an array of length %d' %d
+        assert len(q) == d, msg
+
+
+    def __repr__(self):
+        return 'File boundary'
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        """Return linearly interpolated values based on domain.time
+
+        vol_id and edge_id are ignored
+        """
+
+        t = self.domain.time
+        return self.F(t)
+
+
+
+
+class File_boundary(Boundary):
+    """Boundary values obtained from file and interpolated.
+    conserved quantities as a function of time.
+
+    Assumes that file contains a time series and possibly
+    also spatial info.
+    See docstring for File_function in util.py for details about
+    admissible file formats
+
+    The full solution history is not exactly the same as if
+    the models were coupled:
+    File boundary must read and interpolate from *smoothed* version
+    as stored in sww and cannot work with the discontinuos triangles.
+
+    """
+
+    def __init__(self, filename, domain, verbose = False):
+        import time
+        from Numeric import Float
+        from numpy import array, zeros       
+        from config import time_format
+        from util import file_function
+
+        Boundary.__init__(self)
+
+        #Get x,y vertex coordinates for all triangles
+        V = domain.vertex_coordinates
+
+        #Compute midpoint coordinates for all boundary elements
+        #Only a subset may be invoked when boundary is evaluated but
+        #we don't know which ones at this stage since this object can be attached to
+        #any tagged boundary later on.
+
+        if verbose: print 'Find midpoint coordinates of entire boundary'
+        self.midpoint_coordinates = zeros( (len(domain.boundary), 2), Float)
+        boundary_keys = domain.boundary.keys()
+
+
+        xllcorner = domain.geo_reference.get_xllcorner()
+        yllcorner = domain.geo_reference.get_yllcorner()        
+        
+
+        #Make ordering unique #FIXME: should this happen in domain.py?
+        boundary_keys.sort()
+
+
+        #Record ordering #FIXME: should this also happen in domain.py?
+        self.boundary_indices = {}
+        for i, (vol_id, edge_id) in enumerate(boundary_keys):
+
+            x0 = V[vol_id, 0]; y0 = V[vol_id, 1]
+            x1 = V[vol_id, 2]; y1 = V[vol_id, 3]
+            x2 = V[vol_id, 4]; y2 = V[vol_id, 5]
+
+            #Compute midpoints
+            if edge_id == 0: m = array([(x1 + x2)/2, (y1 + y2)/2])
+            if edge_id == 1: m = array([(x0 + x2)/2, (y0 + y2)/2])
+            if edge_id == 2: m = array([(x1 + x0)/2, (y1 + y0)/2])
+
+            #Convert to absolute UTM coordinates
+            m[0] += xllcorner
+            m[1] += yllcorner
+            
+            #Register point and index
+            self.midpoint_coordinates[i,:] = m
+            self.boundary_indices[(vol_id, edge_id)] = i
+
+
+        if verbose: print 'Initialise file_function'
+        self.F = file_function(filename, domain,
+	                       interpolation_points=self.midpoint_coordinates,
+                               verbose = verbose)
+        self.domain = domain
+
+        #Test
+        q = self.F(0, point_id=0)
+
+        d = len(domain.conserved_quantities)
+        msg = 'Values specified in file %s must be ' %filename
+        msg += ' a list or an array of length %d' %d
+        assert len(q) == d, msg
+
+
+    def __repr__(self):
+        return 'File boundary'
+
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        """Return linearly interpolated values based on domain.time
+
+        vol_id and edge_id are ignored
+        """
+
+        t = self.domain.time
+
+        if vol_id is not None and edge_id is not None:
+            i = self.boundary_indices[ vol_id, edge_id ]
+            return self.F(t, point_id = i)
+        else:
+            #raise 'Boundary call without point_id not implemented'
+            #FIXME: What should the semantics be?
+            return self.F(t)
+
+
+
+
+
+
+
+
+#THIS FAR (10/8/4)
+class Connective_boundary(Boundary):
+    """Connective boundary returns values for the
+    conserved quantities from a volume as defined by a connection table
+    mapping between tuples of (volume id, face id) for volumes that
+    have their boundaries connected.
+
+    FIXME: Perhaps include possibility of mapping between
+    different domains as well
+
+    FIXME: In case of shallow water we may want to have a
+    special version that casts this in terms of height rather than stage
+    """
+
+
+    def __init__(self, table):
+        from domain import Volume
+
+        Boundary.__init__(self)
+
+        self.connection_table = table
+        self.Volume = Volume
+
+    def __repr__(self):
+        return 'Connective boundary'
+
+    #FIXME: IF we ever need to get field_values from connected volume,
+    #that method could be overridden here (using same idea as in
+    #get_conserved_quantities
+    #def get_field_values()
+
+    def get_conserved_quantities(self, volume, face=0):
+
+        id = volume.id
+        if self.connection_table.has_key((id, face)):
+            other_id, other_face = self.connection_table[(id, face)]
+
+            other_volume = self.Volume.instances[other_id]
+            cmd = 'q = other_volume.conserved_quantities_face%d' %face;
+            exec(cmd)
+            return q
+        else:
+            msg = 'Volume, face tuple ($d, %d) has not been mapped'\
+                  %(id, face)
+            raise msg
+
+
+
+
+
+#FIXME: Add a boundary with a general function of x,y, and t
+
+#FIXME: Add periodic boundaries e.g.:
+# Attempt at periodic conditions from advection_spik. Remember this
+#
+#first = 2*(N-1)*N
+#for i in range(1,2*N+1,2):
+#    k = first + i-1#
+#
+#    print i,k
+#
+#    domain[i].faces[2].neighbour = domain[k].faces[1]
+#    domain[k].faces[1].neighbour = domain[i].faces[2]
+
+
+
+class General_boundary(Boundary):
+    """General boundary which can compute conserved quantities based on
+    their previous value, conserved quantities of its neighbour and model time.
+
+    Must specify initial conserved quantities,
+    neighbour,
+    domain to get access to model time
+    a function f(q_old, neighbours_q, t) which must return
+    new conserved quantities q as a function time
+
+    FIXME: COMPLETE UNTESTED - JUST AN IDEA
+    """
+
+    def __init__(self, neighbour=None, conserved_quantities=None, domain=None, f=None):
+        Boundary.__init__(self, neighbour=neighbour, conserved_quantities=conserved_quantities)
+
+        self.f = f
+        self.domain = domain
+
+
+    def get_conserved_quantities(self, volume=None, face=0):
+        return self.f(self.conserved_quantities,
+                      neighbour.conserved_quantities,
+                      self.domain.time)
+
+
+
+
+
+class File_boundary_old(Boundary):
+    """Boundary values obtained from file and interpolated.
+    conserved quantities as a function of time.
+
+    Assumes that file contains a time series.
+
+    No spatial info assumed.
+    """
+
+
+    def __init__(self, domain = None, filename = None):
+        import time
+        from numpy import array
+        from config import time_format
+
+        Boundary.__init__(self)
+
+
+        try:
+            fid = open(filename)
+        except Exception, e:
+            msg = 'Boundary file %s could not be opened: %s\n' %(filename, e)
+            raise msg
+
+
+        line = fid.readline()
+        fid.close()
+        fields = line.split(',')
+        msg = 'File %s must have the format date, values'
+        assert len(fields) == 2, msg
+
+        try:
+            starttime = time.mktime(time.strptime(fields[0], time_format))
+        except ValueError:
+            msg = 'First field in file %s must be' %filename
+            msg += ' date-time with format %s.\n' %time_format
+            msg += 'I got %s instead.' %fields[0]
+            raise msg
+
+        #Split values
+        values = []
+        for value in fields[1].split():
+            values.append(float(value))
+
+        q = array(values)
+
+        msg = 'ERROR: File boundary function must return a 1d list or array '
+        assert len(q.shape) == 1, msg
+
+        d = len(domain.conserved_quantities)
+        msg = 'Values specified in file must be a list or an array of length %d' %d
+        assert len(q) == d, msg
+
+        self.filename = filename
+        self.domain = domain
+        self.starttime = starttime
+
+        if domain.starttime is None:
+            domain.starttime = starttime
+        else:
+            msg = 'Start time as specified in domain (%s) is earlier '
+            'than the starttime of file %s: %s'\
+                  %(domain.starttime, self.filename, self.starttime)
+            if self.starttime > domain.starttime:
+                raise msg
+
+        self.read_time_boundary() #Now read all times in.
+
+
+    def read_time_boundary(self):
+        from Numeric import Float
+        from numpy import zeros, alltrue        
+        from config import time_format
+        import time
+
+        fid = open(self.filename)
+        lines = fid.readlines()
+        fid.close()
+
+        N = len(lines)
+        d = len(self.domain.conserved_quantities)
+
+        T = zeros(N, Float)
+        Q = zeros((N, d), Float)
+
+
+        for i, line in enumerate(lines):
+            fields = line.split(',')
+            real_time = time.mktime(time.strptime(fields[0], time_format))
+
+            T[i] = real_time - self.starttime
+
+
+            for j, value in enumerate(fields[1].split()):
+                Q[i, j] = float(value)
+
+        msg = 'Time boundary must list time as a monotonuosly '
+        msg += 'increasing sequence'
+
+        assert alltrue( T[1:] - T[:-1] > 0 ), msg
+
+        self.T = T     #Time
+        self.Q = Q     #Boundary values
+        self.index = 0 #Initial index
+
+
+    def __repr__(self):
+        return 'File boundary'
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        """Return linearly interpolated values based on domain.time
+        """
+
+        t = self.domain.time
+
+        msg = 'Time given in File boundary does not match model time'
+        if t < self.T[0]: raise msg
+        if t > self.T[-1]: raise msg
+
+        oldindex = self.index
+
+        #Find slot
+        while t > self.T[self.index]: self.index += 1
+        while t < self.T[self.index]: self.index -= 1
+
+        #if oldindex != self.index:
+        #    print 'Changing from %d to %d' %(oldindex, self.index)
+
+
+        #t is now between index and index+1
+        ratio = (t - self.T[self.index])/\
+                (self.T[self.index+1] - self.T[self.index])
+
+        return self.Q[self.index,:] +\
+               ratio*(self.Q[self.index+1,:] - self.Q[self.index,:])
+
+
+
+
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/parameters.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/parameters.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/parameters.py	(revision 7906)
@@ -0,0 +1,27 @@
+from Numeric import Float, sqrt
+from numpy import zeros
+from config import g
+from scipy import sin, cos, tan, arcsin, arccos, arctan, pi
+
+h_0 = 5.0
+h_1 = 10.0
+L=2000.0
+N=200
+
+cell_len=L/N
+points=zeros(N+1, Float)
+for i in range(N+1):
+    points[i]=i*cell_len
+    #points[i] = i*cell_len - 0.5*L
+
+
+
+#delt = 0.0
+friction_slope = 0.0#0.05 #tan(delta) #0.05 # NOTE THAT friction_slope must less than bed_slope
+#thet = pi/36.0
+bed_slope = 0.002 #tan(theta) #0.1      # bottom slope, positive if it is increasing bottom.
+thet = arctan(bed_slope)
+
+F2 = g*cos(thet)*cos(thet)*friction_slope
+c0 = sqrt(g*h_0)   # sound speed
+m = -1.0*g*bed_slope + F2   # auxiliary variable
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/qsub.sh
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/qsub.sh	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/qsub.sh	(revision 7906)
@@ -0,0 +1,8 @@
+#!/bin/bash
+#
+#PBS -N Python
+#PBS -m be
+#PBS -k oe
+
+/usr/bin/python \
+    /home/mungkasi/anuga/trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_RUN.py
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/qsub_new.sh
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/qsub_new.sh	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/qsub_new.sh	(revision 7906)
@@ -0,0 +1,10 @@
+#!/bin/bash
+#
+#PBS -N Python
+#PBS -l nodes=1:ppn=1,walltime=20:00:00,mem=1gb
+#PBS -M sudi.mungkasi@anu.edu.au
+#PBS -m abe
+#PBS -k oe
+
+/usr/bin/python \
+    /home/mungkasi/anuga/trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_RUN.py
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/quantity.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/quantity.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/quantity.py	(revision 7906)
@@ -0,0 +1,1049 @@
+"""Class Quantity - Implements values at each 1d element
+
+To create:
+
+   Quantity(domain, vertex_values)
+
+   domain: Associated domain structure. Required.
+
+   vertex_values: N x 2 array of values at each vertex for each element.
+                  Default None
+
+   If vertex_values are None Create array of zeros compatible with domain.
+   Otherwise check that it is compatible with dimenions of domain.
+   Otherwise raise an exception
+"""
+
+
+
+class Quantity:
+
+    
+    def __init__(self, domain, vertex_values=None):
+        #Initialise Quantity using optional vertex values.
+        
+        from domain import Domain
+        from Numeric import Float
+        from numpy import array, zeros      
+
+        msg = 'First argument in Quantity.__init__ '
+        msg += 'must be of class Domain (or a subclass thereof)'
+        assert isinstance(domain, Domain), msg
+
+        if vertex_values is None:
+            N = domain.number_of_elements
+            self.vertex_values = zeros((N, 2), Float)
+        else:
+            self.vertex_values = array(vertex_values, Float)
+
+            N, V = self.vertex_values.shape
+            assert V == 2,\
+                   'Two vertex values per element must be specified'
+
+
+            msg = 'Number of vertex values (%d) must be consistent with'\
+                  %N
+            msg += 'number of elements in specified domain (%d).'\
+                   %domain.number_of_elements
+
+            assert N == domain.number_of_elements, msg
+
+        self.domain = domain
+
+        #Allocate space for other quantities
+        self.centroid_values = zeros(N, Float)
+        self.centroid_backup_values = zeros(N, Float)
+        #self.edge_values = zeros((N, 2), Float)
+        #edge values are values of the ends of each interval
+      
+        #Intialise centroid values
+        self.interpolate()
+
+
+        from Numeric import Float
+        from numpy import zeros       
+        
+        #Allocate space for boundary values
+        #L = len(domain.boundary)
+        self.boundary_values = zeros(2, Float) #assumes no parrellism
+
+        #Allocate space for updates of conserved quantities by
+        #flux calculations and forcing functions
+        
+        N = domain.number_of_elements
+        self.explicit_update = zeros(N, Float )
+        self.semi_implicit_update = zeros(N, Float )
+
+        self.gradients = zeros(N, Float)
+        self.qmax = zeros(self.centroid_values.shape, Float)
+        self.qmin = zeros(self.centroid_values.shape, Float)
+
+        self.beta = domain.beta        
+
+
+    def __len__(self):
+        """
+        Returns number of intervals.
+        """
+        return self.centroid_values.shape[0]
+    
+    def interpolate(self):
+        """
+        Compute interpolated values at centroid
+        Pre-condition: vertex_values have been set
+        """
+
+        N = self.vertex_values.shape[0]
+        for i in range(N):
+            v0 = self.vertex_values[i, 0]
+            v1 = self.vertex_values[i, 1]
+
+            self.centroid_values[i] = (v0 + v1)/2.0
+
+    def set_values(self, X, location='vertices'):
+        """Set values for quantity
+
+        X: Compatible list, Numeric array (see below), constant or function
+        location: Where values are to be stored.
+                  Permissible options are: vertices, centroid
+                  Default is "vertices"
+
+        In case of location == 'centroid' the dimension values must
+        be a list of a Numerical array of length N, N being the number
+        of elements in the mesh. Otherwise it must be of dimension Nx2
+
+        The values will be stored in elements following their
+        internal ordering.
+
+        If values are described a function, it will be evaluated at specified points
+
+        If selected location is vertices, values for centroid and edges
+        will be assigned interpolated values.
+        In any other case, only values for the specified locations
+        will be assigned and the others will be left undefined.
+        """
+
+        if location not in ['vertices', 'centroids']:
+            msg = 'Invalid location: %s, (possible choices vertices, centroids)' %location
+            raise msg
+
+        if X is None:
+            msg = 'Given values are None'
+            raise msg
+
+        import types
+
+        if callable(X):
+            #Use function specific method
+            self.set_function_values(X, location)
+        elif type(X) in [types.FloatType, types.IntType, types.LongType]:
+            if location == 'centroids':
+                self.centroid_values[:] = X
+            else:
+                self.vertex_values[:] = X
+
+        else:
+            #Use array specific method
+            self.set_array_values(X, location)
+
+        if location == 'vertices':
+            #Intialise centroid and edge values
+            self.interpolate()
+
+
+
+
+
+    def set_function_values(self, f, location='vertices'):
+        """Set values for quantity using specified function
+
+        f: x -> z Function where x and z are arrays
+        location: Where values are to be stored.
+                  Permissible options are: vertices, centroid
+                  Default is "vertices"
+        """
+        
+        if location == 'centroids':
+            
+            P = self.domain.centroids
+            self.set_values(f(P), location)
+        else:
+            #Vertices
+            P = self.domain.get_vertices()
+            
+            for i in range(2):
+                self.vertex_values[:,i] = f(P[:,i])        
+
+    def set_array_values(self, values, location='vertices'):
+        """Set values for quantity
+
+        values: Numeric array
+        location: Where values are to be stored.
+                  Permissible options are: vertices, centroid, edges
+                  Default is "vertices"
+
+        In case of location == 'centroid' the dimension values must
+        be a list of a Numerical array of length N, N being the number
+        of elements in the mesh. Otherwise it must be of dimension Nx2
+
+        The values will be stored in elements following their
+        internal ordering.
+
+        If selected location is vertices, values for centroid
+        will be assigned interpolated values.
+        In any other case, only values for the specified locations
+        will be assigned and the others will be left undefined.
+        """
+
+        from Numeric import Float
+        from numpy import array       
+
+        values = array(values).astype(Float)
+
+        N = self.centroid_values.shape[0]
+
+        msg = 'Number of values must match number of elements'
+        assert values.shape[0] == N, msg
+
+        if location == 'centroids':
+            assert len(values.shape) == 1, 'Values array must be 1d'
+            self.centroid_values = values
+        #elif location == 'edges':
+        #    assert len(values.shape) == 2, 'Values array must be 2d'
+        #    msg = 'Array must be N x 2'
+        #    self.edge_values = values
+        else:
+            assert len(values.shape) == 2, 'Values array must be 2d'
+            msg = 'Array must be N x 2'
+            assert values.shape[1] == 2, msg
+
+            self.vertex_values = values
+
+
+    def get_values(self, location='vertices', indices = None):
+        """get values for quantity
+
+        return X, Compatible list, Numeric array (see below)
+        location: Where values are to be stored.
+                  Permissible options are: vertices, centroid
+                  and unique vertices. Default is 'vertices'
+
+        In case of location == 'centroids' the dimension values must
+        be a list of a Numerical array of length N, N being the number
+        of elements. Otherwise it must be of dimension Nx3
+
+        The returned values with be a list the length of indices
+        (N if indices = None).  Each value will be a list of the three
+        vertex values for this quantity.
+
+        Indices is the set of element ids that the operation applies to.
+
+        """
+        from Numeric import take
+
+        if location not in ['vertices', 'centroids', 'unique vertices']:
+            msg = 'Invalid location: %s' %location
+            raise msg
+
+        import types, Numeric
+        assert type(indices) in [types.ListType, types.NoneType,
+                                 Numeric.ArrayType],\
+                                 'Indices must be a list or None'
+
+        if location == 'centroids':
+            if (indices ==  None):
+                indices = range(len(self))
+            return take(self.centroid_values,indices)
+        elif location == 'unique vertices':
+            if (indices ==  None):
+                indices=range(self.domain.coordinates.shape[0])
+            vert_values = []
+            #Go through list of unique vertices
+            for unique_vert_id in indices:
+                cells = self.domain.vertexlist[unique_vert_id]
+
+                #In case there are unused points
+                if cells is None:
+                    msg = 'Unique vertex not associated with cells'
+                    raise msg
+
+                # Go through all cells, vertex pairs
+                # Average the values
+                sum = 0
+                for cell_id, vertex_id in cells:
+                    sum += self.vertex_values[cell_id, vertex_id]
+                vert_values.append(sum/len(cells))
+            return Numeric.array(vert_values)
+        else:
+            if (indices ==  None):
+                indices = range(len(self))
+            return take(self.vertex_values,indices)
+
+
+    def get_vertex_values(self,
+                          x=True,
+                          smooth = None,
+                          precision = None,
+                          reduction = None):
+        """Return vertex values like an OBJ format
+
+        The vertex values are returned as one sequence in the 1D float array A.
+        If requested the coordinates will be returned in 1D arrays X.
+
+        The connectivity is represented as an integer array, V, of dimension
+        M x 2, where M is the number of volumes. Each row has two indices
+        into the X, A arrays defining the element.
+
+        if smooth is True, vertex values corresponding to one common
+        coordinate set will be smoothed according to the given
+        reduction operator. In this case vertex coordinates will be
+        de-duplicated.
+
+        If no smoothings is required, vertex coordinates and values will
+        be aggregated as a concatenation of values at
+        vertices 0, vertices 1
+
+
+        Calling convention
+        if x is True:
+           X,A,V = get_vertex_values
+        else:
+           A,V = get_vertex_values
+
+        """
+
+        from Numeric import Float, Int
+        from numpy import concatenate, zeros, array, reshape        
+
+
+        if smooth is None:
+            smooth = self.domain.smooth
+
+        if precision is None:
+            precision = Float
+
+        if reduction is None:
+            reduction = self.domain.reduction
+
+        #Create connectivity
+
+        if smooth == True:
+
+            V = self.domain.get_vertices()
+            N = len(self.domain.vertexlist)
+            #N = len(self.domain.vertices)
+            A = zeros(N, precision)
+
+            #Smoothing loop
+            for k in range(N):
+                L = self.domain.vertexlist[k]
+                #L = self.domain.vertices[k]
+
+                #Go through all triangle, vertex pairs
+                #contributing to vertex k and register vertex value
+
+                if L is None: continue #In case there are unused points
+
+                contributions = []
+                for volume_id, vertex_id in L:
+                    v = self.vertex_values[volume_id, vertex_id]
+                    contributions.append(v)
+
+                A[k] = reduction(contributions)
+
+            if x is True:
+                 #X = self.domain.coordinates[:,0].astype(precision)
+                 X = self.domain.coordinates[:].astype(precision)
+                 #Y = self.domain.coordinates[:,1].astype(precision)
+
+                 #return X, Y, A, V
+                 return X, A, V
+            
+            #else:
+            return A, V
+        else:
+            #Don't smooth
+            #obj machinery moved to general_mesh
+
+            # Create a V like [[0 1 2], [3 4 5]....[3*m-2 3*m-1 3*m]]
+            # These vert_id's will relate to the verts created below
+            #m = len(self.domain)  #Number of volumes
+            #M = 3*m        #Total number of unique vertices
+            #V = reshape(array(range(M)).astype(Int), (m,3))
+
+            #V = self.domain.get_triangles(obj=True)
+            V = self.domain.get_vertices
+            #FIXME use get_vertices, when ready
+
+            A = self.vertex_values.flat
+
+            #Do vertex coordinates
+            if x is True:
+                X = self.domain.get_vertex_coordinates()
+
+                #X = C[:,0:6:2].copy()
+                #Y = C[:,1:6:2].copy()
+
+                return X.flat, A, V
+            else:
+                return A, V
+
+    def get_integral(self):
+        """Compute the integral of quantity across entire domain
+        """
+        integral = 0
+        for k in range(self.domain.number_of_elements):
+            area = self.domain.areas[k]
+            qc = self.centroid_values[k]
+            integral += qc*area
+
+        return integral
+
+
+    def update(self, timestep):
+        """Update centroid values based on values stored in
+        explicit_update and semi_implicit_update as well as given timestep
+        """
+
+        from Numeric import Float
+        from numpy import sum, equal, ones      
+
+        N = self.centroid_values.shape[0]
+
+        #Explicit updates
+        self.centroid_values += timestep*self.explicit_update
+        
+        #Semi implicit updates
+        denominator = ones(N, Float)-timestep*self.semi_implicit_update
+
+        if sum(equal(denominator, 0.0)) > 0.0:
+            msg = 'Zero division in semi implicit update. Call Stephen :-)'
+            raise msg
+        else:
+            #Update conserved_quantities from semi implicit updates
+            self.centroid_values /= denominator
+
+
+    def compute_gradients(self):
+        """Compute gradients of piecewise linear function defined by centroids of
+        neighbouring volumes.
+        """
+
+        #print 'compute_gradient'
+
+        from Numeric import Float
+        from numpy import array, zeros       
+
+        N = self.centroid_values.shape[0]
+
+
+        G = self.gradients
+        Q = self.centroid_values
+        X = self.domain.centroids
+
+        for k in range(N):
+
+    	    # first and last elements have boundaries
+
+            if k == 0:
+
+                #Get data
+                k0 = k
+                k1 = k+1
+                k2 = k+2
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+                q2 = Q[k2]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+                x2 = X[k2]
+
+                #Gradient
+                #G[k] = (q1 - q0)/(x1 - x0)
+                
+                G[k] = (q1 - q0)*(x2 - x0)*(x2 - x0) - (q2 - q0)*(x1 - x0)*(x1 - x0)
+                G[k] /= (x1 - x0)*(x2 - x0)*(x2 - x1)
+
+            elif k == N-1:
+
+                #Get data
+                k0 = k
+                k1 = k-1
+                k2 = k-2
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+                q2 = Q[k2]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+                x2 = X[k2]
+
+                #Gradient
+                #G[k] = (q1 - q0)/(x1 - x0)
+                
+                G[k] = (q1 - q0)*(x2 - x0)*(x2 - x0) - (q2 - q0)*(x1 - x0)*(x1 - x0)
+                G[k] /= (x1 - x0)*(x2 - x0)*(x2 - x1)
+
+##                q0 = Q[k0]
+##                q1 = Q[k1]
+##
+##                x0 = X[k0] #V0 centroid
+##                x1 = X[k1] #V1 centroid
+##
+##                #Gradient
+##                G[k] = (q1 - q0)/(x1 - x0)
+
+            else:
+                #Interior Volume (2 neighbours)
+
+                #Get data
+                k0 = k-1
+                k2 = k+1
+
+                q0 = Q[k0]
+                q1 = Q[k]
+                q2 = Q[k2]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k]  #V1 centroid (Self)
+                x2 = X[k2] #V2 centroid
+
+                #Gradient
+                #G[k] = (q2-q0)/(x2-x0)
+                G[k] = ((q0-q1)/(x0-x1)*(x2-x1) - (q2-q1)/(x2-x1)*(x0-x1))/(x2-x0)
+
+
+    def compute_minmod_gradients(self):
+        """Compute gradients of piecewise linear function defined by centroids of
+        neighbouring volumes.
+        """
+
+        #print 'compute_minmod_gradients'
+        
+        from Numeric import Float,sign
+        from numpy import array, zeros       
+        
+        def xmin(a,b):
+            return 0.5*(sign(a)+sign(b))*min(abs(a),abs(b))
+
+        def xmic(t,a,b):
+            return xmin(t*xmin(a,b), 0.50*(a+b) )
+
+
+
+        N = self.centroid_values.shape[0]
+
+
+        G = self.gradients
+        Q = self.centroid_values
+        X = self.domain.centroids
+
+        for k in range(N):
+
+    	    # first and last elements have boundaries
+
+            if k == 0:
+
+                #Get data
+                k0 = k
+                k1 = k+1
+                k2 = k+2
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+                q2 = Q[k2]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+                x2 = X[k2]
+
+                #Gradient
+                #G[k] = (q1 - q0)/(x1 - x0)
+                
+                G[k] = (q1 - q0)*(x2 - x0)*(x2 - x0) - (q2 - q0)*(x1 - x0)*(x1 - x0)
+                G[k] /= (x1 - x0)*(x2 - x0)*(x2 - x1)
+
+            elif k == N-1:
+
+                #Get data
+                k0 = k
+                k1 = k-1
+                k2 = k-2
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+                q2 = Q[k2]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+                x2 = X[k2]
+
+                #Gradient
+                #G[k] = (q1 - q0)/(x1 - x0)
+                
+                G[k] = (q1 - q0)*(x2 - x0)*(x2 - x0) - (q2 - q0)*(x1 - x0)*(x1 - x0)
+                G[k] /= (x1 - x0)*(x2 - x0)*(x2 - x1)
+
+##                #Get data
+##                k0 = k
+##                k1 = k-1
+##
+##                q0 = Q[k0]
+##                q1 = Q[k1]
+##
+##                x0 = X[k0] #V0 centroid
+##                x1 = X[k1] #V1 centroid
+##
+##                #Gradient
+##                G[k] = (q1 - q0)/(x1 - x0)
+
+            elif (self.domain.wet_nodes[k,0] == 2) & (self.domain.wet_nodes[k,1] == 2):
+                G[k] = 0.0
+
+            else:
+                #Interior Volume (2 neighbours)
+
+                #Get data
+                k0 = k-1
+                k2 = k+1
+
+                q0 = Q[k0]
+                q1 = Q[k]
+                q2 = Q[k2]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k]  #V1 centroid (Self)
+                x2 = X[k2] #V2 centroid
+
+                # assuming uniform grid
+                d1 = (q1 - q0)/(x1-x0)
+                d2 = (q2 - q1)/(x2-x1)
+
+                #Gradient
+                #G[k] = (d1+d2)*0.5
+                #G[k] = (d1*(x2-x1) - d2*(x0-x1))/(x2-x0)                
+                G[k] = xmic( self.domain.beta, d1, d2 )
+        
+
+    def extrapolate_first_order(self):
+        """Extrapolate conserved quantities from centroid to
+        vertices for each volume using
+        first order scheme.
+        """
+
+        qc = self.centroid_values
+        qv = self.vertex_values
+
+        for i in range(2):
+            qv[:,i] = qc
+
+
+    def extrapolate_second_order(self):
+        """Extrapolate conserved quantities from centroid to
+        vertices for each volume using
+        second order scheme.
+        """
+        if self.domain.limiter == "pyvolution":
+            #Z = self.gradients
+            #print "gradients 1",Z
+            self.compute_gradients()
+            #print "gradients 2",Z
+
+            #Z = self.gradients
+            #print "gradients 1",Z
+            #self.compute_minmod_gradients()
+            #print "gradients 2", Z
+
+            G = self.gradients
+            V = self.domain.vertices
+            qc = self.centroid_values
+            qv = self.vertex_values        
+
+            #Check each triangle
+            for k in range(self.domain.number_of_elements):
+                #Centroid coordinates
+                x = self.domain.centroids[k]
+
+                #vertex coordinates
+                x0, x1 = V[k,:]
+
+                #Extrapolate
+                qv[k,0] = qc[k] + G[k]*(x0-x)
+                qv[k,1] = qc[k] + G[k]*(x1-x)
+            self.limit_pyvolution()
+        elif self.domain.limiter == "minmod_steve":
+            self.limit_minmod()
+        else:
+            self.limit_range()
+        
+        
+
+    def limit_minmod(self):
+        #Z = self.gradients
+        #print "gradients 1",Z
+        self.compute_minmod_gradients()
+        #print "gradients 2", Z
+
+        G = self.gradients
+        V = self.domain.vertices
+        qc = self.centroid_values
+        qv = self.vertex_values        
+        
+        #Check each triangle
+        for k in range(self.domain.number_of_elements):
+            #Centroid coordinates
+            x = self.domain.centroids[k]
+
+            #vertex coordinates
+            x0, x1 = V[k,:]
+
+            #Extrapolate
+            qv[k,0] = qc[k] + G[k]*(x0-x)
+            qv[k,1] = qc[k] + G[k]*(x1-x)
+
+ 
+    def limit_pyvolution(self):
+        """
+        Limit slopes for each volume to eliminate artificial variance
+        introduced by e.g. second order extrapolator
+
+        This is an unsophisticated limiter as it does not take into
+        account dependencies among quantities.
+
+        precondition:
+        vertex values are estimated from gradient
+        postcondition:
+        vertex values are updated
+        """
+        from Numeric import Float
+        from numpy import zeros      
+
+        N = self.domain.number_of_elements
+        beta = self.domain.beta
+        #beta = 0.8
+
+        qc = self.centroid_values
+        qv = self.vertex_values
+
+        #Find min and max of this and neighbour's centroid values
+        qmax = self.qmax
+        qmin = self.qmin
+
+        for k in range(N):
+            qmax[k] = qmin[k] = qc[k]
+            for i in range(2):
+                n = self.domain.neighbours[k,i]
+                if n >= 0:
+                    qn = qc[n] #Neighbour's centroid value
+
+                    qmin[k] = min(qmin[k], qn)
+                    qmax[k] = max(qmax[k], qn)
+
+
+        #Diffences between centroids and maxima/minima
+        dqmax = qmax - qc
+        dqmin = qmin - qc
+
+        #Deltas between vertex and centroid values
+        dq = zeros(qv.shape, Float)
+        for i in range(2):
+            dq[:,i] = qv[:,i] - qc
+
+        #Phi limiter
+        for k in range(N):
+
+            #Find the gradient limiter (phi) across vertices
+            phi = 1.0
+            for i in range(2):
+                r = 1.0
+                if (dq[k,i] > 0): r = dqmax[k]/dq[k,i]
+                if (dq[k,i] < 0): r = dqmin[k]/dq[k,i]
+
+                phi = min( min(r*beta, 1), phi )
+
+            #Then update using phi limiter
+            for i in range(2):
+                qv[k,i] = qc[k] + phi*dq[k,i]
+
+    def limit_range(self):
+        import sys
+        from Numeric import Float
+        from numpy import zeros        
+        from util import minmod, minmod_kurganov, maxmod, vanleer, vanalbada
+        limiter = self.domain.limiter
+        #print limiter
+        
+        #print 'limit_range'
+        N = self.domain.number_of_elements
+        qc = self.centroid_values
+        qv = self.vertex_values
+        C = self.domain.centroids
+        X = self.domain.vertices
+        beta_p = zeros(N,Float)
+        beta_m = zeros(N,Float)
+        beta_x = zeros(N,Float)
+        
+        for k in range(N):
+        
+            n0 = self.domain.neighbours[k,0]
+            n1 = self.domain.neighbours[k,1]
+            
+            if ( n0 >= 0) & (n1 >= 0):
+                #SLOPE DERIVATIVE LIMIT
+                beta_p[k] = (qc[k]-qc[k-1])/(C[k]-C[k-1])
+                beta_m[k] = (qc[k+1]-qc[k])/(C[k+1]-C[k])
+                beta_x[k] = (qc[k+1]-qc[k-1])/(C[k+1]-C[k-1])
+                
+        dq = zeros(qv.shape, Float)
+        for i in range(2):
+            dq[:,i] =self.domain.vertices[:,i]-self.domain.centroids
+            
+        #Phi limiter
+        for k in range(N):
+            n0 = self.domain.neighbours[k,0]
+            n1 = self.domain.neighbours[k,1]
+            if n0 < 0:
+                #phi = (qc[k+1] - qc[k])/(C[k+1] - C[k])    #This is the original
+                phi = (qc[k+1] - qc[k])/(C[k+1] - C[k])
+            elif n1 < 0:
+                #phi = (qc[k] - qc[k-1])/(C[k] - C[k-1])    #This is the original
+                phi = (qc[k] - qc[k-1])/(C[k] - C[k-1])
+            else:
+                if limiter == "minmod":
+                    phi = minmod(beta_p[k],beta_m[k])  #(beta_p[k]+1.0e-15,beta_m[k])
+                elif limiter == "minmod_kurganov":#Change this
+                    # Also known as monotonized central difference limiter if theta = 2.0
+                    theta = 2.0 
+                    phi = minmod_kurganov(theta*beta_p[k],theta*beta_m[k],beta_x[k])
+                elif limiter == "superbee":
+                    slope1 = minmod(beta_m[k],2.0*beta_p[k])
+                    slope2 = minmod(2.0*beta_m[k],beta_p[k])
+                    phi = maxmod(slope1,slope2)
+                elif limiter == "vanleer":
+                    phi = vanleer(beta_p[k],beta_m[k])
+                elif limiter == "vanalbada":
+                    phi = vanalbada(beta_m[k],beta_p[k])
+            
+            for i in range(2):
+                qv[k,i] = qc[k] + phi*dq[k,i]
+
+    def limit_steve_slope(self):    
+
+        import sys
+        from Numeric import Float
+        from numpy import zeros        
+        from util import minmod, minmod_kurganov, maxmod, vanleer
+
+        N = self.domain.number_of_elements
+        limiter = self.domain.limiter
+        limiter_type = self.domain.limiter_type
+            
+        qc = self.centroid_values
+        qv = self.vertex_values
+
+        #Find min and max of this and neighbour's centroid values
+        beta_p = zeros(N,Float)
+        beta_m = zeros(N,Float)
+        beta_x = zeros(N,Float)
+        C = self.domain.centroids
+        X = self.domain.vertices
+
+        for k in range(N):
+        
+            n0 = self.domain.neighbours[k,0]
+            n1 = self.domain.neighbours[k,1]
+            
+            if (n0 >= 0) & (n1 >= 0):
+                # Check denominator not zero
+                if (qc[k+1]-qc[k]) == 0.0:
+                    beta_p[k] = float(sys.maxint)
+                    beta_m[k] = float(sys.maxint)
+                else:
+                    #STEVE LIMIT
+                    beta_p[k] = (qc[k]-qc[k-1])/(qc[k+1]-qc[k])
+                    beta_m[k] = (qc[k+2]-qc[k+1])/(qc[k+1]-qc[k])
+
+        #Deltas between vertex and centroid values
+        dq = zeros(qv.shape, Float)
+        for i in range(2):
+            dq[:,i] =self.domain.vertices[:,i]-self.domain.centroids
+            
+        #Phi limiter
+        for k in range(N):
+                
+            phi = 0.0
+            if limiter == "flux_minmod":
+                #FLUX MINMOD
+                phi = minmod_kurganov(1.0,beta_m[k],beta_p[k])
+            elif limiter == "flux_superbee":
+                #FLUX SUPERBEE
+                phi = max(0.0,min(1.0,2.0*beta_m[k]),min(2.0,beta_m[k]))+max(0.0,min(1.0,2.0*beta_p[k]),min(2.0,beta_p[k]))-1.0
+            elif limiter == "flux_muscl":
+                #FLUX MUSCL
+                phi = max(0.0,min(2.0,2.0*beta_m[k],2.0*beta_p[k],0.5*(beta_m[k]+beta_p[k])))
+            elif limiter == "flux_vanleer":
+                #FLUX VAN LEER
+                phi = (beta_m[k]+abs(beta_m[k]))/(1.0+abs(beta_m[k]))+(beta_p[k]+abs(beta_p[k]))/(1.0+abs(beta_p[k]))-1.0
+                
+                #Then update using phi limiter
+                n = self.domain.neighbours[k,1]
+                if n>=0:
+                    #qv[k,0] = qc[k] - 0.5*phi*(qc[k+1]-qc[k])
+                    #qv[k,1] = qc[k] + 0.5*phi*(qc[k+1]-qc[k])
+                    qv[k,0] = qc[k] + 0.5*phi*(qv[k,0]-qc[k])
+                    qv[k,1] = qc[k] + 0.5*phi*(qv[k,1]-qc[k])
+                else:
+                    qv[k,i] = qc[k]
+
+    def backup_centroid_values(self):
+        # Call correct module function
+        # (either from this module or C-extension)
+        #backup_centroid_values(self)
+
+        self.centroid_backup_values[:] = (self.centroid_values).astype('f')
+
+    def saxpy_centroid_values(self,a,b):
+        # Call correct module function
+        # (either from this module or C-extension)
+        self.centroid_values[:] = (a*self.centroid_values + b*self.centroid_backup_values).astype('f')
+        
+class Conserved_quantity(Quantity):
+    """Class conserved quantity adds to Quantity:
+
+    storage and method for updating, and
+    methods for extrapolation from centropid to vertices inluding
+    gradients and limiters
+    """
+
+    def __init__(self, domain, vertex_values=None):
+        Quantity.__init__(self, domain, vertex_values)
+
+        print "Use Quantity instead of Conserved_quantity"
+
+"""
+## closePlots crashes with non-interactive matplotlib. (Sudi, 23 July 2010)
+##def newLinePlot(title='Simple Plot'):
+##    import Gnuplot
+##    g = Gnuplot.Gnuplot()
+##    g.title(title)
+##    g('set data style linespoints') 
+##    g.xlabel('x')
+##    g.ylabel('y')
+##    return g
+##
+##def linePlot(g,x,y):
+##    import Gnuplot
+##    g.plot(Gnuplot.PlotItems.Data(x.flat,y.flat))
+
+def newLinePlot(title='Simple Plot'):
+    import pylab as g
+    g.ion()
+    g.hold(False)
+    g.title(title)
+    g.xlabel('x')
+    g.ylabel('y')
+    
+
+def linePlot(x,y):
+    import pylab as g
+    g.plot(x.flat,y.flat)
+
+
+def closePlots():
+    import pylab as g
+    g.close('all')
+    
+if __name__ == "__main__":
+    #from domain import Domain
+    from shallow_water_domain import Domain     
+    from numpy import arange
+    
+    points1 = [0.0, 1.0, 2.0, 3.0]
+    vertex_values = [[1.0,2.0],[4.0,5.0],[-1.0,2.0]]
+
+    D1 = Domain(points1)
+
+    Q1 = Quantity(D1, vertex_values)
+
+    print Q1.vertex_values
+    print Q1.centroid_values
+
+    new_vertex_values = [[2.0,1.0],[3.0,4.0],[-2.0,4.0]]
+
+    Q1.set_values(new_vertex_values)
+
+    print Q1.vertex_values
+    print Q1.centroid_values
+
+    new_centroid_values = [20,30,40]
+    Q1.set_values(new_centroid_values,'centroids')
+
+    print Q1.vertex_values
+    print Q1.centroid_values
+
+    class FunClass:
+        def __init__(self,value):
+            self.value = value
+
+        def __call__(self,x):
+            return self.value*(x**2)
+
+
+    fun = FunClass(1.0)
+    Q1.set_values(fun,'vertices')
+
+    print Q1.vertex_values
+    print Q1.centroid_values
+
+    Xc = Q1.domain.vertices
+    Qc = Q1.vertex_values
+    print Xc
+    print Qc
+
+    Qc[1,0] = 3
+
+    Q1.extrapolate_second_order()
+    #Q1.limit_minmod()
+
+    newLinePlot('plots')
+    linePlot(Xc,Qc)
+    raw_input('press return')
+
+    points2 = arange(10)
+    D2 = Domain(points2)
+
+    Q2 = Quantity(D2)
+    Q2.set_values(fun,'vertices')
+    Xc = Q2.domain.vertices
+    Qc = Q2.vertex_values
+    linePlot(Xc,Qc)
+    raw_input('press return')
+
+    
+    Q2.extrapolate_second_order()
+    #Q2.limit_minmod()
+    Xc = Q2.domain.vertices
+    Qc = Q2.vertex_values
+    print Q2.centroid_values
+    print Qc
+    linePlot(Xc,Qc)
+    raw_input('press return')
+
+
+    for i in range(10):
+        import pylab as g
+        g.hold(True)
+        fun = FunClass(i/10.0)
+        Q2.set_values(fun,'centroids')
+        Q2.extrapolate_second_order()
+        #Q2.limit_minmod()
+        Qc = Q2.vertex_values
+        linePlot(Xc,Qc)
+        raw_input('press return')
+
+    raw_input('press return to quit')
+closePlots()
+"""
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_RUN.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_RUN.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_RUN.py	(revision 7906)
@@ -0,0 +1,107 @@
+import os
+from math import sqrt
+from sww_domain_shv import *
+from Numeric import Float
+from numpy import zeros
+from sf_parameters import *
+
+print "PRINT IT OUT!"
+N = int(N) # number of cells
+print "number of cells=",N
+boundary = {(0,0):'left', (N-1,1): 'right'}
+domain = Domain(points,boundary)
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.cfl = 1.0
+domain.limiter = "minmod"
+
+def stage(x):
+    y=zeros(len(x), Float)
+    for i in range(len(x)):
+        if x[i] < 11.666:
+            y[i] = 0.4125
+        else:
+            y[i] = 0.28 #0.33
+    return y
+domain.set_quantity('stage',stage)
+
+def elevation(x):
+    z_b = zeros(len(x),Float)
+    for i in range(len(x)):
+        if (x[i] >= 8.0) & (x[i] <= 12.0):
+            z_b[i] = 0.2 - 0.05*(x[i]-10.0)**2.0
+        else:
+            z_b[i] = 0.0 
+    return z_b
+domain.set_quantity('elevation',elevation)
+
+### ================ Define the boundary function =========================
+# ['stage', 'xmomentum', 'elevation', 'height', 'velocity']
+D_left = Dirichlet_boundary([0.4125,  0.18,  0.0,  0.4125,  0.18/0.4125])
+D_right = Dirichlet_boundary([0.33,  0.18,  0.0,  0.33,  0.18/0.33])
+domain.set_boundary({'left':D_left,'right':D_right})
+### ================  End of the definition of boundary function ===========
+
+X=domain.vertices
+C=domain.centroids
+import time
+yieldstep=finaltime=10.0
+t0=time.time()
+i=1
+
+while finaltime < 200.1:
+    for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+        domain.write_time()
+    #if t>0.0:
+    N = float(N)
+    StageC = domain.quantities['stage'].centroid_values
+    XmomC = domain.quantities['xmomentum'].centroid_values
+    VelC = domain.quantities['velocity'].centroid_values
+
+    X = domain.vertices
+    StageQ = domain.quantities['stage'].vertex_values
+    XmomQ = domain.quantities['xmomentum'].vertex_values
+    VelQ = domain.quantities['velocity'].vertex_values
+    BedQ = domain.quantities['elevation'].vertex_values
+
+    SD = domain.shock_detector
+        
+    #from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+    import matplotlib
+    matplotlib.use('Agg')
+    import matplotlib.pyplot as plt
+    from matplotlib.pylab import hold
+        
+    hold(False)
+    plt.figure(1)
+        
+    plt.subplot(311)
+    plt.plot(X,StageQ, X,BedQ)
+    #plot1.set_ylim([-1,11])
+    #plot1.set_xlim([0.0,2000.0])
+    #plt.legend(('Numerical solution', 'Bed elevation'),
+    #        'upper left', shadow=False)    
+    #xlabel('Position')
+    plt.ylabel('Stage')
+    
+    plt.subplot(312)
+    plt.plot(points,SD)
+    #plot2.set_xlim([0.0,2000.0])
+    #plt.xlabel('Position')
+    plt.ylabel('Smoothness indicator')
+
+    plt.subplot(313)
+    plt.plot(X,XmomQ)
+    #plot2.set_xlim([0.0,2000.0])
+    plt.xlabel('Position')
+    plt.ylabel('Discharge')
+    
+    #print 'That took %.2f seconds'%(time.time()-t0)
+    print "domain.time=", domain.time
+    auxtime = int(round(domain.time))
+    print "auxtime=", auxtime
+    filename = "%s%02i%s%i" %("shv_nonuniformtime", i, "_", auxtime)
+    plt.savefig(filename)
+    finaltime = finaltime + 10.0
+    i = i + 1
+
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_interactive_RUN.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_interactive_RUN.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_interactive_RUN.py	(revision 7906)
@@ -0,0 +1,98 @@
+import os
+from math import sqrt
+from sww_domain_simplified import *
+from Numeric import Float
+from numpy import zeros
+from sf_parameters import *
+
+N = int(N) # number of cells
+print "number of cells=",N
+boundary = {(0,0):'left', (N-1,1): 'right'}
+domain = Domain(points,boundary)
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.cfl = 1.0
+domain.limiter = "minmod"
+
+def stage(x):
+    y=zeros(len(x), Float)
+    for i in range(len(x)):
+        if x[i] < 11.666:
+            y[i] = 0.4125
+        else:
+            y[i] = 0.33
+    return y
+domain.set_quantity('stage',stage)
+
+def elevation(x):
+    z_b = zeros(len(x),Float)
+    for i in range(len(x)):
+        if (x[i] >= 8.0) & (x[i] <= 12.0):
+            z_b[i] = 0.2 - 0.05*(x[i]-10.0)**2.0
+        else:
+            z_b[i] = 0.0 
+    return z_b
+domain.set_quantity('elevation',elevation)
+
+### ================ Define the boundary function =========================
+# ['stage', 'xmomentum', 'elevation', 'height', 'velocity']
+D_left = Dirichlet_boundary([0.4125,  0.18,  0.0,  0.4125,  0.18/0.4125])
+D_right = Dirichlet_boundary([0.33,  0.18,  0.0,  0.33,  0.18/0.33])
+domain.set_boundary({'left':D_left,'right':D_right})
+### ================  End of the definition of boundary function ===========
+
+X=domain.vertices
+C=domain.centroids
+import time
+yieldstep=finaltime=0.1
+t0=time.time()
+i=1
+
+while finaltime < 0.101:
+    for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+        domain.write_time()
+    finaltime = finaltime + 10.0 
+if t>0.0:
+    N = float(N)
+    StageC = domain.quantities['stage'].centroid_values
+    XmomC = domain.quantities['xmomentum'].centroid_values
+    VelC = domain.quantities['velocity'].centroid_values
+
+    X = domain.vertices
+    StageQ = domain.quantities['stage'].vertex_values
+    XmomQ = domain.quantities['xmomentum'].vertex_values
+    VelQ = domain.quantities['velocity'].vertex_values
+    BedQ = domain.quantities['elevation'].vertex_values
+
+    SD = domain.shock_detector
+
+    from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+    hold(False)
+
+    plot1 = subplot(211)
+    plot(X,StageQ, X,BedQ)
+    #plot1.set_ylim([-1,11])
+    #plot1.set_xlim([0.0,2000.0])
+    legend(('Numerical solution', 'Bed elevation'),
+            'upper left', shadow=False)    
+    #xlabel('Position')
+    ylabel('Stage')
+    
+
+    plot2 = subplot(212)
+    plot(points,SD)
+    #plot2.set_xlim([0.0,2000.0])
+    xlabel('Position')
+    ylabel('Smoothness indicator')
+    
+    print 'That took %.2f seconds'%(time.time()-t0)
+    show()
+        
+    #filename = "%s%04i%s" %("dam_", i, ".eps")
+    #savefig(filename)
+    #finaltime = finaltime + 0.25
+    #print "finaltime=", finaltime
+    #i = i + 1
+    #print "The domain.limiter is", domain.limiter
+    #print 'That took %.2f seconds'%(time.time()-t0)
+    #print '============================================================================='
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_parameters.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_parameters.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sf_parameters.py	(revision 7906)
@@ -0,0 +1,27 @@
+from Numeric import Float, sqrt
+from numpy import zeros
+from config import g
+from scipy import sin, cos, tan, arcsin, arccos, arctan, pi
+
+#h_0 = 5.0
+#h_1 = 10.0
+L=25.0
+N=400
+
+cell_len=L/N
+points=zeros(N+1, Float)
+for i in range(N+1):
+    points[i]=i*cell_len
+    #points[i] = i*cell_len - 0.5*L
+
+
+
+#delt = 0.0
+friction_slope = 0.0#0.05 #tan(delta) #0.05 # NOTE THAT friction_slope must less than bed_slope
+#thet = pi/36.0
+bed_slope = 0.0 #tan(theta) #0.1      # bottom slope, positive if it is increasing bottom.
+thet = arctan(bed_slope)
+
+F2 = g*cos(thet)*cos(thet)*friction_slope
+#c0 = sqrt(g*h_0)   # sound speed
+m = -1.0*g*bed_slope + F2   # auxiliary variable
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sww_domain_shm.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sww_domain_shm.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sww_domain_shm.py	(revision 7906)
@@ -0,0 +1,590 @@
+"""Class Domain -
+1D interval domains for finite-volume computations of
+the shallow water wave equation.
+
+This module contains a specialisation of class Domain from module domain.py
+consisting of methods specific to the Shallow Water Wave Equation
+
+
+U_t + E_x = S
+
+where
+
+U = [w, uh]
+E = [uh, u^2h + gh^2/2]
+S represents source terms forcing the system
+(e.g. gravity, friction, wind stress, ...)
+
+and _t, _x, _y denote the derivative with respect to t, x and y respectiely.
+
+The quantities are
+
+symbol    variable name    explanation
+x         x                horizontal distance from origin [m]
+z         elevation        elevation of bed on which flow is modelled [m]
+h         height           water height above z [m]
+w         stage            absolute water level, w = z+h [m]
+u                          speed in the x direction [m/s]
+uh        xmomentum        momentum in the x direction [m^2/s]
+
+eta                        mannings friction coefficient [to appear]
+nu                         wind stress coefficient [to appear]
+
+The conserved quantities are w, uh
+
+For details see e.g.
+Christopher Zoppou and Stephen Roberts,
+Catastrophic Collapse of Water Supply Reservoirs in Urban Areas,
+Journal of Hydraulic Engineering, vol. 127, No. 7 July 1999
+
+John Jakeman, Ole Nielsen, Stephen Roberts, Duncan Gray, Christopher Zoppou
+Geoscience Australia, 2006
+
+Sudi Mungkasi, ANU, 2010
+"""
+
+
+from domain import *
+Generic_Domain = Domain #Rename
+
+#Shallow water domain
+class Domain(Generic_Domain):
+
+    def __init__(self, coordinates, boundary = None, tagged_elements = None):
+        conserved_quantities = ['stage', 'xmomentum'] #['height', 'xmomentum']
+        evolved_quantities = ['stage', 'xmomentum', 'elevation', 'height', 'velocity']
+        other_quantities = ['friction']
+        Generic_Domain.__init__(self, coordinates, boundary,
+                                conserved_quantities, evolved_quantities, other_quantities,
+                                tagged_elements)
+        
+        from config import minimum_allowed_height, g, h0
+        self.minimum_allowed_height = minimum_allowed_height
+        self.g = g
+        self.h0 = h0
+
+        self.forcing_terms.append(gravity_F2)
+        #self.forcing_terms.append(manning_friction)
+
+        #Realtime visualisation
+        self.visualiser = None
+        self.visualise  = False
+        self.visualise_color_stage = False
+        self.visualise_stage_range = 1.0
+        self.visualise_timer = True
+        self.visualise_range_z = None
+        
+        #Stored output
+        self.store = True
+        self.format = 'sww'
+        self.smooth = True
+
+        #Evolve parametrs
+        self.cfl = 1.0
+        
+        #Reduction operation for get_vertex_values
+        from util import mean
+        self.reduction = mean
+        #self.reduction = min  #Looks better near steep slopes
+
+        self.quantities_to_be_stored = ['stage','xmomentum']
+
+	self.__doc__ = 'sww_domain_shm'
+	self.check_integrity()
+
+
+    def set_quantities_to_be_stored(self, q):
+        """Specify which quantities will be stored in the sww file.
+
+        q must be either:
+          - the name of a quantity
+          - a list of quantity names
+          - None
+
+        In the two first cases, the named quantities will be stored at each
+        yieldstep
+        (This is in addition to the quantities elevation and friction)  
+        If q is None, storage will be switched off altogether.
+        """
+
+        if q is None:
+            self.quantities_to_be_stored = []            
+            self.store = False
+            return
+
+        if isinstance(q, basestring):
+            q = [q] # Turn argument into a list
+
+        #Check correcness    
+        for quantity_name in q:
+            msg = 'Quantity %s is not a valid conserved quantity' %quantity_name
+            assert quantity_name in self.conserved_quantities, msg 
+        
+        self.quantities_to_be_stored = q
+        
+
+    def initialise_visualiser(self,scale_z=1.0,rect=None):
+        #Realtime visualisation
+        if self.visualiser is None:
+            from realtime_visualisation_new import Visualiser
+            self.visualiser = Visualiser(self,scale_z,rect)
+            self.visualiser.setup['elevation']=True
+            self.visualiser.updating['stage']=True
+        self.visualise = True
+        if self.visualise_color_stage == True:
+            self.visualiser.coloring['stage'] = True
+            self.visualiser.qcolor['stage'] = (0.0, 0.0, 0.8)
+        print 'initialise visualiser'
+        print self.visualiser.setup
+        print self.visualiser.updating
+
+    def check_integrity(self):
+        Generic_Domain.check_integrity(self)
+        #Check that we are solving the shallow water wave equation
+
+        msg = 'First conserved quantity must be "stage"'
+        assert self.conserved_quantities[0] == 'stage', msg
+        msg = 'Second conserved quantity must be "xmomentum"'
+        assert self.conserved_quantities[1] == 'xmomentum', msg
+		
+	msg = 'First evolved quantity must be "stage"'
+        assert self.evolved_quantities[0] == 'stage', msg
+        msg = 'Second evolved quantity must be "xmomentum"'
+        assert self.evolved_quantities[1] == 'xmomentum', msg
+        msg = 'Third evolved quantity must be "elevation"'
+        assert self.evolved_quantities[2] == 'elevation', msg
+        msg = 'Fourth evolved quantity must be "height"'
+        assert self.evolved_quantities[3] == 'height', msg
+        msg = 'Fifth evolved quantity must be "velocity"'
+        assert self.evolved_quantities[4] == 'velocity', msg
+
+    def extrapolate_second_order_sw(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        extrapolate_second_order_sw(self)
+
+    def compute_fluxes(self):
+        #Call correct module function(either from this module or C-extension)
+        compute_fluxes_C_wellbalanced(self)
+        #compute_fluxes_C_nonwellbalanced2(self)
+
+    def compute_timestep(self):
+        #Call correct module function
+        compute_timestep(self)
+
+    def distribute_to_vertices_and_edges(self):
+        #Call correct module function(either from this module or C-extension)
+        #distribute_to_vertices_and_edges_shv(self)
+        distribute_to_vertices_and_edges_shm(self)
+        
+    def evolve(self, yieldstep = None, finaltime = None, duration = None, skip_initial_step = False):
+        #Call basic machinery from parent class
+        for t in Generic_Domain.evolve(self, yieldstep, finaltime, duration, skip_initial_step):
+            yield(t)
+
+    def initialise_storage(self):
+        """Create and initialise self.writer object for storing data.
+        Also, save x and bed elevation
+        """
+
+        import data_manager
+
+        #Initialise writer
+        self.writer = data_manager.get_dataobject(self, mode = 'w')
+
+        #Store vertices and connectivity
+        self.writer.store_connectivity()
+
+
+    def store_timestep(self, name):
+        """Store named quantity and time.
+
+        Precondition:
+           self.write has been initialised
+        """
+        self.writer.store_timestep(name)
+
+
+#=============== End of Shallow Water Domain ===============================
+
+# Compute flux definition
+# ###################################
+def compute_fluxes_C_wellbalanced(domain):
+    import sys
+    from Numeric import Float
+    from numpy import zeros   
+    
+    N = domain.number_of_elements
+    timestep = float(sys.maxint)
+    epsilon = domain.epsilon
+    g = domain.g
+    neighbours = domain.neighbours
+    neighbour_vertices = domain.neighbour_vertices
+    normals = domain.normals
+    areas = domain.areas
+    
+    Stage    = domain.quantities['stage']
+    Xmom     = domain.quantities['xmomentum']
+    Bed      = domain.quantities['elevation']
+    Height   = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+
+    stage_boundary_values = Stage.boundary_values
+    xmom_boundary_values  = Xmom.boundary_values
+    bed_boundary_values   = Bed.boundary_values
+    height_boundary_values= Height.boundary_values
+    vel_boundary_values   = Velocity.boundary_values
+    
+    stage_explicit_update = Stage.explicit_update
+    xmom_explicit_update  = Xmom.explicit_update
+    bed_explicit_values   = Bed.explicit_update
+    height_explicit_values= Height.explicit_update
+    vel_explicit_values   = Velocity.explicit_update
+    
+    max_speed_array = domain.max_speed_array
+   
+    domain.distribute_to_vertices_and_edges()
+    domain.update_boundary()
+    
+    stage_V = Stage.vertex_values
+    xmom_V  = Xmom.vertex_values
+    bed_V   = Bed.vertex_values
+    height_V= Height.vertex_values
+    vel_V   = Velocity.vertex_values
+
+    number_of_elements = len(stage_V)
+
+    from comp_flux_ext_wellbalanced import compute_fluxes_ext_wellbalanced
+    domain.flux_timestep = compute_fluxes_ext_wellbalanced(timestep,
+                                  epsilon,
+                                  g,
+                                                           
+                                  neighbours,
+                                  neighbour_vertices,
+                                  normals,
+                                  areas,
+                                                           
+                                  stage_V,
+                                  xmom_V,
+                                  bed_V,
+                                  height_V,
+                                  vel_V,
+                                                           
+                                  stage_boundary_values,
+                                  xmom_boundary_values,
+                                  bed_boundary_values,
+                                  height_boundary_values,
+                                  vel_boundary_values,
+                                                           
+                                  stage_explicit_update,
+                                  xmom_explicit_update,
+                                  bed_explicit_values,
+                                  height_explicit_values,
+                                  vel_explicit_values,
+                                                           
+                                  number_of_elements,
+                                  max_speed_array)
+
+
+# ###################################
+# Module functions for gradient limiting (distribute_to_vertices_and_edges)
+def distribute_to_vertices_and_edges_shv(domain):
+    """Distribution from centroids to vertices specific to the
+    shallow water wave
+    equation.
+
+    It will ensure that h (w-z) is always non-negative even in the
+    presence of steep bed-slopes by taking a weighted average between shallow
+    and deep cases.
+
+    In addition, all conserved quantities get distributed as per either a
+    constant (order==1) or a piecewise linear function (order==2).
+
+    FIXME: more explanation about removal of artificial variability etc
+
+    Precondition:
+      All quantities defined at centroids and bed elevation defined at
+      vertices.
+
+    Postcondition
+      Conserved quantities defined at vertices
+
+    """
+
+    #from config import optimised_gradient_limiter
+
+    #Remove very thin layers of water
+    #protect_against_infinitesimal_and_negative_heights(domain)  
+
+    import sys
+    from Numeric import Float
+    from numpy import zeros    
+    from config import epsilon, h0
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+    #Arrays   
+    w_C   = Stage.centroid_values    
+    uh_C  = Xmom.centroid_values    
+    z_C   = Bed.centroid_values 
+    h_C   = Height.centroid_values
+    u_C   = Velocity.centroid_values
+
+    for i in range(N):
+	h_C[i] = w_C[i] - z_C[i]						
+        if h_C[i] <= epsilon:
+	    uh_C[i] = 0.0
+	    u_C[i] = 0.0
+	    #w_C[i] = z_C[i]
+	else:
+            u_C[i]  = uh_C[i]/(h_C[i] + h0/h_C[i])
+
+    for name in ['stage', 'height', 'velocity']:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            Q.extrapolate_second_order()
+        else:
+            raise 'Unknown order'
+
+    stage_V = domain.quantities['stage'].vertex_values
+    bed_V   = domain.quantities['elevation'].vertex_values
+    h_V     = domain.quantities['height'].vertex_values
+    u_V     = domain.quantities['velocity'].vertex_values		
+    xmom_V  = domain.quantities['xmomentum'].vertex_values 
+
+    bed_V[:] = stage_V - h_V
+    xmom_V[:] = u_V * h_V
+    
+    return
+
+def distribute_to_vertices_and_edges_shm(domain):
+    # shm stands for STAGE, HEIGHT, MOMENTUM
+    """Distribution from centroids to vertices specific to the
+    shallow water wave
+    equation.
+
+    It will ensure that h (w-z) is always non-negative even in the
+    presence of steep bed-slopes by taking a weighted average between shallow
+    and deep cases.
+
+    In addition, all conserved quantities get distributed as per either a
+    constant (order==1) or a piecewise linear function (order==2).
+
+    FIXME: more explanation about removal of artificial variability etc
+
+    Precondition:
+      All quantities defined at centroids and bed elevation defined at
+      vertices.
+
+    Postcondition
+      Conserved quantities defined at vertices
+
+    """
+
+    #from config import optimised_gradient_limiter
+
+    #Remove very thin layers of water
+    #protect_against_infinitesimal_and_negative_heights(domain)  
+
+    import sys
+    from Numeric import Float
+    from numpy import array, zeros
+    from config import epsilon, h0
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+    #Arrays   
+    w_C   = Stage.centroid_values    
+    uh_C  = Xmom.centroid_values    
+    z_C   = Bed.centroid_values 
+    h_C   = Height.centroid_values
+    u_C   = Velocity.centroid_values
+
+    
+    for i in range(N):
+	h_C[i] = w_C[i] - z_C[i]						
+        if h_C[i] <= epsilon:
+	    uh_C[i] = 0.0
+	    u_C[i] = 0.0
+	else:
+            u_C[i] = uh_C[i]/(h_C[i] + h0/h_C[i])
+
+    for name in ['stage', 'height', 'xmomentum']:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            Q.extrapolate_second_order()
+        else:
+            raise 'Unknown order'
+
+    stage_V = domain.quantities['stage'].vertex_values
+    bed_V   = domain.quantities['elevation'].vertex_values
+    h_V     = domain.quantities['height'].vertex_values
+    u_V     = domain.quantities['velocity'].vertex_values		
+    xmom_V  = domain.quantities['xmomentum'].vertex_values 
+
+    bed_V[:] = stage_V - h_V
+
+    for i in range(N):						
+        if min(h_V[i]) <= 0.0:
+	    h_V[i] = array([0.0, 0.0])
+	    stage_V[i] = bed_V[i]
+	    xmom_V[i] = array([0.0, 0.0])
+    
+    u_V[:]  = xmom_V/(h_V + h0/h_V)    
+    
+    return
+
+
+    
+#
+def protect_against_infinitesimal_and_negative_heights(domain):
+    """Protect against infinitesimal heights and associated high velocities
+    """
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    hc = wc - zc  #Water depths at centroids
+
+    zv = domain.quantities['elevation'].vertex_values
+    wv = domain.quantities['stage'].vertex_values
+    hv = wv-zv
+    xmomv = domain.quantities['xmomentum'].vertex_values
+    #remove the above two lines and corresponding code below
+
+    #Update
+    for k in range(domain.number_of_elements):
+
+        if hc[k] < domain.minimum_allowed_height:
+            #Control stage
+            if hc[k] < domain.epsilon:
+                wc[k] = zc[k] # Contain 'lost mass' error
+                wv[k,0] = zv[k,0]
+                wv[k,1] = zv[k,1]
+                
+            xmomc[k] = 0.0
+            
+    
+
+
+
+#########################
+#Standard forcing terms:
+#
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import Float
+    from numpy import zeros, array, sum    
+
+    xmom = domain.quantities['xmomentum'].explicit_update
+    stage = domain.quantities['stage'].explicit_update
+
+    Stage = domain.quantities['stage']
+    Elevation = domain.quantities['elevation']
+    h = Stage.vertex_values - Elevation.vertex_values
+    b = Elevation.vertex_values
+    w = Stage.vertex_values
+
+    x = domain.get_vertex_coordinates()
+    g = domain.g
+
+    for k in range(domain.number_of_elements):
+        avg_h = sum( h[k,:] )/2
+
+        #Compute bed slope
+        x0, x1 = x[k,:]
+        b0, b1 = b[k,:]
+
+        w0, w1 = w[k,:]
+        wx = gradient(x0, x1, w0, w1)
+        bx = gradient(x0, x1, b0, b1)
+        
+        #Update momentum (explicit update is reset to source values)
+        xmom[k] += -g*bx*avg_h
+
+def gravity_F2(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import Float
+    from numpy import zeros, array, sum    
+    from parameters import F2#This is an additional friction!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+    xmom = domain.quantities['xmomentum'].explicit_update
+    stage = domain.quantities['stage'].explicit_update
+
+    Stage = domain.quantities['stage']
+    Elevation = domain.quantities['elevation']
+    h = Stage.vertex_values - Elevation.vertex_values
+    b = Elevation.vertex_values
+    w = Stage.vertex_values
+
+    x = domain.get_vertex_coordinates()
+    g = domain.g
+
+    for k in range(domain.number_of_elements):
+        avg_h = sum( h[k,:] )/2
+
+        #Compute bed slope
+        x0, x1 = x[k,:]
+        b0, b1 = b[k,:]
+
+        w0, w1 = w[k,:]
+        wx = gradient(x0, x1, w0, w1)
+        bx = gradient(x0, x1, b0, b1)
+        
+        #Update momentum (explicit update is reset to source values)
+        xmom[k] += -g*bx*avg_h + avg_h*F2#This is an additional friction!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+ 
+def manning_friction(domain):
+    """Apply (Manning) friction to water momentum
+    """
+
+    from math import sqrt
+
+    w = domain.quantities['stage'].centroid_values
+    z = domain.quantities['elevation'].centroid_values
+    h = w-z
+
+    uh = domain.quantities['xmomentum'].centroid_values
+    eta = domain.quantities['friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+
+    N = domain.number_of_elements
+    eps = domain.minimum_allowed_height
+    g = domain.g
+
+    for k in range(N):
+        if eta[k] >= eps:
+            if h[k] >= eps:
+                S = -g * eta[k]**2 * uh[k]
+            	S /= h[k]**(7.0/3)
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sww_domain_shv.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sww_domain_shv.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/sww_domain_shv.py	(revision 7906)
@@ -0,0 +1,590 @@
+"""Class Domain -
+1D interval domains for finite-volume computations of
+the shallow water wave equation.
+
+This module contains a specialisation of class Domain from module domain.py
+consisting of methods specific to the Shallow Water Wave Equation
+
+
+U_t + E_x = S
+
+where
+
+U = [w, uh]
+E = [uh, u^2h + gh^2/2]
+S represents source terms forcing the system
+(e.g. gravity, friction, wind stress, ...)
+
+and _t, _x, _y denote the derivative with respect to t, x and y respectiely.
+
+The quantities are
+
+symbol    variable name    explanation
+x         x                horizontal distance from origin [m]
+z         elevation        elevation of bed on which flow is modelled [m]
+h         height           water height above z [m]
+w         stage            absolute water level, w = z+h [m]
+u                          speed in the x direction [m/s]
+uh        xmomentum        momentum in the x direction [m^2/s]
+
+eta                        mannings friction coefficient [to appear]
+nu                         wind stress coefficient [to appear]
+
+The conserved quantities are w, uh
+
+For details see e.g.
+Christopher Zoppou and Stephen Roberts,
+Catastrophic Collapse of Water Supply Reservoirs in Urban Areas,
+Journal of Hydraulic Engineering, vol. 127, No. 7 July 1999
+
+John Jakeman, Ole Nielsen, Stephen Roberts, Duncan Gray, Christopher Zoppou
+Geoscience Australia, 2006
+
+Sudi Mungkasi, ANU, 2010
+"""
+
+
+from domain import *
+Generic_Domain = Domain #Rename
+
+#Shallow water domain
+class Domain(Generic_Domain):
+
+    def __init__(self, coordinates, boundary = None, tagged_elements = None):
+        conserved_quantities = ['stage', 'xmomentum'] #['height', 'xmomentum']
+        evolved_quantities = ['stage', 'xmomentum', 'elevation', 'height', 'velocity']
+        other_quantities = ['friction']
+        Generic_Domain.__init__(self, coordinates, boundary,
+                                conserved_quantities, evolved_quantities, other_quantities,
+                                tagged_elements)
+        
+        from config import minimum_allowed_height, g, h0
+        self.minimum_allowed_height = minimum_allowed_height
+        self.g = g
+        self.h0 = h0
+
+        self.forcing_terms.append(gravity_F2)
+        #self.forcing_terms.append(manning_friction)
+
+        #Realtime visualisation
+        self.visualiser = None
+        self.visualise  = False
+        self.visualise_color_stage = False
+        self.visualise_stage_range = 1.0
+        self.visualise_timer = True
+        self.visualise_range_z = None
+        
+        #Stored output
+        self.store = True
+        self.format = 'sww'
+        self.smooth = True
+
+        #Evolve parametrs
+        self.cfl = 1.0
+        
+        #Reduction operation for get_vertex_values
+        from util import mean
+        self.reduction = mean
+        #self.reduction = min  #Looks better near steep slopes
+
+        self.quantities_to_be_stored = ['stage','xmomentum']
+
+	self.__doc__ = 'sww_domain_shv'
+	self.check_integrity()
+
+
+    def set_quantities_to_be_stored(self, q):
+        """Specify which quantities will be stored in the sww file.
+
+        q must be either:
+          - the name of a quantity
+          - a list of quantity names
+          - None
+
+        In the two first cases, the named quantities will be stored at each
+        yieldstep
+        (This is in addition to the quantities elevation and friction)  
+        If q is None, storage will be switched off altogether.
+        """
+
+        if q is None:
+            self.quantities_to_be_stored = []            
+            self.store = False
+            return
+
+        if isinstance(q, basestring):
+            q = [q] # Turn argument into a list
+
+        #Check correcness    
+        for quantity_name in q:
+            msg = 'Quantity %s is not a valid conserved quantity' %quantity_name
+            assert quantity_name in self.conserved_quantities, msg 
+        
+        self.quantities_to_be_stored = q
+        
+
+    def initialise_visualiser(self,scale_z=1.0,rect=None):
+        #Realtime visualisation
+        if self.visualiser is None:
+            from realtime_visualisation_new import Visualiser
+            self.visualiser = Visualiser(self,scale_z,rect)
+            self.visualiser.setup['elevation']=True
+            self.visualiser.updating['stage']=True
+        self.visualise = True
+        if self.visualise_color_stage == True:
+            self.visualiser.coloring['stage'] = True
+            self.visualiser.qcolor['stage'] = (0.0, 0.0, 0.8)
+        print 'initialise visualiser'
+        print self.visualiser.setup
+        print self.visualiser.updating
+
+    def check_integrity(self):
+        Generic_Domain.check_integrity(self)
+        #Check that we are solving the shallow water wave equation
+
+        msg = 'First conserved quantity must be "stage"'
+        assert self.conserved_quantities[0] == 'stage', msg
+        msg = 'Second conserved quantity must be "xmomentum"'
+        assert self.conserved_quantities[1] == 'xmomentum', msg
+		
+	msg = 'First evolved quantity must be "stage"'
+        assert self.evolved_quantities[0] == 'stage', msg
+        msg = 'Second evolved quantity must be "xmomentum"'
+        assert self.evolved_quantities[1] == 'xmomentum', msg
+        msg = 'Third evolved quantity must be "elevation"'
+        assert self.evolved_quantities[2] == 'elevation', msg
+        msg = 'Fourth evolved quantity must be "height"'
+        assert self.evolved_quantities[3] == 'height', msg
+        msg = 'Fifth evolved quantity must be "velocity"'
+        assert self.evolved_quantities[4] == 'velocity', msg
+
+    def extrapolate_second_order_sw(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        extrapolate_second_order_sw(self)
+
+    def compute_fluxes(self):
+        #Call correct module function(either from this module or C-extension)
+        compute_fluxes_C_wellbalanced(self)
+        #compute_fluxes_C_nonwellbalanced2(self)
+
+    def compute_timestep(self):
+        #Call correct module function
+        compute_timestep(self)
+
+    def distribute_to_vertices_and_edges(self):
+        #Call correct module function(either from this module or C-extension)
+        distribute_to_vertices_and_edges_shv(self)
+        #distribute_to_vertices_and_edges_shm(self)
+        
+    def evolve(self, yieldstep = None, finaltime = None, duration = None, skip_initial_step = False):
+        #Call basic machinery from parent class
+        for t in Generic_Domain.evolve(self, yieldstep, finaltime, duration, skip_initial_step):
+            yield(t)
+
+    def initialise_storage(self):
+        """Create and initialise self.writer object for storing data.
+        Also, save x and bed elevation
+        """
+
+        import data_manager
+
+        #Initialise writer
+        self.writer = data_manager.get_dataobject(self, mode = 'w')
+
+        #Store vertices and connectivity
+        self.writer.store_connectivity()
+
+
+    def store_timestep(self, name):
+        """Store named quantity and time.
+
+        Precondition:
+           self.write has been initialised
+        """
+        self.writer.store_timestep(name)
+
+
+#=============== End of Shallow Water Domain ===============================
+
+# Compute flux definition
+# ###################################
+def compute_fluxes_C_wellbalanced(domain):
+    import sys
+    from Numeric import Float
+    from numpy import zeros   
+    
+    N = domain.number_of_elements
+    timestep = float(sys.maxint)
+    epsilon = domain.epsilon
+    g = domain.g
+    neighbours = domain.neighbours
+    neighbour_vertices = domain.neighbour_vertices
+    normals = domain.normals
+    areas = domain.areas
+    
+    Stage    = domain.quantities['stage']
+    Xmom     = domain.quantities['xmomentum']
+    Bed      = domain.quantities['elevation']
+    Height   = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+
+    stage_boundary_values = Stage.boundary_values
+    xmom_boundary_values  = Xmom.boundary_values
+    bed_boundary_values   = Bed.boundary_values
+    height_boundary_values= Height.boundary_values
+    vel_boundary_values   = Velocity.boundary_values
+    
+    stage_explicit_update = Stage.explicit_update
+    xmom_explicit_update  = Xmom.explicit_update
+    bed_explicit_values   = Bed.explicit_update
+    height_explicit_values= Height.explicit_update
+    vel_explicit_values   = Velocity.explicit_update
+    
+    max_speed_array = domain.max_speed_array
+   
+    domain.distribute_to_vertices_and_edges()
+    domain.update_boundary()
+    
+    stage_V = Stage.vertex_values
+    xmom_V  = Xmom.vertex_values
+    bed_V   = Bed.vertex_values
+    height_V= Height.vertex_values
+    vel_V   = Velocity.vertex_values
+
+    number_of_elements = len(stage_V)
+
+    from comp_flux_ext_wellbalanced import compute_fluxes_ext_wellbalanced
+    domain.flux_timestep = compute_fluxes_ext_wellbalanced(timestep,
+                                  epsilon,
+                                  g,
+                                                           
+                                  neighbours,
+                                  neighbour_vertices,
+                                  normals,
+                                  areas,
+                                                           
+                                  stage_V,
+                                  xmom_V,
+                                  bed_V,
+                                  height_V,
+                                  vel_V,
+                                                           
+                                  stage_boundary_values,
+                                  xmom_boundary_values,
+                                  bed_boundary_values,
+                                  height_boundary_values,
+                                  vel_boundary_values,
+                                                           
+                                  stage_explicit_update,
+                                  xmom_explicit_update,
+                                  bed_explicit_values,
+                                  height_explicit_values,
+                                  vel_explicit_values,
+                                                           
+                                  number_of_elements,
+                                  max_speed_array)
+
+
+# ###################################
+# Module functions for gradient limiting (distribute_to_vertices_and_edges)
+def distribute_to_vertices_and_edges_shv(domain):
+    """Distribution from centroids to vertices specific to the
+    shallow water wave
+    equation.
+
+    It will ensure that h (w-z) is always non-negative even in the
+    presence of steep bed-slopes by taking a weighted average between shallow
+    and deep cases.
+
+    In addition, all conserved quantities get distributed as per either a
+    constant (order==1) or a piecewise linear function (order==2).
+
+    FIXME: more explanation about removal of artificial variability etc
+
+    Precondition:
+      All quantities defined at centroids and bed elevation defined at
+      vertices.
+
+    Postcondition
+      Conserved quantities defined at vertices
+
+    """
+
+    #from config import optimised_gradient_limiter
+
+    #Remove very thin layers of water
+    #protect_against_infinitesimal_and_negative_heights(domain)  
+
+    import sys
+    from Numeric import Float
+    from numpy import zeros    
+    from config import epsilon, h0
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+    #Arrays   
+    w_C   = Stage.centroid_values    
+    uh_C  = Xmom.centroid_values    
+    z_C   = Bed.centroid_values 
+    h_C   = Height.centroid_values
+    u_C   = Velocity.centroid_values
+
+    for i in range(N):
+	h_C[i] = w_C[i] - z_C[i]						
+        if h_C[i] <= epsilon:
+	    uh_C[i] = 0.0
+	    u_C[i] = 0.0
+	    #w_C[i] = z_C[i]
+	else:
+            u_C[i]  = uh_C[i]/(h_C[i] + h0/h_C[i])
+
+    for name in ['stage', 'height', 'velocity']:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            Q.extrapolate_second_order()
+        else:
+            raise 'Unknown order'
+
+    stage_V = domain.quantities['stage'].vertex_values
+    bed_V   = domain.quantities['elevation'].vertex_values
+    h_V     = domain.quantities['height'].vertex_values
+    u_V     = domain.quantities['velocity'].vertex_values		
+    xmom_V  = domain.quantities['xmomentum'].vertex_values 
+
+    bed_V[:] = stage_V - h_V
+    xmom_V[:] = u_V * h_V
+    
+    return
+
+def distribute_to_vertices_and_edges_shm(domain):
+    # shm stands for STAGE, HEIGHT, MOMENTUM
+    """Distribution from centroids to vertices specific to the
+    shallow water wave
+    equation.
+
+    It will ensure that h (w-z) is always non-negative even in the
+    presence of steep bed-slopes by taking a weighted average between shallow
+    and deep cases.
+
+    In addition, all conserved quantities get distributed as per either a
+    constant (order==1) or a piecewise linear function (order==2).
+
+    FIXME: more explanation about removal of artificial variability etc
+
+    Precondition:
+      All quantities defined at centroids and bed elevation defined at
+      vertices.
+
+    Postcondition
+      Conserved quantities defined at vertices
+
+    """
+
+    #from config import optimised_gradient_limiter
+
+    #Remove very thin layers of water
+    #protect_against_infinitesimal_and_negative_heights(domain)  
+
+    import sys
+    from Numeric import Float
+    from numpy import array, zeros
+    from config import epsilon, h0
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+    #Arrays   
+    w_C   = Stage.centroid_values    
+    uh_C  = Xmom.centroid_values    
+    z_C   = Bed.centroid_values 
+    h_C   = Height.centroid_values
+    u_C   = Velocity.centroid_values
+
+    
+    for i in range(N):
+	h_C[i] = w_C[i] - z_C[i]						
+        if h_C[i] <= epsilon:
+	    uh_C[i] = 0.0
+	    u_C[i] = 0.0
+	else:
+            u_C[i] = uh_C[i]/(h_C[i] + h0/h_C[i])
+
+    for name in ['stage', 'height', 'xmomentum']:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            Q.extrapolate_second_order()
+        else:
+            raise 'Unknown order'
+
+    stage_V = domain.quantities['stage'].vertex_values
+    bed_V   = domain.quantities['elevation'].vertex_values
+    h_V     = domain.quantities['height'].vertex_values
+    u_V     = domain.quantities['velocity'].vertex_values		
+    xmom_V  = domain.quantities['xmomentum'].vertex_values 
+
+    bed_V[:] = stage_V - h_V
+
+    for i in range(N):						
+        if min(h_V[i]) <= 0.0:
+	    h_V[i] = array([0.0, 0.0])
+	    stage_V[i] = bed_V[i]
+	    xmom_V[i] = array([0.0, 0.0])
+    
+    u_V[:]  = xmom_V/(h_V + h0/h_V)    
+    
+    return
+
+
+    
+#
+def protect_against_infinitesimal_and_negative_heights(domain):
+    """Protect against infinitesimal heights and associated high velocities
+    """
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    hc = wc - zc  #Water depths at centroids
+
+    zv = domain.quantities['elevation'].vertex_values
+    wv = domain.quantities['stage'].vertex_values
+    hv = wv-zv
+    xmomv = domain.quantities['xmomentum'].vertex_values
+    #remove the above two lines and corresponding code below
+
+    #Update
+    for k in range(domain.number_of_elements):
+
+        if hc[k] < domain.minimum_allowed_height:
+            #Control stage
+            if hc[k] < domain.epsilon:
+                wc[k] = zc[k] # Contain 'lost mass' error
+                wv[k,0] = zv[k,0]
+                wv[k,1] = zv[k,1]
+                
+            xmomc[k] = 0.0
+            
+    
+
+
+
+#########################
+#Standard forcing terms:
+#
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import Float
+    from numpy import zeros, array, sum    
+
+    xmom = domain.quantities['xmomentum'].explicit_update
+    stage = domain.quantities['stage'].explicit_update
+
+    Stage = domain.quantities['stage']
+    Elevation = domain.quantities['elevation']
+    h = Stage.vertex_values - Elevation.vertex_values
+    b = Elevation.vertex_values
+    w = Stage.vertex_values
+
+    x = domain.get_vertex_coordinates()
+    g = domain.g
+
+    for k in range(domain.number_of_elements):
+        avg_h = sum( h[k,:] )/2
+
+        #Compute bed slope
+        x0, x1 = x[k,:]
+        b0, b1 = b[k,:]
+
+        w0, w1 = w[k,:]
+        wx = gradient(x0, x1, w0, w1)
+        bx = gradient(x0, x1, b0, b1)
+        
+        #Update momentum (explicit update is reset to source values)
+        xmom[k] += -g*bx*avg_h
+
+def gravity_F2(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import Float
+    from numpy import zeros, array, sum    
+    from parameters import F2#This is an additional friction!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+    xmom = domain.quantities['xmomentum'].explicit_update
+    stage = domain.quantities['stage'].explicit_update
+
+    Stage = domain.quantities['stage']
+    Elevation = domain.quantities['elevation']
+    h = Stage.vertex_values - Elevation.vertex_values
+    b = Elevation.vertex_values
+    w = Stage.vertex_values
+
+    x = domain.get_vertex_coordinates()
+    g = domain.g
+
+    for k in range(domain.number_of_elements):
+        avg_h = sum( h[k,:] )/2
+
+        #Compute bed slope
+        x0, x1 = x[k,:]
+        b0, b1 = b[k,:]
+
+        w0, w1 = w[k,:]
+        wx = gradient(x0, x1, w0, w1)
+        bx = gradient(x0, x1, b0, b1)
+        
+        #Update momentum (explicit update is reset to source values)
+        xmom[k] += -g*bx*avg_h + avg_h*F2#This is an additional friction!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+ 
+def manning_friction(domain):
+    """Apply (Manning) friction to water momentum
+    """
+
+    from math import sqrt
+
+    w = domain.quantities['stage'].centroid_values
+    z = domain.quantities['elevation'].centroid_values
+    h = w-z
+
+    uh = domain.quantities['xmomentum'].centroid_values
+    eta = domain.quantities['friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+
+    N = domain.number_of_elements
+    eps = domain.minimum_allowed_height
+    g = domain.g
+
+    for k in range(N):
+        if eta[k] >= eps:
+            if h[k] >= eps:
+                S = -g * eta[k]**2 * uh[k]
+            	S /= h[k]**(7.0/3)
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/util.py
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/util.py	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/util.py	(revision 7906)
@@ -0,0 +1,175 @@
+"""
+This module contains various auxiliary function used by pyvolution.
+"""
+
+def mean(x):
+    from Numeric import sum
+    return sum(x)/len(x)
+
+
+def gradient(x0, x1, q0, q1):
+
+    if q1-q0 != 0:
+        a = (q1-q0)/(x1-x0)
+    else:
+        a = 0
+        
+    return a
+
+def minmod(beta_p,beta_m):
+    if (abs(beta_p) <= abs(beta_m)) & (beta_p*beta_m > 0.0):
+        phi = beta_p
+    elif (abs(beta_m) < abs(beta_p)) & (beta_p*beta_m > 0.0):
+        phi = beta_m
+    else:
+        phi = 0.0
+    return phi
+
+def minmod_kurganov(a,b,c):
+    from Numeric import sign
+    if sign(a)==sign(b)==sign(c):
+        return sign(a)*min(abs(a),abs(b),abs(c))
+    else:
+        return 0.0
+
+def maxmod(a,b):
+    if (abs(a) >= abs(b)) & (a*b > 0.0):
+        phi = a
+    elif (abs(b) > abs(a)) & (a*b > 0.0):
+        phi = b
+    else:
+        phi = 0.0
+    return phi
+
+def vanleer(a,b):
+    if abs(a)+abs(b) > 1e-12:
+        return (a*abs(b)+abs(a)*b)/(abs(a)+abs(b))
+    else:
+        return 0.0
+
+def vanalbada(a,b):
+    if a*a+b*b > 1e-12:
+        return (a*a*b+a*b*b)/(a*a+b*b)
+    else:
+        return 0.0
+
+def calculate_wetted_area(x1,x2,z1,z2,w1,w2):
+    if (w1 > z1) & (w2 < z2) & (z1 <= z2):
+        x = ((w2-z1)*(x2-x1)+x1*(z2-z1)-x2*(w2-w1))/(z2-z1+w1-w2)
+        A = 0.5*(w1-z1)*(x-x1)
+        L = x-x1
+    elif (w1 < z1) & (w2 > z2) & (z1 < z2):
+        x = ((w2-z1)*(x2-x1)+x1*(z2-z1)-x2*(w2-w1))/(z2-z1+w1-w2)
+        A = 0.5*(w2-z2)*(x2-x)
+        L = x2-x
+    elif (w1 < z1) & (w2 > z2) & (z1 >= z2):
+        x = ((w1-z2)*(x2-x1)+x2*(z2-z1)-x1*(w2-w1))/(z2-z1+w1-w2)
+        A = 0.5*(w2-z2)*(x2-x)
+        L = x2-x
+    elif (w1 > z1) & (w2 < z2) & (z1 > z2):
+        x = ((w1-z2)*(x2-x1)+x2*(z2-z1)-x1*(w2-w1))/(z2-z1+w1-w2)
+        A = 0.5*(w1-z1)*(x-x1)
+        L = x-x1
+    elif (w1 <= z1) & (w2 <= z2):
+        A = 0.0
+    elif (w1 == z1) & (w2 > z2) & (z2 < z1):
+        A = 0.5*(x2-x1)*(w2-z2)
+    elif (w2 == z2) & (w1 > z1) & (z1 < z2):
+        A = 0.5*(x2-x1)*(w1-z1)
+    return A
+
+
+def calculate_new_wet_area(x1,x2,z1,z2,A):
+    from Numeric import sqrt
+    min_centroid_height = 1.0e-3
+    # Assumes reconstructed stage flat in a wetted cell
+    M = (z2-z1)/(x2-x1)
+    L = (x2-x1)
+    min_area = min_centroid_height*L
+    max_area = 0.5*(x2-x1)*abs(z2-z1)
+    if A < max_area:
+        if (z1 < z2):
+            x = sqrt(2*A/M)+x1
+            wet_len = x-x1
+            wc = z1 + sqrt(M*2*A)
+        elif (z2 < z1):
+            x = -sqrt(-2*A/M)+x2
+            wet_len = x2-x 
+            wc = z2+sqrt(-M*2*A)
+        else:
+            wc = A/L+0.5*(z1+z2)
+            wet_len = x2-x1
+    else:
+        wc = 0.5*(z1+z2)+A/L
+        wet_len = x2-x1
+            
+    return wc,wet_len
+
+def calculate_new_wet_area_analytic(x1,x2,z1,z2,A,t):
+    min_centroid_height = 1.0e-3
+    # Assumes reconstructed stage flat in a wetted cell
+    M = (z2-z1)/(x2-x1)
+    L = (x2-x1)
+    min_area = min_centroid_height*L
+    max_area = 0.5*(x2-x1)*abs(z2-z1)
+    w1,uh1 = analytic_cannal(x1,t)
+    w2,uh2 = analytic_cannal(x2,t)
+    if (w1 > z1) & (w2 < z2) & (z1 <= z2):
+        print "test1"
+        x = ((w2-z1)*(x2-x1)+x1*(z2-z1)-x2*(w2-w1))/(z2-z1+w1-w2)
+        wet_len = x-x1
+    elif (w1 < z1) & (w2 > z2) & (z1 < z2):
+        print "test2"
+        x = ((w2-z1)*(x2-x1)+x1*(z2-z1)-x2*(w2-w1))/(z2-z1+w1-w2)
+        wet_len = x2-x
+    elif (w1 < z1) & (w2 > z2) & (z1 >= z2):
+        print "test3"
+        x = ((w1-z2)*(x2-x1)+x2*(z2-z1)-x1*(w2-w1))/(z2-z1+w1-w2)
+        wet_len = x2-x
+    elif (w1 > z1) & (w2 < z2) & (z1 > z2):
+        print "test4"
+        x = ((w1-z2)*(x2-x1)+x2*(z2-z1)-x1*(w2-w1))/(z2-z1+w1-w2)
+        wet_len = x-x1
+    elif (w1 >= z1) & (w2 >= z2):
+        print "test5"
+        wet_len = x2-x1 
+    else: #(w1 <= z1) & (w2 <= z2)
+        print "test5"
+        if (w1 > z1) | (w2 > z2):
+            print "ERROR"
+        wet_len = x2-x1        
+    return w1,w2,wet_len,uh1,uh2
+
+def analytic_cannal(C,t):
+    from Numeric import Float,sqrt,sin,cos
+    from numpy import zeros    
+
+    
+    #N = len(C)
+    #u = zeros(N,Float)    ## water velocity
+    #h = zeros(N,Float)    ## water depth
+    x = C
+    g = 9.81
+
+
+    ## Define Basin Bathymetry
+    #z_b = zeros(N,Float) ## elevation of basin
+    #z = zeros(N,Float)   ## elevation of water surface
+    z_infty = 10.0       ## max equilibrium water depth at lowest point.
+    L_x = 2500.0         ## width of channel
+
+    A0 = 0.5*L_x                  ## determines amplitudes of oscillations
+    omega = sqrt(2*g*z_infty)/L_x ## angular frequency of osccilation
+
+    x1 = A0*cos(omega*t)-L_x # left shoreline
+    x2 = A0*cos(omega*t)+L_x # right shoreline
+    if (x >=x1) & (x <= x2):
+        z_b = z_infty*(x**2/L_x**2) ## or A0*cos(omega*t)\pmL_x
+        u = -A0*omega*sin(omega*t)
+        z = z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x/L_x-0.5*A0/(L_x)*cos(omega*t))
+    else:
+       z_b = z_infty*(x**2/L_x**2)
+       u=0.0
+       z = z_b
+    h = z-z_b
+    return z,u*h
Index: /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/util_ext.h
===================================================================
--- /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/util_ext.h	(revision 7906)
+++ /trunk/anuga_work/development/sudi/sw_1d/shock_detector_shv/util_ext.h	(revision 7906)
@@ -0,0 +1,360 @@
+// Python - C extension for finite_volumes util module.
+//
+// To compile (Python2.3):
+//  gcc -c util_ext.c -I/usr/include/python2.3 -o util_ext.o -Wall -O 
+//  gcc -shared util_ext.o  -o util_ext.so	
+//
+// See the module util.py
+//
+//
+// Ole Nielsen, GA 2004
+	
+#include "Python.h"	
+#include "Numeric/arrayobject.h"
+#include "math.h"
+
+
+double max(double x, double y) {  
+  //Return maximum of two doubles
+  
+  if (x > y) return x;
+  else return y;
+}
+
+
+double min(double x, double y) {  
+  //Return minimum of two doubles
+  
+  if (x < y) return x;
+  else return y;
+}
+
+
+int _gradient(double x0, double y0, 
+	      double x1, double y1, 
+	      double x2, double y2, 
+	      double q0, double q1, double q2, 
+	      double *a, double *b) {
+	      
+  /*Compute gradient (a,b) based on three points (x0,y0), (x1,y1) and (x2,y2) 
+  with values q0, q1 and q2.
+  
+  Extrapolation formula (q0 is selected as an arbitrary origin)
+    q(x,y) = q0 + a*(x-x0) + b*(y-y0)                    (1)
+  
+  Substituting the known values for q1 and q2 into (1) yield the 
+  equations for a and b 
+  
+      q1-q0 = a*(x1-x0) + b*(y1-y0)                      (2)
+      q2-q0 = a*(x2-x0) + b*(y2-y0)                      (3)      
+      
+  or in matrix form
+  
+  /               \  /   \   /       \  
+  |  x1-x0  y1-y0 |  | a |   | q1-q0 |
+  |               |  |   | = |       | 
+  |  x2-x0  y2-y0 |  | b |   | q2-q0 |
+  \               /  \   /   \       /
+   
+  which is solved using the standard determinant technique    
+      
+  */
+	      
+
+  double det;
+  
+  det = (y2-y0)*(x1-x0) - (y1-y0)*(x2-x0);
+
+  *a = (y2-y0)*(q1-q0) - (y1-y0)*(q2-q0);
+  *a /= det;
+
+  *b = (x1-x0)*(q2-q0) - (x2-x0)*(q1-q0);
+  *b /= det;
+
+  return 0;
+}
+
+
+int _gradient2(double x0, double y0, 
+	       double x1, double y1, 
+	       double q0, double q1, 
+	       double *a, double *b) {
+  /*Compute gradient (a,b) between two points (x0,y0) and (x1,y1) 
+  with values q0 and q1 such that the plane is constant in the direction 
+  orthogonal to (x1-x0, y1-y0).
+  
+  Extrapolation formula
+    q(x,y) = q0 + a*(x-x0) + b*(y-y0)                    (1)
+  
+  Substituting the known values for q1 into (1) yields an 
+  under determined  equation for a and b 
+      q1-q0 = a*(x1-x0) + b*(y1-y0)                      (2)
+      
+      
+  Now add the additional requirement that the gradient in the direction 
+  orthogonal to (x1-x0, y1-y0) should be zero. The orthogonal direction 
+  is given by the vector (y0-y1, x1-x0).
+  
+  Define the point (x2, y2) = (x0 + y0-y1, y0 + x1-x0) on the orthognal line. 
+  Then we know that the corresponding value q2 should be equal to q0 in order 
+  to obtain the zero gradient, hence applying (1) again    
+      q0 = q2 = q(x2, y2) = q0 + a*(x2-x0) + b*(y2-y0)
+                          = q0 + a*(x0 + y0-y1-x0) + b*(y0 + x1-x0 - y0)
+			  = q0 + a*(y0-y1) + b*(x1-x0)
+			  
+  leads to the orthogonality constraint
+     a*(y0-y1) + b*(x1-x0) = 0                           (3) 
+     
+  which closes the system and yields
+  
+  /               \  /   \   /       \  
+  |  x1-x0  y1-y0 |  | a |   | q1-q0 |
+  |               |  |   | = |       | 
+  |  y0-y1  x1-x0 |  | b |   |   0   |
+  \               /  \   /   \       /
+   
+  which is solved using the standard determinant technique    
+      
+  */
+
+  double det, xx, yy, qq;
+  
+  xx = x1-x0;
+  yy = y1-y0;
+  qq = q1-q0;
+    
+  det = xx*xx + yy*yy;  //FIXME  catch det == 0
+  *a = xx*qq/det;
+  *b = yy*qq/det;
+        
+  return 0;
+}
+
+
+void _limit_old(int N, double beta, double* qc, double* qv, 
+	    double* qmin, double* qmax) { 
+
+  //N are the number of elements
+  int k, i, k3;
+  double dq, dqa[3], phi, r;
+  
+  //printf("INSIDE\n");
+  for (k=0; k<N; k++) {
+    k3 = k*3;
+    
+    //Find the gradient limiter (phi) across vertices  
+    phi = 1.0;
+    for (i=0; i<3; i++) {    
+      r = 1.0;
+      
+      dq = qv[k3+i] - qc[k];    //Delta between vertex and centroid values
+      dqa[i] = dq;              //Save dq for use in the next loop
+      
+      if (dq > 0.0) r = (qmax[k] - qc[k])/dq;
+      if (dq < 0.0) r = (qmin[k] - qc[k])/dq;      
+  
+  
+      phi = min( min(r*beta, 1.0), phi);    
+    }
+    
+    //Then update using phi limiter
+    for (i=0; i<3; i++) {    
+      qv[k3+i] = qc[k] + phi*dqa[i];
+    }
+  }
+}
+
+
+void  print_double_array(char* name, double* array, int n, int m){
+
+    int k,i,km;
+
+    printf("%s = [",name);
+    for (k=0; k<n; k++){
+	km = m*k;
+	printf("[");
+	for (i=0; i<m ; i++){
+	    printf("%g ",array[km+i]);
+	}
+	if (k==(n-1))
+	    printf("]");
+	else
+	    printf("]\n");
+    }
+    printf("]\n");
+}
+
+void  print_int_array(char* name, int* array, int n, int m){
+
+    int k,i,km;
+
+    printf("%s = [",name);
+    for (k=0; k<n; k++){
+	km = m*k;
+	printf("[");
+	for (i=0; i<m ; i++){
+	    printf("%i ",array[km+i]);
+	}
+	if (k==(n-1))
+	    printf("]");
+	else
+	    printf("]\n");
+    }
+    printf("]\n");
+}
+
+
+void  print_long_array(char* name, long* array, int n, int m){
+
+    int k,i,km;
+
+    printf("%s = [",name);
+    for (k=0; k<n; k++){
+	km = m*k;
+	printf("[");
+	for (i=0; i<m ; i++){
+	  printf("%i ",(int) array[km+i]);
+	}
+	if (k==(n-1))
+	    printf("]");
+	else
+	    printf("]\n");
+    }
+    printf("]\n");
+}
+
+void print_numeric_array(PyArrayObject *x) {  
+  int i, j;
+  for (i=0; i<x->dimensions[0]; i++) {  
+    for (j=0; j<x->dimensions[1]; j++) {
+      printf("%f ", *(double*) (x->data + i*x->strides[0] + j*x->strides[1]));
+    }
+    printf("\n");  
+  }
+  printf("\n");    
+}
+
+void print_numeric_vector(PyArrayObject *x) {  
+  int i;
+  for (i=0; i<x->dimensions[0]; i++) {
+    printf("%f ", *(double*) (x->data + i*x->strides[0]));  
+  }
+  printf("\n");  
+}
+
+PyArrayObject *get_consecutive_array(PyObject *O, char *name) {
+  PyArrayObject *A, *B;
+  
+
+  //Get array object from attribute
+  
+  /*
+  //FIXME: THE TEST DOESN't WORK
+  printf("Err = %d\n", PyObject_HasAttrString(O, name));
+  if (PyObject_HasAttrString(O, name) == 1) {
+    B = (PyArrayObject*) PyObject_GetAttrString(O, name);
+    if (!B) return NULL;
+  } else {
+    return NULL;
+    } 
+  */
+    
+  B = (PyArrayObject*) PyObject_GetAttrString(O, name);
+
+  //printf("B = %p\n",(void*)B);
+  if (!B) {
+    printf("util_ext.h: get_consecutive_array could not obtain python object");
+    printf(" %s\n",name);
+    fflush(stdout);
+    PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_consecutive_array could not obtain python object");
+    return NULL;
+  }     
+  
+  //Convert to consecutive array
+  A = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*) B, 
+						    B -> descr -> type, 0, 0);
+  
+  Py_DECREF(B); //FIXME: Is this really needed??
+  
+  if (!A) {
+    printf("util_ext.h: get_consecutive_array could not obtain array object");
+    printf(" %s \n",name);
+    fflush(stdout);
+    PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_consecutive_array could not obtain array");
+    return NULL;
+  }
+
+
+  return A;
+}
+
+
+
+double get_python_double(PyObject *O, char *name) {
+  PyObject *TObject;
+  #define BUFFER_SIZE 80
+  char buf[BUFFER_SIZE];
+  double tmp;
+  int n;
+  
+
+  //Get double from attribute
+  TObject = PyObject_GetAttrString(O, name);
+  if (!TObject) {
+	n =  snprintf(buf, BUFFER_SIZE, "util_ext.h: get_python_double could not obtain double %s.\n", name);
+	//printf("name = %s",name);
+    PyErr_SetString(PyExc_RuntimeError, buf);
+
+    return 0.0;
+  }  
+  
+  tmp = PyFloat_AsDouble(TObject);
+  
+  Py_DECREF(TObject);
+  
+  return tmp;
+}
+
+
+
+
+int get_python_integer(PyObject *O, char *name) {
+  PyObject *TObject;
+  #define BUFFER_SIZE 80
+  char buf[BUFFER_SIZE];
+  long tmp;
+  int n;
+  
+
+  //Get double from attribute
+  TObject = PyObject_GetAttrString(O, name);
+  if (!TObject) {
+  	n =  snprintf(buf, BUFFER_SIZE, "util_ext.h: get_python_integer could not obtain double %s.\n", name);
+	//printf("name = %s",name);
+    PyErr_SetString(PyExc_RuntimeError, buf);
+    return 0;
+  }  
+  
+  tmp = PyInt_AsLong(TObject);
+  
+  Py_DECREF(TObject);
+  
+  return tmp;
+}
+
+
+PyObject *get_python_object(PyObject *O, char *name) {
+  PyObject *Oout;
+
+  Oout = PyObject_GetAttrString(O, name);
+  if (!Oout) {
+    PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_python_object could not obtain object");
+    return NULL;
+  }
+
+  return Oout;
+
+}
+
+
+
