Index: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/comp_flux_ext_wellbalanced.c
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/comp_flux_ext_wellbalanced.c	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/comp_flux_ext_wellbalanced.c	(revision 7837)
@@ -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: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/config.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/config.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/config.py	(revision 7837)
@@ -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: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/debris_avalanche_RUN.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/debris_avalanche_RUN.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/debris_avalanche_RUN.py	(revision 7837)
@@ -0,0 +1,178 @@
+import os
+import time
+from shallow_water_domain_avalanche import *
+from Numeric import array, zeros, Float, sqrt
+from config import g, epsilon
+from numpy import sin, cos, tan
+from scipy import linspace
+from parameters import *
+
+def analytical_sol(X,t):
+    N = len(X)
+    u = zeros(N,Float)
+    h = zeros(N,Float)
+    w = zeros(N,Float)
+    z = zeros(N,Float)
+    mom = zeros(N,Float)
+    for i in range(N):
+        # Calculate Analytical Solution at time t > 0
+        if X[i] <= -2.0*c0*t + 0.5*m*t**2.0:
+            u[i] = 0.0
+            h[i] = 0.0
+        elif X[i] <= c0*t + 0.5*m*t**2.0:
+            u[i] = 2.0/3.0 * (X[i]/t - c0 + m*t)
+            h[i] = 1.0/(9.0*g) * (X[i]/t + 2.0*c0 - 0.5*m*t)**2.0
+        else:
+            u[i] = m*t
+            h[i] = h_0
+        z[i] = bed_slope*X[i]
+        w[i] = h[i] + z[i]
+        mom[i] = u[i]*h[i]
+    return u,h,w,z,mom
+
+def height(X):
+    N = len(X)
+    y = zeros(N,Float)
+    for i in range(N):
+        if X[i]<=0.0:
+            y[i] = 0.0
+        else:
+            y[i] = h_0
+    return y
+
+def stage(X):
+    N = len(X)
+    w = zeros(N,Float)
+    for i in range(N):
+        if X[i]<=0.0:
+            w[i] = bed_slope*X[i]
+        else:
+            w[i] = bed_slope*X[i] + h_0
+    return w        
+
+def elevation(X):
+    N = len(X)
+    y=zeros(N, Float)
+    for i in range(N):
+        y[i] = bed_slope*X[i]
+    return y
+"""
+#=========================================================================#
+#The following values are set in parameters.py
+h_0 = 10.0         # depth upstream. Note that the depth downstream is 0.0
+L = 2000.0         # length of stream/domain
+n = 100             # number of cells
+cell_len = L/n     # length of each cell
+points = zeros(n+1, Float)
+for i in range (n+1):
+    points[i] = i*cell_len - 0.5*L
+
+bed_slope = 0.005      # bottom slope, positive if it is increasing bottom.
+c0 = sqrt(g*h_0)   # sound speed
+m = -1.0*g*bed_slope   # auxiliary variable
+#==========================================================================#
+"""
+boundary = { (0,0): 'left',(n-1,1): 'right'}
+domain = Domain(points,boundary)
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.beta = 1.0
+domain.set_limiter("minmod")
+
+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)
+#T_right = Transmissive_boundary(domain)
+#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])
+domain.set_boundary({'left':D_left,'right':T_right})
+domain.set_quantity('stage',stage)
+domain.set_quantity('elevation',elevation)
+
+X = domain.vertices
+C = domain.centroids
+
+yieldstep = finaltime = 15.0
+t0 = time.time()
+
+while finaltime <= 15.1:
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        domain.write_time()
+        
+    #The following is for computing the error and plotting the result
+    Mom = domain.quantities['xmomentum']
+    Height = domain.quantities['height']
+    Stage = domain.quantities['stage']
+    Velocity = domain.quantities['velocity']
+    Elevation = domain.quantities['elevation']
+
+    #The following is for computing the error
+    Uc,Hc,Wc,Zc,Mc = analytical_sol(C,domain.time)
+    HeightC = Height.centroid_values
+    MomC = Mom.centroid_values
+    StageC = Stage.centroid_values
+    VelC = Velocity.centroid_values
+    ElevationC = Elevation.centroid_values
+
+    print "number of cells=",n
+    W_error = (1.0/n)*sum(abs(Wc-StageC))
+    M_error = (1.0/n)*sum(abs(Mc-MomC))
+    U_error = (1.0/n)*sum(abs(Uc-VelC))
+    print "stage_error %.10f" %(W_error)
+    print "momentum_error %.10f"%(M_error)
+    print "velocity_error %.10f" %(U_error)
+
+
+    #The following is for plotting the result.
+    Uv,Hv,Wv,Zv,Mv = analytical_sol(X.flat,domain.time)
+    HeightV = Height.vertex_values
+    MomV = Mom.vertex_values
+    StageV = Stage.vertex_values
+    VelV = Velocity.vertex_values
+    ElevationV = Elevation.vertex_values
+    from pylab import clf,plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+    hold(False)
+    clf()
+
+    plot1 = subplot(311)
+    plot(X.flat,Wv,'b-', X.flat,StageV.flat,'k--', X.flat,ElevationV.flat,'k:')
+    #plot(X.flat,Wv, X.flat,StageV.flat, X.flat,ElevationV.flat)    
+    #xlabel('Position')
+    ylabel('Stage')
+    #plot1.set_ylim([-1.0,21.0])
+    #plot1.set_xlim([-480.0,-420.0])#([-9.0e-3,9.0e-3])
+    #legend(('analytical solution', 'numerical solution', 'discretized bed'), 'upper left', shadow=False)
+    
+    plot2 = subplot(312)
+    plot(X.flat,Mv,'b-', X.flat,MomV.flat,'k--')
+    #xlabel('Position')
+    ylabel('Momentum')
+    #plot2.set_xlim([-300.0,300.0])
+    plot2.set_ylim([-310.0,10.0])#([-90.0,10.0])
+    #legend(('analytical solution', 'numerical solution'), 'lower right', shadow=False)    
+
+    plot3 = subplot(313)
+    plot(X.flat,Uv,'b-', X.flat,VelV.flat,'k--')
+    xlabel('Position')
+    ylabel('Velocity')
+    #plot3.set_xlim([-300.0,300.0])
+    plot3.set_ylim([-45.0,5.0])#([-30.0,5.0])
+    #legend(('analytical solution', 'numerical solution'), 'lower right', shadow=False)
+    
+    finaltime = finaltime + 10.0
+
+    file = "A-case3-"
+    file += str(n)
+    file += ".eps"
+    savefig(file)      
+    
+    show()
+
+
Index: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/desktop.ini
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/desktop.ini	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/desktop.ini	(revision 7837)
@@ -0,0 +1,4 @@
+[ViewState]
+Mode=
+Vid=
+FolderType=Documents
Index: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/domain.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/domain.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/domain.py	(revision 7837)
@@ -0,0 +1,1386 @@
+"""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 array, zeros, Float, Int
+
+        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
+
+    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 Numeric 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 array, Int
+
+        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 Numeric 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 zeros, Float
+        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 zeros, Float
+        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:
+                # 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
+                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
+
+
+    def evolve_one_euler_step(self, yieldstep, finaltime):
+        """
+        One Euler Time Step
+        Q^{n+1} = E(h) Q^n
+        """
+
+
+        # 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
+        
+
+
+    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()            
+
+        #--------------------------------------
+        # 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()   
+
+
+
+    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()            
+
+        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       
+        
+
+    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 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 zeros,Float
+
+        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 zeros,Float
+
+        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]
+        
+        """
+        ################
+        n = len(self.quantities['stage'].vertex_values)
+        self.quantities['stage'].vertex_values[n-1,0]     = self.quantities['stage'].centroid_values[n-1]
+        self.quantities['xmomentum'].vertex_values[n-1,0] = self.quantities['xmomentum'].centroid_values[n-1]
+        self.quantities['elevation'].vertex_values[n-1,0] = self.quantities['elevation'].centroid_values[n-1]
+        self.quantities['height'].vertex_values[n-1,0]    = self.quantities['height'].centroid_values[n-1]
+        self.quantities['velocity'].vertex_values[n-1,0]  = self.quantities['velocity'].centroid_values[n-1]
+
+        self.quantities['stage'].vertex_values[n-1,1]     = self.quantities['stage'].centroid_values[n-1]
+        self.quantities['xmomentum'].vertex_values[n-1,1] = self.quantities['xmomentum'].centroid_values[n-1]
+        self.quantities['elevation'].vertex_values[n-1,1] = self.quantities['elevation'].centroid_values[n-1]
+        self.quantities['height'].vertex_values[n-1,1]    = self.quantities['height'].centroid_values[n-1]
+        self.quantities['velocity'].vertex_values[n-1,1]  = self.quantities['velocity'].centroid_values[n-1]
+        """
+        
+    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 ones, sum, equal, Float
+
+        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: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/generic_boundary_conditions.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/generic_boundary_conditions.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/generic_boundary_conditions.py	(revision 7837)
@@ -0,0 +1,548 @@
+"""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 zeros, Float
+        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 array, Float
+        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 array, Float
+        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 Numeric 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 array, zeros, Float
+        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 Numeric 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 zeros, Float, 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: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/parameters.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/parameters.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/parameters.py	(revision 7837)
@@ -0,0 +1,21 @@
+from Numeric import zeros, Float, sqrt
+from config import g
+from scipy import sin, cos, tan, arcsin, arccos, arctan, pi
+
+h_0 = 20.0         # depth upstream. Note that the depth downstream is 0.0
+L = 2000.0         # length of stream/domain
+n = 800            # number of cells
+cell_len = L/n     # length of each cell
+points = zeros(n+1, Float)
+for i in range (n+1):
+    points[i] = i*cell_len - 0.5*L
+
+
+friction_slope = 0.05 #tan(delt) #0.05 # NOTE THAT friction_slope must less than bed_slope
+bed_slope = 0.1 #tan(thet) #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: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/quantity.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/quantity.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/quantity.py	(revision 7837)
@@ -0,0 +1,1038 @@
+"""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 array, zeros, Float
+
+        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 zeros, Float
+        
+        #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 array, Float
+
+        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 concatenate, zeros, Float, Int, 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 sum, equal, ones, Float
+
+        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 array, zeros, Float
+
+        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 array, zeros, Float,sign
+        
+        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 zeros, Float
+
+        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 zeros, Float
+        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 zeros, Float
+        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"
+
+
+##
+##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 Numeric 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: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/shallow_water_domain_avalanche.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/shallow_water_domain_avalanche.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/shallow_water_domain_avalanche.py	(revision 7837)
@@ -0,0 +1,1277 @@
+"""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
+"""
+
+
+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)  #gravity, gravity_F1, 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__ = 'shallow_water_domain_avalanche'
+	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 ===============================
+
+#Rotation of momentum vector
+def rotate(q, normal, direction = 1):
+    """Rotate the momentum component q (q[1], q[2])
+    from x,y coordinates to coordinates based on normal vector.
+
+    If direction is negative the rotation is inverted.
+
+    Input vector is preserved
+
+    This function is specific to the shallow water wave equation
+    """
+
+    from Numeric import zeros, Float
+
+    assert len(q) == 3,\
+           'Vector of conserved quantities must have length 3'\
+           'for 2D shallow water equation'
+
+    try:
+        l = len(normal)
+    except:
+        raise 'Normal vector must be an Numeric array'
+
+    assert l == 2, 'Normal vector must have 2 components'
+
+
+    n1 = normal[0]
+    n2 = normal[1]
+
+    r = zeros(len(q), Float) #Rotated quantities
+    r[0] = q[0]              #First quantity, height, is not rotated
+
+    if direction == -1:
+        n2 = -n2
+
+
+    r[1] =  n1*q[1] + n2*q[2]
+    r[2] = -n2*q[1] + n1*q[2]
+
+    return r
+
+
+def flux_function(normal, ql, qr, zl, zr):
+    """Compute fluxes between volumes for the shallow water wave equation
+    cast in terms of w = h+z using the 'central scheme' as described in
+
+    Kurganov, Noelle, Petrova. 'Semidiscrete Central-Upwind Schemes For
+    Hyperbolic Conservation Laws and Hamilton-Jacobi Equations'.
+    Siam J. Sci. Comput. Vol. 23, No. 3, pp. 707-740.
+
+    The implemented formula is given in equation (3.15) on page 714
+
+    Conserved quantities w, uh, are stored as elements 0 and 1
+    in the numerical vectors ql an qr.
+
+    Bed elevations zl and zr.
+    """
+
+    from config import g, epsilon, h0
+    from math import sqrt
+    from Numeric import array
+
+    #Align momentums with x-axis
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+	
+    z = 0.5*(zl+zr) #Take average of field values
+
+    w_left  = q_left[0]   #w=h+z
+    h_left  = w_left-z
+    uh_left = q_left[1]
+
+    if h_left < epsilon:
+        u_left = 0.0  #Could have been negative
+        h_left = 0.0
+    else:
+        u_left  = uh_left/(h_left +  h0/h_left)
+
+
+    uh_left = u_left*h_left
+
+
+    w_right  = q_right[0]  #w=h+z
+    h_right  = w_right-z
+    uh_right = q_right[1]
+
+    if h_right < epsilon:
+        u_right = 0.0  #Could have been negative
+        h_right = 0.0
+    else:
+        u_right  = uh_right/(h_right + h0/h_right)
+
+    uh_right = u_right*h_right
+	
+
+    #We have got h and u at vertex, then the following is the calculation of fluxes!
+    soundspeed_left  = sqrt(g*h_left)
+    soundspeed_right = sqrt(g*h_right)
+
+    #Maximal wave speed
+    s_max = max(u_left+soundspeed_left, u_right+soundspeed_right, 0)
+    
+    #Minimal wave speed
+    s_min = min(u_left-soundspeed_left, u_right-soundspeed_right, 0)
+    
+    #Flux computation
+    flux_left  = array([u_left*h_left,
+                        u_left*uh_left + 0.5*g*h_left*h_left])
+    flux_right = array([u_right*h_right,
+                        u_right*uh_right + 0.5*g*h_right*h_right])
+
+    denom = s_max-s_min
+    if denom == 0.0:
+        edgeflux = array([0.0, 0.0])
+        max_speed = 0.0
+    else:
+        edgeflux = (s_max*flux_left - s_min*flux_right)/denom
+        edgeflux += s_max*s_min*(q_right-q_left)/denom
+        
+        edgeflux[1] = edgeflux[1]*normal
+
+        max_speed = max(abs(s_max), abs(s_min))
+
+    return edgeflux, max_speed
+
+#
+def compute_timestep(domain):
+    import sys
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    
+    stage = Stage.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+
+    stage_bdry = Stage.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+
+    flux = zeros(2, Float) #Work array for summing up fluxes
+    ql = zeros(2, Float)
+    qr = zeros(2, Float)
+
+    #Loop
+    timestep = float(sys.maxint)
+    enter = True
+    for k in range(N):
+
+        flux[:] = 0.  #Reset work array
+        for i in range(2):
+            #Quantities inside volume facing neighbour i
+            ql = [stage[k, i], xmom[k, i]]
+            zl = bed[k, i]
+
+            #Quantities at neighbour on nearest face
+            n = domain.neighbours[k,i]
+            if n < 0:
+                m = -n-1 #Convert negative flag to index
+                qr[0] = stage_bdry[m]
+                qr[1] = xmom_bdry[m]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                m = domain.neighbour_vertices[k,i]
+                qr[0] = stage[n, m]
+                qr[1] =  xmom[n, m]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+
+            edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+
+            #Update optimal_timestep
+            try:
+                timestep = min(timestep, domain.cfl*0.5*domain.areas[k]/max_speed)
+            except ZeroDivisionError:
+                pass
+
+    domain.timestep = timestep
+
+# Compute flux definition
+# ###################################
+def compute_fluxes_C_wellbalanced(domain):
+    import sys
+    from Numeric import zeros, Float
+    
+    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)
+
+
+def compute_fluxes_C_nonwellbalanced2(domain):
+    import sys
+    from Numeric import zeros, Float
+    
+    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_nonwellbalanced2 import compute_fluxes_ext_nonwellbalanced2
+    domain.flux_timestep = compute_fluxes_ext_nonwellbalanced2(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 zeros, Float
+    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 zeros, Float
+    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] <= 0.01:  #epsilon :
+	    #h_C[i] = 0.0
+	    #w_C[i] = z_C[i]
+	    uh_C[i] = 0.0
+	    u_C[i] = 0.0
+	    
+	if h_C[i] < epsilon:
+            h_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', '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 h_V[i] <= 0.0:
+	    h_V[i] = 0.0
+	    stage_V[i] = bed_V[i]
+	    xmom_V[i] = 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
+            
+    
+def h_limiter(domain):
+    """Limit slopes for each volume to eliminate artificial variance
+    introduced by e.g. second order extrapolator
+
+    limit on h = w-z
+
+    This limiter depends on two quantities (w,z) so it resides within
+    this module rather than within quantity.py
+    """
+
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+    beta_h = domain.beta_h
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = wc - zc
+
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = wv-zv
+
+    hvbar = zeros(hv.shape, Float) #h-limited values
+
+    #Find min and max of this and neighbour's centroid values
+    hmax = zeros(hc.shape, Float)
+    hmin = zeros(hc.shape, Float)
+
+    for k in range(N):
+        hmax[k] = hmin[k] = hc[k]
+        for i in range(2):   
+            n = domain.neighbours[k,i]
+            if n >= 0:
+                hn = hc[n] #Neighbour's centroid value
+
+                hmin[k] = min(hmin[k], hn)
+                hmax[k] = max(hmax[k], hn)
+
+
+    #Diffences between centroids and maxima/minima
+    dhmax = hmax - hc
+    dhmin = hmin - hc
+
+    #Deltas between vertex and centroid values
+    dh = zeros(hv.shape, Float)
+    for i in range(2):
+        dh[:,i] = hv[:,i] - hc
+
+    #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 (dh[k,i] > 0): r = dhmax[k]/dh[k,i]
+            if (dh[k,i] < 0): r = dhmin[k]/dh[k,i]
+
+            phi = min( min(r*beta_h, 1), phi )
+
+        #Then update using phi limiter
+        for i in range(2):
+            hvbar[k,i] = hc[k] + phi*dh[k,i]
+
+    return hvbar
+
+def balance_deep_and_shallow(domain):
+    """Compute linear combination between stage as computed by
+    gradient-limiters limiting using w, and stage computed by
+    gradient-limiters limiting using h (h-limiter).
+    The former takes precedence when heights are large compared to the
+    bed slope while the latter takes precedence when heights are
+    relatively small.  Anything in between is computed as a balanced
+    linear combination in order to avoid numerical disturbances which
+    would otherwise appear as a result of hard switching between
+    modes.
+
+    The h-limiter is always applied irrespective of the order.
+    """
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = wc - zc
+
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = wv-zv
+
+    #Limit h
+    hvbar = h_limiter(domain)
+
+    for k in range(domain.number_of_elements):
+        #Compute maximal variation in bed elevation
+        #  This quantitiy is
+        #    dz = max_i abs(z_i - z_c)
+        #  and it is independent of dimension
+        #  In the 1d case zc = (z0+z1)/2
+        #  In the 2d case zc = (z0+z1+z2)/3
+
+        dz = max(abs(zv[k,0]-zc[k]),
+                 abs(zv[k,1]-zc[k]))#,
+#                 abs(zv[k,2]-zc[k]))
+
+
+        hmin = min( hv[k,:] )
+
+        #Create alpha in [0,1], where alpha==0 means using the h-limited
+        #stage and alpha==1 means using the w-limited stage as
+        #computed by the gradient limiter (both 1st or 2nd order)
+
+        #If hmin > dz/2 then alpha = 1 and the bed will have no effect
+        #If hmin < 0 then alpha = 0 reverting to constant height above bed.
+
+        if dz > 0.0:
+            alpha = max( min( 2*hmin/dz, 1.0), 0.0 )
+        else:
+            #Flat bed
+            alpha = 1.0
+
+        alpha  = 0.0
+	#Let
+	#
+	#  wvi be the w-limited stage (wvi = zvi + hvi)
+	#  wvi- be the h-limited state (wvi- = zvi + hvi-)
+	#
+	#
+	#where i=0,1,2 denotes the vertex ids
+	#
+        #Weighted balance between w-limited and h-limited stage is
+        #
+	#  wvi := (1-alpha)*(zvi+hvi-) + alpha*(zvi+hvi)
+	#
+        #It follows that the updated wvi is
+        #  wvi := zvi + (1-alpha)*hvi- + alpha*hvi
+        #
+	# Momentum is balanced between constant and limited
+
+
+        #for i in range(3):
+        #    wv[k,i] = zv[k,i] + hvbar[k,i]
+
+	#return
+
+	if alpha < 1:
+
+            #for i in range(3):
+            for i in range(2):
+                wv[k,i] = zv[k,i] + (1.0-alpha)*hvbar[k,i] + alpha*hv[k,i]
+
+            #Momentums at centroids
+            xmomc = domain.quantities['xmomentum'].centroid_values
+
+
+            #Momentums at vertices
+            xmomv = domain.quantities['xmomentum'].vertex_values
+
+
+            # Update momentum as a linear combination of
+            # xmomc and ymomc (shallow) and momentum
+            # from extrapolator xmomv and ymomv (deep).
+            xmomv[k,:] = (1.0-alpha)*xmomc[k] + alpha*xmomv[k,:]
+
+
+
+
+
+#########################
+#Standard forcing terms:
+#
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import zeros, Float, 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_F1(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import zeros, Float, array, sum
+    from parameters import F1#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*F1#This is an additional friction!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+
+
+def gravity_F2(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import zeros, Float, 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]
+
+def linear_friction(domain):
+    """Apply linear friction to water momentum
+
+    Assumes quantity: 'linear_friction' to be present
+    """
+
+    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
+    tau = domain.quantities['linear_friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+
+    N = domain.number_of_elements
+    eps = domain.minimum_allowed_height
+    g = domain.g #Not necessary? Why was this added?
+
+    for k in range(N):
+        if tau[k] >= eps:
+            if h[k] >= eps:
+            	S = -tau[k]/h[k]
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
+
+
+
+def check_forcefield(f):
+    """Check that f is either
+    1: a callable object f(t,x,y), where x and y are vectors
+       and that it returns an array or a list of same length
+       as x and y
+    2: a scalar
+    """
+
+    from Numeric import ones, Float, array
+
+
+    if callable(f):
+        N = 2
+        x = ones(2, Float)
+        
+        try:
+            q = f(1.0, x=x)
+        except Exception, e:
+            msg = 'Function %s could not be executed:\n%s' %(f, e)
+	    #FIXME: Reconsider this semantics
+            raise msg
+
+        try:
+            q = array(q).astype(Float)
+        except:
+            msg = 'Return value from vector function %s could ' %f
+            msg += 'not be converted into a Numeric array of floats.\n'
+            msg += 'Specified function should return either list or array.'
+            raise msg
+
+        #Is this really what we want?
+        msg = 'Return vector from function %s ' %f
+        msg += 'must have same lenght as input vectors'
+        assert len(q) == N, msg
+
+    else:
+        try:
+            f = float(f)
+        except:
+            msg = 'Force field %s must be either a scalar' %f
+            msg += ' or a vector function'
+            raise msg
+    return f
+
+class Wind_stress:
+    """Apply wind stress to water momentum in terms of
+    wind speed [m/s] and wind direction [degrees]
+    """
+
+    def __init__(self, *args, **kwargs):
+        """Initialise windfield from wind speed s [m/s]
+        and wind direction phi [degrees]
+
+        Inputs v and phi can be either scalars or Python functions, e.g.
+
+        W = Wind_stress(10, 178)
+
+        #FIXME - 'normal' degrees are assumed for now, i.e. the
+        vector (1,0) has zero degrees.
+        We may need to convert from 'compass' degrees later on and also
+        map from True north to grid north.
+
+        Arguments can also be Python functions of t,x,y as in
+
+        def speed(t,x,y):
+            ...
+            return s
+
+        def angle(t,x,y):
+            ...
+            return phi
+
+        where x and y are vectors.
+
+        and then pass the functions in
+
+        W = Wind_stress(speed, angle)
+
+        The instantiated object W can be appended to the list of
+        forcing_terms as in
+
+        Alternatively, one vector valued function for (speed, angle)
+        can be applied, providing both quantities simultaneously.
+        As in
+        W = Wind_stress(F), where returns (speed, angle) for each t.
+
+        domain.forcing_terms.append(W)
+        """
+
+        from config import rho_a, rho_w, eta_w
+        from Numeric import array, Float
+
+        if len(args) == 2:
+            s = args[0]
+            phi = args[1]
+        elif len(args) == 1:
+            #Assume vector function returning (s, phi)(t,x,y)
+            vector_function = args[0]
+            s = lambda t,x: vector_function(t,x=x)[0]
+            phi = lambda t,x: vector_function(t,x=x)[1]
+        else:
+           #Assume info is in 2 keyword arguments
+
+           if len(kwargs) == 2:
+               s = kwargs['s']
+               phi = kwargs['phi']
+           else:
+               raise 'Assumes two keyword arguments: s=..., phi=....'
+
+        print 'phi', phi
+        self.speed = check_forcefield(s)
+        self.phi = check_forcefield(phi)
+
+        self.const = eta_w*rho_a/rho_w
+
+
+    def __call__(self, domain):
+        """Evaluate windfield based on values found in domain
+        """
+
+        from math import pi, cos, sin, sqrt
+        from Numeric import Float, ones, ArrayType
+
+        xmom_update = domain.quantities['xmomentum'].explicit_update
+
+        N = domain.number_of_elements
+        t = domain.time
+
+        if callable(self.speed):
+            xc = domain.get_centroid_coordinates()
+            s_vec = self.speed(t, xc)
+        else:
+            #Assume s is a scalar
+
+            try:
+                s_vec = self.speed * ones(N, Float)
+            except:
+                msg = 'Speed must be either callable or a scalar: %s' %self.s
+                raise msg
+
+
+        if callable(self.phi):
+            xc = domain.get_centroid_coordinates()
+            phi_vec = self.phi(t, xc)
+        else:
+            #Assume phi is a scalar
+
+            try:
+                phi_vec = self.phi * ones(N, Float)
+            except:
+                msg = 'Angle must be either callable or a scalar: %s' %self.phi
+                raise msg
+
+        #assign_windfield_values(xmom_update, ymom_update,
+        #                        s_vec, phi_vec, self.const)
+        assign_windfield_values(xmom_update, s_vec, phi_vec, self.const)
+
+
+#def assign_windfield_values(xmom_update, ymom_update,
+#                            s_vec, phi_vec, const):
+def assign_windfield_values(xmom_update, s_vec, phi_vec, const):
+    """Python version of assigning wind field to update vectors.
+    A c version also exists (for speed)
+    """
+    from math import pi, cos, sin, sqrt
+
+    N = len(s_vec)
+    for k in range(N):
+        s = s_vec[k]
+        phi = phi_vec[k]
+
+        #Convert to radians
+        phi = phi*pi/180
+
+        #Compute velocity vector (u, v)
+        u = s*cos(phi)
+        v = s*sin(phi)
+
+        #Compute wind stress
+        S = const * u
+        xmom_update[k] += S*u
Index: anuga_work/development/sudi/sw_1d/avalanche/A_velocity/util.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/A_velocity/util.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/A_velocity/util.py	(revision 7837)
@@ -0,0 +1,174 @@
+"""
+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 zeros, Float,sqrt,sin,cos
+
+    
+    #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: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/comp_flux_ext_wellbalanced.c
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/comp_flux_ext_wellbalanced.c	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/comp_flux_ext_wellbalanced.c	(revision 7837)
@@ -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: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/config.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/config.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/config.py	(revision 7837)
@@ -0,0 +1,112 @@
+"""Module where global model parameters are set for anuga_1d
+"""
+
+epsilon = 1.0e-12
+h0 = 1.0e-16
+
+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: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/debris_avalanche_RUN.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/debris_avalanche_RUN.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/debris_avalanche_RUN.py	(revision 7837)
@@ -0,0 +1,178 @@
+import os
+import time
+from shallow_water_domain_avalanche import *
+from Numeric import array, zeros, Float, sqrt
+from config import g, epsilon
+from numpy import sin, cos, tan
+from scipy import linspace
+from parameters import *
+
+def analytical_sol(X,t):
+    N = len(X)
+    u = zeros(N,Float)
+    h = zeros(N,Float)
+    w = zeros(N,Float)
+    z = zeros(N,Float)
+    mom = zeros(N,Float)
+    for i in range(N):
+        # Calculate Analytical Solution at time t > 0
+        if X[i] <= -2.0*c0*t + 0.5*m*t**2.0:
+            u[i] = 0.0
+            h[i] = 0.0
+        elif X[i] <= c0*t + 0.5*m*t**2.0:
+            u[i] = 2.0/3.0 * (X[i]/t - c0 + m*t)
+            h[i] = 1.0/(9.0*g) * (X[i]/t + 2.0*c0 - 0.5*m*t)**2.0
+        else:
+            u[i] = m*t
+            h[i] = h_0
+        z[i] = bed_slope*X[i]
+        w[i] = h[i] + z[i]
+        mom[i] = u[i]*h[i]
+    return u,h,w,z,mom
+
+def height(X):
+    N = len(X)
+    y = zeros(N,Float)
+    for i in range(N):
+        if X[i]<=0.0:
+            y[i] = 0.0
+        else:
+            y[i] = h_0
+    return y
+
+def stage(X):
+    N = len(X)
+    w = zeros(N,Float)
+    for i in range(N):
+        if X[i]<=0.0:
+            w[i] = bed_slope*X[i]
+        else:
+            w[i] = bed_slope*X[i] + h_0
+    return w        
+
+def elevation(X):
+    N = len(X)
+    y=zeros(N, Float)
+    for i in range(N):
+        y[i] = bed_slope*X[i]
+    return y
+"""
+#=========================================================================#
+#The following values are set in parameters.py
+h_0 = 10.0         # depth upstream. Note that the depth downstream is 0.0
+L = 2000.0         # length of stream/domain
+n = 100             # number of cells
+cell_len = L/n     # length of each cell
+points = zeros(n+1, Float)
+for i in range (n+1):
+    points[i] = i*cell_len - 0.5*L
+
+bed_slope = 0.005      # bottom slope, positive if it is increasing bottom.
+c0 = sqrt(g*h_0)   # sound speed
+m = -1.0*g*bed_slope   # auxiliary variable
+#==========================================================================#
+"""
+boundary = { (0,0): 'left',(n-1,1): 'right'}
+domain = Domain(points,boundary)
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.beta = 1.0
+domain.set_limiter("minmod")
+
+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)
+#T_right = Transmissive_boundary(domain)
+#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])
+domain.set_boundary({'left':D_left,'right':T_right})
+domain.set_quantity('stage',stage)
+domain.set_quantity('elevation',elevation)
+
+X = domain.vertices
+C = domain.centroids
+
+yieldstep = finaltime = 15.0
+t0 = time.time()
+
+while finaltime <= 15.1:
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        domain.write_time()
+        
+    #The following is for computing the error and plotting the result
+    Mom = domain.quantities['xmomentum']
+    Height = domain.quantities['height']
+    Stage = domain.quantities['stage']
+    Velocity = domain.quantities['velocity']
+    Elevation = domain.quantities['elevation']
+
+    #The following is for computing the error
+    Uc,Hc,Wc,Zc,Mc = analytical_sol(C,domain.time)
+    HeightC = Height.centroid_values
+    MomC = Mom.centroid_values
+    StageC = Stage.centroid_values
+    VelC = Velocity.centroid_values
+    ElevationC = Elevation.centroid_values
+
+    print "number of cells=",n
+    W_error = (1.0/n)*sum(abs(Wc-StageC))
+    M_error = (1.0/n)*sum(abs(Mc-MomC))
+    U_error = (1.0/n)*sum(abs(Uc-VelC))
+    print "stage_error %.10f" %(W_error)
+    print "momentum_error %.10f"%(M_error)
+    print "velocity_error %.10f" %(U_error)
+
+
+    #The following is for plotting the result.
+    Uv,Hv,Wv,Zv,Mv = analytical_sol(X.flat,domain.time)
+    HeightV = Height.vertex_values
+    MomV = Mom.vertex_values
+    StageV = Stage.vertex_values
+    VelV = Velocity.vertex_values
+    ElevationV = Elevation.vertex_values
+    from pylab import clf,plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+    hold(False)
+    clf()
+
+    plot1 = subplot(311)
+    plot(X.flat,Wv,'b-', X.flat,StageV.flat,'k--', X.flat,ElevationV.flat,'k:')
+    #plot(X.flat,Wv, X.flat,StageV.flat, X.flat,ElevationV.flat)    
+    #xlabel('Position')
+    ylabel('Stage')
+    #plot1.set_ylim([-1.0,21.0])
+    #plot1.set_xlim([-500.0,-420.0])#([-9.0e-3,9.0e-3])
+    #legend(('Analytical solution', 'Numerical solution', 'Discretized bed'), 'upper left', shadow=False)
+    
+    plot2 = subplot(312)
+    plot(X.flat,Mv,'b-', X.flat,MomV.flat,'k--')
+    #xlabel('Position')
+    ylabel('Momentum')
+    #plot2.set_xlim([-300.0,300.0])
+    #plot2.set_ylim([-310.0,10.0])#([-90.0,10.0])
+    #legend(('analytical solution', 'numerical solution'), 'lower right', shadow=False)    
+
+    plot3 = subplot(313)
+    plot(X.flat,Uv,'b-', X.flat,VelV.flat,'k--')
+    xlabel('Position')
+    ylabel('Velocity')
+    #plot3.set_xlim([-300.0,300.0])
+    #plot3.set_ylim([-45.0,5.0])#([-30.0,5.0])
+    #legend(('analytical solution', 'numerical solution'), 'lower right', shadow=False)
+    
+    finaltime = finaltime + 10.0
+
+    file = "B-case2-"
+    file += str(n)
+    file += ".eps"
+    #savefig(file)      
+    
+    show()
+
+
Index: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/desktop.ini
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/desktop.ini	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/desktop.ini	(revision 7837)
@@ -0,0 +1,4 @@
+[ViewState]
+Mode=
+Vid=
+FolderType=Documents
Index: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/domain.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/domain.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/domain.py	(revision 7837)
@@ -0,0 +1,1386 @@
+"""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 array, zeros, Float, Int
+
+        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
+
+    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 Numeric 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 array, Int
+
+        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 Numeric 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 zeros, Float
+        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 zeros, Float
+        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:
+                # 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
+                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
+
+
+    def evolve_one_euler_step(self, yieldstep, finaltime):
+        """
+        One Euler Time Step
+        Q^{n+1} = E(h) Q^n
+        """
+
+
+        # 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
+        
+
+
+    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()            
+
+        #--------------------------------------
+        # 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()   
+
+
+
+    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()            
+
+        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       
+        
+
+    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 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 zeros,Float
+
+        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 zeros,Float
+
+        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]
+        
+        """
+        ################
+        n = len(self.quantities['stage'].vertex_values)
+        self.quantities['stage'].vertex_values[n-1,0]     = self.quantities['stage'].centroid_values[n-1]
+        self.quantities['xmomentum'].vertex_values[n-1,0] = self.quantities['xmomentum'].centroid_values[n-1]
+        self.quantities['elevation'].vertex_values[n-1,0] = self.quantities['elevation'].centroid_values[n-1]
+        self.quantities['height'].vertex_values[n-1,0]    = self.quantities['height'].centroid_values[n-1]
+        self.quantities['velocity'].vertex_values[n-1,0]  = self.quantities['velocity'].centroid_values[n-1]
+
+        self.quantities['stage'].vertex_values[n-1,1]     = self.quantities['stage'].centroid_values[n-1]
+        self.quantities['xmomentum'].vertex_values[n-1,1] = self.quantities['xmomentum'].centroid_values[n-1]
+        self.quantities['elevation'].vertex_values[n-1,1] = self.quantities['elevation'].centroid_values[n-1]
+        self.quantities['height'].vertex_values[n-1,1]    = self.quantities['height'].centroid_values[n-1]
+        self.quantities['velocity'].vertex_values[n-1,1]  = self.quantities['velocity'].centroid_values[n-1]
+        """
+        
+    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 ones, sum, equal, Float
+
+        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: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/generic_boundary_conditions.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/generic_boundary_conditions.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/generic_boundary_conditions.py	(revision 7837)
@@ -0,0 +1,548 @@
+"""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 zeros, Float
+        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 array, Float
+        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 array, Float
+        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 Numeric 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 array, zeros, Float
+        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 Numeric 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 zeros, Float, 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: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/parameters.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/parameters.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/parameters.py	(revision 7837)
@@ -0,0 +1,21 @@
+from Numeric import zeros, Float, sqrt
+from config import g
+from scipy import sin, cos, tan, arcsin, arccos, arctan, pi
+
+h_0 = 20.0         # depth upstream. Note that the depth downstream is 0.0
+L = 2000.0         # length of stream/domain
+n = 800             # number of cells
+cell_len = L/n     # length of each cell
+points = zeros(n+1, Float)
+for i in range (n+1):
+    points[i] = i*cell_len - 0.5*L
+
+
+friction_slope = 0.05 #tan(delta) #0.05 # NOTE THAT friction_slope must less than bed_slope
+bed_slope = 0.1 #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: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/quantity.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/quantity.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/quantity.py	(revision 7837)
@@ -0,0 +1,1038 @@
+"""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 array, zeros, Float
+
+        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 zeros, Float
+        
+        #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 array, Float
+
+        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 concatenate, zeros, Float, Int, 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 sum, equal, ones, Float
+
+        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 array, zeros, Float
+
+        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 array, zeros, Float,sign
+        
+        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 zeros, Float
+
+        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 zeros, Float
+        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 zeros, Float
+        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"
+
+
+##
+##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 Numeric 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: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/shallow_water_domain_avalanche.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/shallow_water_domain_avalanche.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/shallow_water_domain_avalanche.py	(revision 7837)
@@ -0,0 +1,1285 @@
+"""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
+"""
+
+
+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)  #gravity, gravity_F1, 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__ = 'shallow_water_domain_avalanche'
+	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 ===============================
+
+#Rotation of momentum vector
+def rotate(q, normal, direction = 1):
+    """Rotate the momentum component q (q[1], q[2])
+    from x,y coordinates to coordinates based on normal vector.
+
+    If direction is negative the rotation is inverted.
+
+    Input vector is preserved
+
+    This function is specific to the shallow water wave equation
+    """
+
+    from Numeric import zeros, Float
+
+    assert len(q) == 3,\
+           'Vector of conserved quantities must have length 3'\
+           'for 2D shallow water equation'
+
+    try:
+        l = len(normal)
+    except:
+        raise 'Normal vector must be an Numeric array'
+
+    assert l == 2, 'Normal vector must have 2 components'
+
+
+    n1 = normal[0]
+    n2 = normal[1]
+
+    r = zeros(len(q), Float) #Rotated quantities
+    r[0] = q[0]              #First quantity, height, is not rotated
+
+    if direction == -1:
+        n2 = -n2
+
+
+    r[1] =  n1*q[1] + n2*q[2]
+    r[2] = -n2*q[1] + n1*q[2]
+
+    return r
+
+
+def flux_function(normal, ql, qr, zl, zr):
+    """Compute fluxes between volumes for the shallow water wave equation
+    cast in terms of w = h+z using the 'central scheme' as described in
+
+    Kurganov, Noelle, Petrova. 'Semidiscrete Central-Upwind Schemes For
+    Hyperbolic Conservation Laws and Hamilton-Jacobi Equations'.
+    Siam J. Sci. Comput. Vol. 23, No. 3, pp. 707-740.
+
+    The implemented formula is given in equation (3.15) on page 714
+
+    Conserved quantities w, uh, are stored as elements 0 and 1
+    in the numerical vectors ql an qr.
+
+    Bed elevations zl and zr.
+    """
+
+    from config import g, epsilon, h0
+    from math import sqrt
+    from Numeric import array
+
+    #Align momentums with x-axis
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+	
+    z = 0.5*(zl+zr) #Take average of field values
+
+    w_left  = q_left[0]   #w=h+z
+    h_left  = w_left-z
+    uh_left = q_left[1]
+
+    if h_left < epsilon:
+        u_left = 0.0  #Could have been negative
+        h_left = 0.0
+    else:
+        u_left  = uh_left/(h_left +  h0/h_left)
+
+
+    uh_left = u_left*h_left
+
+
+    w_right  = q_right[0]  #w=h+z
+    h_right  = w_right-z
+    uh_right = q_right[1]
+
+    if h_right < epsilon:
+        u_right = 0.0  #Could have been negative
+        h_right = 0.0
+    else:
+        u_right  = uh_right/(h_right + h0/h_right)
+
+    uh_right = u_right*h_right
+	
+
+    #We have got h and u at vertex, then the following is the calculation of fluxes!
+    soundspeed_left  = sqrt(g*h_left)
+    soundspeed_right = sqrt(g*h_right)
+
+    #Maximal wave speed
+    s_max = max(u_left+soundspeed_left, u_right+soundspeed_right, 0)
+    
+    #Minimal wave speed
+    s_min = min(u_left-soundspeed_left, u_right-soundspeed_right, 0)
+    
+    #Flux computation
+    flux_left  = array([u_left*h_left,
+                        u_left*uh_left + 0.5*g*h_left*h_left])
+    flux_right = array([u_right*h_right,
+                        u_right*uh_right + 0.5*g*h_right*h_right])
+
+    denom = s_max-s_min
+    if denom == 0.0:
+        edgeflux = array([0.0, 0.0])
+        max_speed = 0.0
+    else:
+        edgeflux = (s_max*flux_left - s_min*flux_right)/denom
+        edgeflux += s_max*s_min*(q_right-q_left)/denom
+        
+        edgeflux[1] = edgeflux[1]*normal
+
+        max_speed = max(abs(s_max), abs(s_min))
+
+    return edgeflux, max_speed
+
+#
+def compute_timestep(domain):
+    import sys
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    
+    stage = Stage.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+
+    stage_bdry = Stage.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+
+    flux = zeros(2, Float) #Work array for summing up fluxes
+    ql = zeros(2, Float)
+    qr = zeros(2, Float)
+
+    #Loop
+    timestep = float(sys.maxint)
+    enter = True
+    for k in range(N):
+
+        flux[:] = 0.  #Reset work array
+        for i in range(2):
+            #Quantities inside volume facing neighbour i
+            ql = [stage[k, i], xmom[k, i]]
+            zl = bed[k, i]
+
+            #Quantities at neighbour on nearest face
+            n = domain.neighbours[k,i]
+            if n < 0:
+                m = -n-1 #Convert negative flag to index
+                qr[0] = stage_bdry[m]
+                qr[1] = xmom_bdry[m]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                m = domain.neighbour_vertices[k,i]
+                qr[0] = stage[n, m]
+                qr[1] =  xmom[n, m]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+
+            edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+
+            #Update optimal_timestep
+            try:
+                timestep = min(timestep, domain.cfl*0.5*domain.areas[k]/max_speed)
+            except ZeroDivisionError:
+                pass
+
+    domain.timestep = timestep
+
+# Compute flux definition
+# ###################################
+def compute_fluxes_C_wellbalanced(domain):
+    import sys
+    from Numeric import zeros, Float
+    
+    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)
+
+
+def compute_fluxes_C_nonwellbalanced2(domain):
+    import sys
+    from Numeric import zeros, Float
+    
+    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_nonwellbalanced2 import compute_fluxes_ext_nonwellbalanced2
+    domain.flux_timestep = compute_fluxes_ext_nonwellbalanced2(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 zeros, Float
+    from config import epsilon, h0, h_min
+
+    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] <= 0.01:  #epsilon :
+	    #h_C[i] = 0.0
+	    #w_C[i] = z_C[i]
+	    uh_C[i] = 0.0
+	    u_C[i] = 0.0
+	    
+	if h_C[i] < epsilon: #h_min:
+            h_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 zeros, Float
+    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]
+    #u_C[:] = uh_C/(h_C + h0/h_C)
+    
+    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] # This makes a negligible difference.
+	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 h_V[i] <= 0.0:
+	    h_V[i] = 0.0
+	    stage_V[i] = bed_V[i]
+	    xmom_V[i] = 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
+            
+    
+def h_limiter(domain):
+    """Limit slopes for each volume to eliminate artificial variance
+    introduced by e.g. second order extrapolator
+
+    limit on h = w-z
+
+    This limiter depends on two quantities (w,z) so it resides within
+    this module rather than within quantity.py
+    """
+
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+    beta_h = domain.beta_h
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = wc - zc
+
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = wv-zv
+
+    hvbar = zeros(hv.shape, Float) #h-limited values
+
+    #Find min and max of this and neighbour's centroid values
+    hmax = zeros(hc.shape, Float)
+    hmin = zeros(hc.shape, Float)
+
+    for k in range(N):
+        hmax[k] = hmin[k] = hc[k]
+        for i in range(2):   
+            n = domain.neighbours[k,i]
+            if n >= 0:
+                hn = hc[n] #Neighbour's centroid value
+
+                hmin[k] = min(hmin[k], hn)
+                hmax[k] = max(hmax[k], hn)
+
+
+    #Diffences between centroids and maxima/minima
+    dhmax = hmax - hc
+    dhmin = hmin - hc
+
+    #Deltas between vertex and centroid values
+    dh = zeros(hv.shape, Float)
+    for i in range(2):
+        dh[:,i] = hv[:,i] - hc
+
+    #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 (dh[k,i] > 0): r = dhmax[k]/dh[k,i]
+            if (dh[k,i] < 0): r = dhmin[k]/dh[k,i]
+
+            phi = min( min(r*beta_h, 1), phi )
+
+        #Then update using phi limiter
+        for i in range(2):
+            hvbar[k,i] = hc[k] + phi*dh[k,i]
+
+    return hvbar
+
+def balance_deep_and_shallow(domain):
+    """Compute linear combination between stage as computed by
+    gradient-limiters limiting using w, and stage computed by
+    gradient-limiters limiting using h (h-limiter).
+    The former takes precedence when heights are large compared to the
+    bed slope while the latter takes precedence when heights are
+    relatively small.  Anything in between is computed as a balanced
+    linear combination in order to avoid numerical disturbances which
+    would otherwise appear as a result of hard switching between
+    modes.
+
+    The h-limiter is always applied irrespective of the order.
+    """
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = wc - zc
+
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = wv-zv
+
+    #Limit h
+    hvbar = h_limiter(domain)
+
+    for k in range(domain.number_of_elements):
+        #Compute maximal variation in bed elevation
+        #  This quantitiy is
+        #    dz = max_i abs(z_i - z_c)
+        #  and it is independent of dimension
+        #  In the 1d case zc = (z0+z1)/2
+        #  In the 2d case zc = (z0+z1+z2)/3
+
+        dz = max(abs(zv[k,0]-zc[k]),
+                 abs(zv[k,1]-zc[k]))#,
+#                 abs(zv[k,2]-zc[k]))
+
+
+        hmin = min( hv[k,:] )
+
+        #Create alpha in [0,1], where alpha==0 means using the h-limited
+        #stage and alpha==1 means using the w-limited stage as
+        #computed by the gradient limiter (both 1st or 2nd order)
+
+        #If hmin > dz/2 then alpha = 1 and the bed will have no effect
+        #If hmin < 0 then alpha = 0 reverting to constant height above bed.
+
+        if dz > 0.0:
+            alpha = max( min( 2*hmin/dz, 1.0), 0.0 )
+        else:
+            #Flat bed
+            alpha = 1.0
+
+        alpha  = 0.0
+	#Let
+	#
+	#  wvi be the w-limited stage (wvi = zvi + hvi)
+	#  wvi- be the h-limited state (wvi- = zvi + hvi-)
+	#
+	#
+	#where i=0,1,2 denotes the vertex ids
+	#
+        #Weighted balance between w-limited and h-limited stage is
+        #
+	#  wvi := (1-alpha)*(zvi+hvi-) + alpha*(zvi+hvi)
+	#
+        #It follows that the updated wvi is
+        #  wvi := zvi + (1-alpha)*hvi- + alpha*hvi
+        #
+	# Momentum is balanced between constant and limited
+
+
+        #for i in range(3):
+        #    wv[k,i] = zv[k,i] + hvbar[k,i]
+
+	#return
+
+	if alpha < 1:
+
+            #for i in range(3):
+            for i in range(2):
+                wv[k,i] = zv[k,i] + (1.0-alpha)*hvbar[k,i] + alpha*hv[k,i]
+
+            #Momentums at centroids
+            xmomc = domain.quantities['xmomentum'].centroid_values
+
+
+            #Momentums at vertices
+            xmomv = domain.quantities['xmomentum'].vertex_values
+
+
+            # Update momentum as a linear combination of
+            # xmomc and ymomc (shallow) and momentum
+            # from extrapolator xmomv and ymomv (deep).
+            xmomv[k,:] = (1.0-alpha)*xmomc[k] + alpha*xmomv[k,:]
+
+
+
+
+
+#########################
+#Standard forcing terms:
+#
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import zeros, Float, 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_F1(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import zeros, Float, array, sum
+    from parameters import F1#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*F1#This is an additional friction!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+
+
+def gravity_F2(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import zeros, Float, 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]
+
+def linear_friction(domain):
+    """Apply linear friction to water momentum
+
+    Assumes quantity: 'linear_friction' to be present
+    """
+
+    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
+    tau = domain.quantities['linear_friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+
+    N = domain.number_of_elements
+    eps = domain.minimum_allowed_height
+    g = domain.g #Not necessary? Why was this added?
+
+    for k in range(N):
+        if tau[k] >= eps:
+            if h[k] >= eps:
+            	S = -tau[k]/h[k]
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
+
+
+
+def check_forcefield(f):
+    """Check that f is either
+    1: a callable object f(t,x,y), where x and y are vectors
+       and that it returns an array or a list of same length
+       as x and y
+    2: a scalar
+    """
+
+    from Numeric import ones, Float, array
+
+
+    if callable(f):
+        N = 2
+        x = ones(2, Float)
+        
+        try:
+            q = f(1.0, x=x)
+        except Exception, e:
+            msg = 'Function %s could not be executed:\n%s' %(f, e)
+	    #FIXME: Reconsider this semantics
+            raise msg
+
+        try:
+            q = array(q).astype(Float)
+        except:
+            msg = 'Return value from vector function %s could ' %f
+            msg += 'not be converted into a Numeric array of floats.\n'
+            msg += 'Specified function should return either list or array.'
+            raise msg
+
+        #Is this really what we want?
+        msg = 'Return vector from function %s ' %f
+        msg += 'must have same lenght as input vectors'
+        assert len(q) == N, msg
+
+    else:
+        try:
+            f = float(f)
+        except:
+            msg = 'Force field %s must be either a scalar' %f
+            msg += ' or a vector function'
+            raise msg
+    return f
+
+class Wind_stress:
+    """Apply wind stress to water momentum in terms of
+    wind speed [m/s] and wind direction [degrees]
+    """
+
+    def __init__(self, *args, **kwargs):
+        """Initialise windfield from wind speed s [m/s]
+        and wind direction phi [degrees]
+
+        Inputs v and phi can be either scalars or Python functions, e.g.
+
+        W = Wind_stress(10, 178)
+
+        #FIXME - 'normal' degrees are assumed for now, i.e. the
+        vector (1,0) has zero degrees.
+        We may need to convert from 'compass' degrees later on and also
+        map from True north to grid north.
+
+        Arguments can also be Python functions of t,x,y as in
+
+        def speed(t,x,y):
+            ...
+            return s
+
+        def angle(t,x,y):
+            ...
+            return phi
+
+        where x and y are vectors.
+
+        and then pass the functions in
+
+        W = Wind_stress(speed, angle)
+
+        The instantiated object W can be appended to the list of
+        forcing_terms as in
+
+        Alternatively, one vector valued function for (speed, angle)
+        can be applied, providing both quantities simultaneously.
+        As in
+        W = Wind_stress(F), where returns (speed, angle) for each t.
+
+        domain.forcing_terms.append(W)
+        """
+
+        from config import rho_a, rho_w, eta_w
+        from Numeric import array, Float
+
+        if len(args) == 2:
+            s = args[0]
+            phi = args[1]
+        elif len(args) == 1:
+            #Assume vector function returning (s, phi)(t,x,y)
+            vector_function = args[0]
+            s = lambda t,x: vector_function(t,x=x)[0]
+            phi = lambda t,x: vector_function(t,x=x)[1]
+        else:
+           #Assume info is in 2 keyword arguments
+
+           if len(kwargs) == 2:
+               s = kwargs['s']
+               phi = kwargs['phi']
+           else:
+               raise 'Assumes two keyword arguments: s=..., phi=....'
+
+        print 'phi', phi
+        self.speed = check_forcefield(s)
+        self.phi = check_forcefield(phi)
+
+        self.const = eta_w*rho_a/rho_w
+
+
+    def __call__(self, domain):
+        """Evaluate windfield based on values found in domain
+        """
+
+        from math import pi, cos, sin, sqrt
+        from Numeric import Float, ones, ArrayType
+
+        xmom_update = domain.quantities['xmomentum'].explicit_update
+
+        N = domain.number_of_elements
+        t = domain.time
+
+        if callable(self.speed):
+            xc = domain.get_centroid_coordinates()
+            s_vec = self.speed(t, xc)
+        else:
+            #Assume s is a scalar
+
+            try:
+                s_vec = self.speed * ones(N, Float)
+            except:
+                msg = 'Speed must be either callable or a scalar: %s' %self.s
+                raise msg
+
+
+        if callable(self.phi):
+            xc = domain.get_centroid_coordinates()
+            phi_vec = self.phi(t, xc)
+        else:
+            #Assume phi is a scalar
+
+            try:
+                phi_vec = self.phi * ones(N, Float)
+            except:
+                msg = 'Angle must be either callable or a scalar: %s' %self.phi
+                raise msg
+
+        #assign_windfield_values(xmom_update, ymom_update,
+        #                        s_vec, phi_vec, self.const)
+        assign_windfield_values(xmom_update, s_vec, phi_vec, self.const)
+
+
+#def assign_windfield_values(xmom_update, ymom_update,
+#                            s_vec, phi_vec, const):
+def assign_windfield_values(xmom_update, s_vec, phi_vec, const):
+    """Python version of assigning wind field to update vectors.
+    A c version also exists (for speed)
+    """
+    from math import pi, cos, sin, sqrt
+
+    N = len(s_vec)
+    for k in range(N):
+        s = s_vec[k]
+        phi = phi_vec[k]
+
+        #Convert to radians
+        phi = phi*pi/180
+
+        #Compute velocity vector (u, v)
+        u = s*cos(phi)
+        v = s*sin(phi)
+
+        #Compute wind stress
+        S = const * u
+        xmom_update[k] += S*u
Index: anuga_work/development/sudi/sw_1d/avalanche/B_momentum/util.py
===================================================================
--- anuga_work/development/sudi/sw_1d/avalanche/B_momentum/util.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/avalanche/B_momentum/util.py	(revision 7837)
@@ -0,0 +1,174 @@
+"""
+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 zeros, Float,sqrt,sin,cos
+
+    
+    #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: anuga_work/development/sudi/sw_1d/periodic_waves/cg/analytical_prescription.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/analytical_prescription.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/analytical_prescription.py	(revision 7837)
@@ -0,0 +1,87 @@
+from scipy import sin, cos, sqrt, pi, dot
+from gaussPivot import *
+from parameter import *
+
+def root_g(a,b,t):
+    dx = 0.01
+    def g(u):
+        return u + 2.0*A*pi/T*sin(2.0*pi/T*(t+u))
+    while 1:
+        x1,x2 = rootsearch(g,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(g,x1,x2,1)
+        else:
+            break
+    return root
+def shore(t):
+    a = -1.0
+    b = 1.0
+    #dx = 0.01
+    u = root_g(a,b,t)
+    xi = -0.5*u*u + A*cos(2.0*pi/T*(t+u)) #This is the displacement
+    #position = 1.0 + xi
+    return [xi, u]#[position, u]
+
+def w_at_O(t):
+    return eps*cos(2.0*pi*t/T)
+
+def u_at_O(t):
+    a = -1.01
+    b = 1.01
+    dx = 0.01
+    w = w_at_O(t)
+    def fun(u):
+        return u + A*j1(4.0*pi/T*(1.0+w)**0.5)*sin(2.0*pi/T*(t+u))/(1.0+w)**0.5
+    while 1:
+        x1,x2 = rootsearch(fun,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(fun,x1,x2,1)
+        else:
+            break
+    return root
+
+
+def prescribe(x,t):
+    from Numeric import array, zeros, Float
+    q_shore = shore(t)
+    q = zeros(2,Float)
+    if x<1.0-abs(q_shore[0]):
+        q[0] = w_at_O(t)
+        q[1] = u_at_O(t)
+    else:
+        q = q_shore
+    def fun(q): #Here q=(w, u)
+        f = zeros(2,Float)
+        f[0] = q[0] + 0.5*q[1]**2.0 - A*j0(4.0*pi/T*(1.0+q[0]-x)**0.5)*cos(2.0*pi/T*(t+q[1]))
+        f[1] = q[1] + A*j1(4.0*pi/T*(1.0+q[0]-x)**0.5)*sin(2.0*pi/T*(t+q[1]))/(1+q[0]-x)**0.5
+        return f
+    def newtonRaphson2(f,q,tol=1.0e-15):
+        for i in range(30):                                                                                                                                    
+            h = 1.0e-4      ##1.0e-4 may be too large.
+            n = len(q)
+            jac = zeros((n,n),Float)
+            if 1.0+q[0]-x<0.0:
+                #temp1 = 1.0+q[0]-x
+                #q[0] = x-1.0+0.01
+                #print "1.0+q[0]-x=",1.0+q[0]-x
+                print "SomethingWRONG"
+                #return q
+                #q[0] =0.25
+            f0 = f(q)
+            for i in range(n):
+                temp = q[i]
+                q[i] = temp + h
+                f1 = f(q)
+                q[i] = temp
+                jac[:,i] = (f1 - f0)/h
+            if sqrt(dot(f0,f0)/len(q)) < tol: return q
+            dq = gaussPivot(jac,-f0)
+            q = q + dq
+            if sqrt(dot(dq,dq)) < tol*max(max(abs(q)),1.0): return q
+        print 'Too many iterations'
+    q = newtonRaphson2(fun,q)    
+    return q[0], q[1]
+
+#w,u=prescribe(0.0,0.0)
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/bisect.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/bisect.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/bisect.py	(revision 7837)
@@ -0,0 +1,28 @@
+## module bisect
+''' root = bisect(f,x1,x2,switch=0,tol=1.0e-9).
+    Finds a root of f(x) = 0 by bisection.
+    The root must be bracketed in (x1,x2).
+    Setting switch = 1 returns root = None if
+    f(x) increases as a result of a bisection.
+'''    
+from math import log,ceil
+import error
+
+def bisect(f,x1,x2,switch=0,epsilon=1.0e-15):#9):
+    f1 = f(x1)
+    if f1 == 0.0: return x1
+    f2 = f(x2)
+    if f2 == 0.0: return x2
+    if f1*f2 > 0.0: error.err('Root is not bracketed')
+    n = ceil(log(abs(x2 - x1)/epsilon)/log(2.0))
+    for i in range(n):
+        x3 = 0.5*(x1 + x2); f3 = f(x3)
+        if (switch == 1) and (abs(f3) >abs(f1)) \
+                         and (abs(f3) > abs(f2)):
+            return None   
+        if f3 == 0.0: return x3
+        if f2*f3 < 0.0:
+            x1 = x3; f1 = f3
+        else:
+            x2 = x3; f2 = f3
+    return (x1 + x2)/2.0
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/comp_flux_ext_wellbalanced.c
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/comp_flux_ext_wellbalanced.c	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/comp_flux_ext_wellbalanced.c	(revision 7837)
@@ -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: anuga_work/development/sudi/sw_1d/periodic_waves/cg/config.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/config.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/config.py	(revision 7837)
@@ -0,0 +1,112 @@
+"""Module where global model parameters are set for anuga_1d
+"""
+
+epsilon = 1.0e-6#12
+h0 = 1.0e-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.
+h_min = 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: anuga_work/development/sudi/sw_1d/periodic_waves/cg/desktop.ini
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/desktop.ini	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/desktop.ini	(revision 7837)
@@ -0,0 +1,4 @@
+[ViewState]
+Mode=
+Vid=
+FolderType=Documents
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/domain.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/domain.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/domain.py	(revision 7837)
@@ -0,0 +1,1388 @@
+"""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 array, zeros, Float, Int
+
+        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'
+        self.checkpoint = False
+
+    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 Numeric 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 array, Int
+
+        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 Numeric 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 zeros, Float
+        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 zeros, Float
+        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:
+                # 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
+                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
+
+
+    def evolve_one_euler_step(self, yieldstep, finaltime):
+        """
+        One Euler Time Step
+        Q^{n+1} = E(h) Q^n
+        """
+
+
+        # 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
+        
+
+
+    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()            
+
+        #--------------------------------------
+        # 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()   
+
+
+    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()            
+
+        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       
+        
+
+    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 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 zeros,Float
+
+        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 zeros,Float
+
+        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
+        def transform_function(t):
+            from analytical_prescription import prescribe
+            from parameter import h_0, L, cell_len
+            from config import g
+            from math import sqrt            
+            #position = 0.5*cell_len/L
+            timing = t*sqrt(g*h_0)/L
+            w, u = prescribe(0.0,timing) #(position,timing)
+            wO = w*h_0
+            uO = u*sqrt(g*h_0)
+            zO = -h_0
+            hO = wO - zO
+            pO = uO * hO
+            #[    'stage', 'xmomentum', 'elevation', 'height', 'velocity']
+            return [wO,  pO,   zO,      hO,      uO]
+        tempor = transform_function(self.time)
+        
+        self.quantities['stage'].centroid_values[0]     = tempor[0]
+        self.quantities['xmomentum'].centroid_values[0] = tempor[1]
+        self.quantities['elevation'].centroid_values[0] = tempor[2]
+        self.quantities['height'].centroid_values[0]    = tempor[3]
+        self.quantities['velocity'].centroid_values[0]  = tempor[4]
+        
+        
+    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]
+
+        
+        def transform_function(t):
+            from analytical_prescription import prescribe
+            from parameter import h_0, L, cell_len
+            from config import g
+            from math import sqrt            
+            #position = cell_len/L
+            timing = t*sqrt(g*h_0)/L
+            w, u = prescribe(0.0,timing) #(position,timing)
+            wO = w*h_0
+            uO = u*sqrt(g*h_0)
+            zO = -h_0
+            hO = wO - zO
+            pO = uO * hO
+            #[    'stage', 'xmomentum', 'elevation', 'height', 'velocity']
+            return [wO,  pO,   zO,      hO,      uO]
+        temp = transform_function(self.time)
+        
+        #Below is just for checking/testing
+        self.quantities['stage'].vertex_values[0,1]     = temp[0]
+        self.quantities['xmomentum'].vertex_values[0,1] = temp[1]
+        self.quantities['elevation'].vertex_values[0,1] = temp[2]
+        self.quantities['height'].vertex_values[0,1]    = temp[3]
+        self.quantities['velocity'].vertex_values[0,1]  = temp[4]
+                            
+    
+    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 ones, sum, equal, Float
+
+        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: anuga_work/development/sudi/sw_1d/periodic_waves/cg/domain_cg.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/domain_cg.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/domain_cg.py	(revision 7837)
@@ -0,0 +1,1039 @@
+"""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
+"""
+
+
+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)
+        #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__ = 'domain_cg'
+	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)
+
+    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(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 ===============================
+
+#Rotation of momentum vector
+def rotate(q, normal, direction = 1):
+    """Rotate the momentum component q (q[1], q[2])
+    from x,y coordinates to coordinates based on normal vector.
+
+    If direction is negative the rotation is inverted.
+
+    Input vector is preserved
+
+    This function is specific to the shallow water wave equation
+    """
+
+    from Numeric import zeros, Float
+
+    assert len(q) == 3,\
+           'Vector of conserved quantities must have length 3'\
+           'for 2D shallow water equation'
+
+    try:
+        l = len(normal)
+    except:
+        raise 'Normal vector must be an Numeric array'
+
+    assert l == 2, 'Normal vector must have 2 components'
+
+
+    n1 = normal[0]
+    n2 = normal[1]
+
+    r = zeros(len(q), Float) #Rotated quantities
+    r[0] = q[0]              #First quantity, height, is not rotated
+
+    if direction == -1:
+        n2 = -n2
+
+
+    r[1] =  n1*q[1] + n2*q[2]
+    r[2] = -n2*q[1] + n1*q[2]
+
+    return r
+
+
+def flux_function(normal, ql, qr, zl, zr):
+    """Compute fluxes between volumes for the shallow water wave equation
+    cast in terms of w = h+z using the 'central scheme' as described in
+
+    Kurganov, Noelle, Petrova. 'Semidiscrete Central-Upwind Schemes For
+    Hyperbolic Conservation Laws and Hamilton-Jacobi Equations'.
+    Siam J. Sci. Comput. Vol. 23, No. 3, pp. 707-740.
+
+    The implemented formula is given in equation (3.15) on page 714
+
+    Conserved quantities w, uh, are stored as elements 0 and 1
+    in the numerical vectors ql an qr.
+
+    Bed elevations zl and zr.
+    """
+
+    from config import g, epsilon, h0
+    from math import sqrt
+    from Numeric import array
+
+    #Align momentums with x-axis
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+	
+    z = 0.5*(zl+zr) #Take average of field values
+
+    w_left  = q_left[0]   #w=h+z
+    h_left  = w_left-z
+    uh_left = q_left[1]
+
+    if h_left < epsilon:
+        u_left = 0.0  #Could have been negative
+        h_left = 0.0
+    else:
+        u_left  = uh_left/(h_left +  h0/h_left)
+
+
+    uh_left = u_left*h_left
+
+
+    w_right  = q_right[0]  #w=h+z
+    h_right  = w_right-z
+    uh_right = q_right[1]
+
+    if h_right < epsilon:
+        u_right = 0.0  #Could have been negative
+        h_right = 0.0
+    else:
+        u_right  = uh_right/(h_right + h0/h_right)
+
+    uh_right = u_right*h_right
+	
+
+    #We have got h and u at vertex, then the following is the calculation of fluxes!
+    soundspeed_left  = sqrt(g*h_left)
+    soundspeed_right = sqrt(g*h_right)
+
+    #Maximal wave speed
+    s_max = max(u_left+soundspeed_left, u_right+soundspeed_right, 0)
+    
+    #Minimal wave speed
+    s_min = min(u_left-soundspeed_left, u_right-soundspeed_right, 0)
+    
+    #Flux computation
+    flux_left  = array([u_left*h_left,
+                        u_left*uh_left + 0.5*g*h_left*h_left])
+    flux_right = array([u_right*h_right,
+                        u_right*uh_right + 0.5*g*h_right*h_right])
+
+    denom = s_max-s_min
+    if denom == 0.0:
+        edgeflux = array([0.0, 0.0])
+        max_speed = 0.0
+    else:
+        edgeflux = (s_max*flux_left - s_min*flux_right)/denom
+        edgeflux += s_max*s_min*(q_right-q_left)/denom
+        
+        edgeflux[1] = edgeflux[1]*normal
+
+        max_speed = max(abs(s_max), abs(s_min))
+
+    return edgeflux, max_speed
+
+#
+def compute_timestep(domain):
+    import sys
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    
+    stage = Stage.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+
+    stage_bdry = Stage.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+
+    flux = zeros(2, Float) #Work array for summing up fluxes
+    ql = zeros(2, Float)
+    qr = zeros(2, Float)
+
+    #Loop
+    timestep = float(sys.maxint)
+    enter = True
+    for k in range(N):
+
+        flux[:] = 0.  #Reset work array
+        for i in range(2):
+            #Quantities inside volume facing neighbour i
+            ql = [stage[k, i], xmom[k, i]]
+            zl = bed[k, i]
+
+            #Quantities at neighbour on nearest face
+            n = domain.neighbours[k,i]
+            if n < 0:
+                m = -n-1 #Convert negative flag to index
+                qr[0] = stage_bdry[m]
+                qr[1] = xmom_bdry[m]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                m = domain.neighbour_vertices[k,i]
+                qr[0] = stage[n, m]
+                qr[1] =  xmom[n, m]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+
+            edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+
+            #Update optimal_timestep
+            try:
+                timestep = min(timestep, domain.cfl*0.5*domain.areas[k]/max_speed)
+            except ZeroDivisionError:
+                pass
+
+    domain.timestep = timestep
+
+# Compute flux definition
+# ###################################
+def compute_fluxes_C_wellbalanced(domain):
+    import sys
+    from Numeric import zeros, Float
+    
+    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(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 zeros, Float
+    from config import epsilon, h0, h_min
+
+    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] <= 0.01:  #epsilon :
+	    #h_C[i] = 0.0
+	    #w_C[i] = z_C[i]
+	    uh_C[i] = 0.0
+	    u_C[i] = 0.0
+	    
+	if h_C[i] < epsilon: #h_min:
+            h_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 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
+            
+    
+def h_limiter(domain):
+    """Limit slopes for each volume to eliminate artificial variance
+    introduced by e.g. second order extrapolator
+
+    limit on h = w-z
+
+    This limiter depends on two quantities (w,z) so it resides within
+    this module rather than within quantity.py
+    """
+
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+    beta_h = domain.beta_h
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = wc - zc
+
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = wv-zv
+
+    hvbar = zeros(hv.shape, Float) #h-limited values
+
+    #Find min and max of this and neighbour's centroid values
+    hmax = zeros(hc.shape, Float)
+    hmin = zeros(hc.shape, Float)
+
+    for k in range(N):
+        hmax[k] = hmin[k] = hc[k]
+        for i in range(2):   
+            n = domain.neighbours[k,i]
+            if n >= 0:
+                hn = hc[n] #Neighbour's centroid value
+
+                hmin[k] = min(hmin[k], hn)
+                hmax[k] = max(hmax[k], hn)
+
+
+    #Diffences between centroids and maxima/minima
+    dhmax = hmax - hc
+    dhmin = hmin - hc
+
+    #Deltas between vertex and centroid values
+    dh = zeros(hv.shape, Float)
+    for i in range(2):
+        dh[:,i] = hv[:,i] - hc
+
+    #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 (dh[k,i] > 0): r = dhmax[k]/dh[k,i]
+            if (dh[k,i] < 0): r = dhmin[k]/dh[k,i]
+
+            phi = min( min(r*beta_h, 1), phi )
+
+        #Then update using phi limiter
+        for i in range(2):
+            hvbar[k,i] = hc[k] + phi*dh[k,i]
+
+    return hvbar
+
+def balance_deep_and_shallow(domain):
+    """Compute linear combination between stage as computed by
+    gradient-limiters limiting using w, and stage computed by
+    gradient-limiters limiting using h (h-limiter).
+    The former takes precedence when heights are large compared to the
+    bed slope while the latter takes precedence when heights are
+    relatively small.  Anything in between is computed as a balanced
+    linear combination in order to avoid numerical disturbances which
+    would otherwise appear as a result of hard switching between
+    modes.
+
+    The h-limiter is always applied irrespective of the order.
+    """
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = wc - zc
+
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = wv-zv
+
+    #Limit h
+    hvbar = h_limiter(domain)
+
+    for k in range(domain.number_of_elements):
+        #Compute maximal variation in bed elevation
+        #  This quantitiy is
+        #    dz = max_i abs(z_i - z_c)
+        #  and it is independent of dimension
+        #  In the 1d case zc = (z0+z1)/2
+        #  In the 2d case zc = (z0+z1+z2)/3
+
+        dz = max(abs(zv[k,0]-zc[k]),
+                 abs(zv[k,1]-zc[k]))#,
+#                 abs(zv[k,2]-zc[k]))
+
+
+        hmin = min( hv[k,:] )
+
+        #Create alpha in [0,1], where alpha==0 means using the h-limited
+        #stage and alpha==1 means using the w-limited stage as
+        #computed by the gradient limiter (both 1st or 2nd order)
+
+        #If hmin > dz/2 then alpha = 1 and the bed will have no effect
+        #If hmin < 0 then alpha = 0 reverting to constant height above bed.
+
+        if dz > 0.0:
+            alpha = max( min( 2*hmin/dz, 1.0), 0.0 )
+        else:
+            #Flat bed
+            alpha = 1.0
+
+        alpha  = 0.0
+	#Let
+	#
+	#  wvi be the w-limited stage (wvi = zvi + hvi)
+	#  wvi- be the h-limited state (wvi- = zvi + hvi-)
+	#
+	#
+	#where i=0,1,2 denotes the vertex ids
+	#
+        #Weighted balance between w-limited and h-limited stage is
+        #
+	#  wvi := (1-alpha)*(zvi+hvi-) + alpha*(zvi+hvi)
+	#
+        #It follows that the updated wvi is
+        #  wvi := zvi + (1-alpha)*hvi- + alpha*hvi
+        #
+	# Momentum is balanced between constant and limited
+
+
+        #for i in range(3):
+        #    wv[k,i] = zv[k,i] + hvbar[k,i]
+
+	#return
+
+	if alpha < 1:
+
+            #for i in range(3):
+            for i in range(2):
+                wv[k,i] = zv[k,i] + (1.0-alpha)*hvbar[k,i] + alpha*hv[k,i]
+
+            #Momentums at centroids
+            xmomc = domain.quantities['xmomentum'].centroid_values
+
+
+            #Momentums at vertices
+            xmomv = domain.quantities['xmomentum'].vertex_values
+
+
+            # Update momentum as a linear combination of
+            # xmomc and ymomc (shallow) and momentum
+            # from extrapolator xmomv and ymomv (deep).
+            xmomv[k,:] = (1.0-alpha)*xmomc[k] + alpha*xmomv[k,:]
+
+
+
+
+
+#########################
+#Standard forcing terms:
+#
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import zeros, Float, 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 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]
+
+def linear_friction(domain):
+    """Apply linear friction to water momentum
+
+    Assumes quantity: 'linear_friction' to be present
+    """
+
+    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
+    tau = domain.quantities['linear_friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+
+    N = domain.number_of_elements
+    eps = domain.minimum_allowed_height
+    g = domain.g #Not necessary? Why was this added?
+
+    for k in range(N):
+        if tau[k] >= eps:
+            if h[k] >= eps:
+            	S = -tau[k]/h[k]
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
+ #           	ymom_update[k] += S*vh[k]
+
+
+
+def check_forcefield(f):
+    """Check that f is either
+    1: a callable object f(t,x,y), where x and y are vectors
+       and that it returns an array or a list of same length
+       as x and y
+    2: a scalar
+    """
+
+    from Numeric import ones, Float, array
+
+
+    if callable(f):
+        N = 2
+        x = ones(2, Float)
+        
+        try:
+            q = f(1.0, x=x)
+        except Exception, e:
+            msg = 'Function %s could not be executed:\n%s' %(f, e)
+	    #FIXME: Reconsider this semantics
+            raise msg
+
+        try:
+            q = array(q).astype(Float)
+        except:
+            msg = 'Return value from vector function %s could ' %f
+            msg += 'not be converted into a Numeric array of floats.\n'
+            msg += 'Specified function should return either list or array.'
+            raise msg
+
+        #Is this really what we want?
+        msg = 'Return vector from function %s ' %f
+        msg += 'must have same lenght as input vectors'
+        assert len(q) == N, msg
+
+    else:
+        try:
+            f = float(f)
+        except:
+            msg = 'Force field %s must be either a scalar' %f
+            msg += ' or a vector function'
+            raise msg
+    return f
+
+class Wind_stress:
+    """Apply wind stress to water momentum in terms of
+    wind speed [m/s] and wind direction [degrees]
+    """
+
+    def __init__(self, *args, **kwargs):
+        """Initialise windfield from wind speed s [m/s]
+        and wind direction phi [degrees]
+
+        Inputs v and phi can be either scalars or Python functions, e.g.
+
+        W = Wind_stress(10, 178)
+
+        #FIXME - 'normal' degrees are assumed for now, i.e. the
+        vector (1,0) has zero degrees.
+        We may need to convert from 'compass' degrees later on and also
+        map from True north to grid north.
+
+        Arguments can also be Python functions of t,x,y as in
+
+        def speed(t,x,y):
+            ...
+            return s
+
+        def angle(t,x,y):
+            ...
+            return phi
+
+        where x and y are vectors.
+
+        and then pass the functions in
+
+        W = Wind_stress(speed, angle)
+
+        The instantiated object W can be appended to the list of
+        forcing_terms as in
+
+        Alternatively, one vector valued function for (speed, angle)
+        can be applied, providing both quantities simultaneously.
+        As in
+        W = Wind_stress(F), where returns (speed, angle) for each t.
+
+        domain.forcing_terms.append(W)
+        """
+
+        from config import rho_a, rho_w, eta_w
+        from Numeric import array, Float
+
+        if len(args) == 2:
+            s = args[0]
+            phi = args[1]
+        elif len(args) == 1:
+            #Assume vector function returning (s, phi)(t,x,y)
+            vector_function = args[0]
+            s = lambda t,x: vector_function(t,x=x)[0]
+            phi = lambda t,x: vector_function(t,x=x)[1]
+        else:
+           #Assume info is in 2 keyword arguments
+
+           if len(kwargs) == 2:
+               s = kwargs['s']
+               phi = kwargs['phi']
+           else:
+               raise 'Assumes two keyword arguments: s=..., phi=....'
+
+        print 'phi', phi
+        self.speed = check_forcefield(s)
+        self.phi = check_forcefield(phi)
+
+        self.const = eta_w*rho_a/rho_w
+
+
+    def __call__(self, domain):
+        """Evaluate windfield based on values found in domain
+        """
+
+        from math import pi, cos, sin, sqrt
+        from Numeric import Float, ones, ArrayType
+
+        xmom_update = domain.quantities['xmomentum'].explicit_update
+
+        N = domain.number_of_elements
+        t = domain.time
+
+        if callable(self.speed):
+            xc = domain.get_centroid_coordinates()
+            s_vec = self.speed(t, xc)
+        else:
+            #Assume s is a scalar
+
+            try:
+                s_vec = self.speed * ones(N, Float)
+            except:
+                msg = 'Speed must be either callable or a scalar: %s' %self.s
+                raise msg
+
+
+        if callable(self.phi):
+            xc = domain.get_centroid_coordinates()
+            phi_vec = self.phi(t, xc)
+        else:
+            #Assume phi is a scalar
+
+            try:
+                phi_vec = self.phi * ones(N, Float)
+            except:
+                msg = 'Angle must be either callable or a scalar: %s' %self.phi
+                raise msg
+
+        #assign_windfield_values(xmom_update, ymom_update,
+        #                        s_vec, phi_vec, self.const)
+        assign_windfield_values(xmom_update, s_vec, phi_vec, self.const)
+
+
+#def assign_windfield_values(xmom_update, ymom_update,
+#                            s_vec, phi_vec, const):
+def assign_windfield_values(xmom_update, s_vec, phi_vec, const):
+    """Python version of assigning wind field to update vectors.
+    A c version also exists (for speed)
+    """
+    from math import pi, cos, sin, sqrt
+
+    N = len(s_vec)
+    for k in range(N):
+        s = s_vec[k]
+        phi = phi_vec[k]
+
+        #Convert to radians
+        phi = phi*pi/180
+
+        #Compute velocity vector (u, v)
+        u = s*cos(phi)
+        v = s*sin(phi)
+
+        #Compute wind stress
+        S = const * u
+        xmom_update[k] += S*u
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/error.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/error.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/error.py	(revision 7837)
@@ -0,0 +1,9 @@
+## module error
+''' err(string).
+    Prints 'string' and terminates program.
+'''    
+import sys
+def err(string):
+    print string
+    raw_input('Press return to exit')
+    sys.exit()
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/gaussPivot.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/gaussPivot.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/gaussPivot.py	(revision 7837)
@@ -0,0 +1,43 @@
+## module gaussPivot
+''' x = gaussPivot(a,b,tol=1.0e-9).
+    Solves [a]{x} = {b} by Gauss elimination with
+    scaled row pivoting
+'''    
+from Numeric import *
+import swap 
+import error
+
+def gaussPivot(a,b,tol=1.0e-12):
+    n = len(b)
+    
+  # Set up scale factors
+    s = zeros((n),Float)
+    for i in range(n):
+        s[i] = max(abs(a[i,:]))
+            
+    for k in range(0,n-1):
+        
+      # Row interchange, if needed
+        p = int(argmax(abs(a[k:n,k])/s[k:n])) + k
+        if abs(a[p,k]) < tol: error.err('Matrix is singular')
+        if p != k:
+            swap.swapRows(b,k,p)
+            swap.swapRows(s,k,p)
+            swap.swapRows(a,k,p)
+            
+      # Elimination
+        for i in range(k+1,n):
+            if a[i,k] != 0.0:
+                lam = a[i,k]/a[k,k]
+                a[i,k+1:n] = a [i,k+1:n] - lam*a[k,k+1:n]
+                b[i] = b[i] - lam*b[k]
+    if abs(a[n-1,n-1]) < tol: error.err('Matrix is singular')
+                   
+  # Back substitution
+    for k in range(n-1,-1,-1):
+        b[k] = (b[k] - dot(a[k,k+1:n],b[k+1:n]))/a[k,k]
+    return b
+
+
+
+        
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/generic_boundary_conditions.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/generic_boundary_conditions.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/generic_boundary_conditions.py	(revision 7837)
@@ -0,0 +1,548 @@
+"""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 zeros, Float
+        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 array, Float
+        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 array, Float
+        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 Numeric 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 array, zeros, Float
+        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 Numeric 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 zeros, Float, 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: anuga_work/development/sudi/sw_1d/periodic_waves/cg/parameter.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/parameter.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/parameter.py	(revision 7837)
@@ -0,0 +1,81 @@
+from scipy.special import jn
+from scipy import pi, sqrt, linspace, pi, sin, cos
+from config import g
+from Numeric import zeros, Float
+from rootsearch import *
+from bisect import *
+
+def j0(x):
+    return jn(0.0, x)
+
+def j1(x):
+    return jn(1.0, x)
+
+def j2(x):
+    return jn(2.0, x)
+
+def j3(x):
+    return jn(3.0, x)
+
+def jm1(x):
+    return jn(-1.0, x)
+
+def jm2(x):
+    return jn(-2.0, x)
+
+
+"""
+##==========================================================================##
+#DIMENSIONAL PARAMETERS
+L = 5e4                 # Length of channel (m)
+h_0 = 5e2               # Height at origin when the water is still
+N = 550                 # Number of computational cells????????????????
+cell_len = 1.1*L/N      # Origin = 0.0
+Tp = 15.0*60.0                           # Period of oscillation
+a = 1.0                                 # Amplitude at origin
+X = linspace(-0.5*cell_len, 1.1*L+0.5*cell_len, N+2)             # Discretized spatial domain
+##=========================================================================##
+"""
+#DIMENSIONAL PARAMETERS
+L = 5e4                 # Length of channel (m)
+h_0 = 5e2               # Height at origin when the water is still
+numb = 550                 # initial Number of computational cells
+cell_len = 100.0#100.0 is actually 1.1*L/numb
+Tp = 15.0*60.0                           # Period of oscillation
+a =1.0                                  # Amplitude at origin
+               
+points = zeros(numb+2,Float)
+for i in range(numb+2):
+        points[i] = i*cell_len - 0.5*cell_len
+N = len(points)-1       # Number of computational cells
+
+
+#DIMENSIONLESS PARAMETERS
+eps = a/h_0
+T = Tp*sqrt(g*h_0)/L
+A = eps/j0(4.0*pi/T)
+
+def w_at_O_JOHNS(t):
+    return eps*cos(2.0*pi*t/T)
+
+def u_at_O_JOHNS(t):
+    a = -1.01#-1.0
+    b = 1.01#1.0
+    dx = 0.01
+    w = w_at_O_JOHNS(t)
+    def fun(u):
+        return u + A*j1(4.0*pi/T*(1.0+w)**0.5)*sin(2.0*pi/T*(t+u))/(1+w)**0.5
+    while 1:
+        x1,x2 = rootsearch(fun,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(fun,x1,x2,1)
+        else:
+            break
+    return root
+
+
+def prescribe_at_O_JOHNS(t):
+    w = w_at_O_JOHNS(t)
+    u = u_at_O_JOHNS(t)
+    return w, u
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/quantity.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/quantity.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/quantity.py	(revision 7837)
@@ -0,0 +1,1038 @@
+"""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 array, zeros, Float
+
+        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 zeros, Float
+        
+        #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 array, Float
+
+        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 concatenate, zeros, Float, Int, 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 sum, equal, ones, Float
+
+        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 array, zeros, Float
+
+        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 array, zeros, Float,sign
+        
+        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 zeros, Float
+
+        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 zeros, Float
+        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):
+            #Note: neighbours=[-1, {0, 1, 2, ..., N-1}, -2]
+            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):
+            #Note: neighbours=[-1, {0, 1, 2, ..., N-1}, -2]            
+            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])
+            elif n1 < 0:
+                phi = (qc[k] - qc[k-1])/(C[k] - C[k-1])
+            else:
+                if limiter == "minmod":
+                    phi = minmod(beta_p[k],beta_m[k])
+                elif limiter == "minmod_kurganov":
+                    # 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 zeros, Float
+        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"
+
+
+##
+##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))
+
+
+#####The following is a UNIT TEST##########
+
+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 domain_cg import Domain    
+    from Numeric 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: anuga_work/development/sudi/sw_1d/periodic_waves/cg/rootsearch.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/rootsearch.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/rootsearch.py	(revision 7837)
@@ -0,0 +1,15 @@
+## module rootsearch
+''' x1,x2 = rootsearch(f,a,b,dx).
+    Searches the interval (a,b) in increments dx for
+    the bounds (x1,x2) of the smallest root of f(x). 
+    Returns x1 = x2 = None if no roots were detected.
+'''   
+def rootsearch(f,a,b,dx):
+    x1 = a; f1 = f(a)
+    x2 = a + dx; f2 = f(x2)
+    while f1*f2 > 0.0:
+        if x1  >=  b: return None,None
+        x1 = x2; f1 = f2
+        x2 = x1 + dx; f2 = f(x2)
+    else:
+        return x1,x2
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-discrepancy.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-discrepancy.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-discrepancy.py	(revision 7837)
@@ -0,0 +1,127 @@
+import os
+from scipy.special import jn
+from scipy import sin, cos, sqrt, linspace, pi, zeros
+from rootsearch import *
+from bisect import *
+from Numeric import zeros,Float,dot
+from gaussPivot import *
+from config import g
+from analytical_prescription import *
+
+
+def j0(x):
+    return jn(0.0, x)
+
+def j1(x):
+    return jn(1.0, x)
+
+def j2(x):
+    return jn(2.0, x)
+
+def j3(x):
+    return jn(3.0, x)
+
+def jm1(x):
+    return jn(-1.0, x)
+
+def jm2(x):
+    return jn(-2.0, x)
+
+def bed(x):
+    return x-1.0
+
+
+def w_at_O(t):
+    return eps*cos(2.0*pi*t/T)
+
+def u_at_O(t):
+    a = -1.01#-1.0
+    b = 1.01#1.0
+    dx = 0.01
+    w = w_at_O(t)
+    def fun(u):
+        return u + A*j1(4.0*pi/T*(1.0+w)**0.5)*sin(2.0*pi/T*(t+u))/(1.0+w)**0.5
+    while 1:
+        x1,x2 = rootsearch(fun,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(fun,x1,x2,1)
+        else:
+            break
+    return root
+
+"""
+##==========================================================================##
+#DIMENSIONAL PARAMETERS
+L = 5e4                 # Length of channel (m)
+h_0 = 5e2               # Height at origin when the water is still
+Tp = 15.0*60.0                           # Period of oscillation
+a = 1.0                                 # Amplitude at origin
+##=========================================================================##
+#DIMENSIONLESS PARAMETERS
+eps = a/h_0
+T = Tp*sqrt(g*h_0)/L
+A = eps/j0(4.0*pi/T)
+"""
+
+
+Time = linspace(0.0,T,100)
+N_T = len(Time)
+
+
+Stage = zeros(N_T, Float)    
+Veloc = zeros(N_T, Float)
+for i in range(N_T):
+    t=Time[i]
+    zet, vel = prescribe(0.0,t)
+    Stage[i] = zet
+    Veloc[i] = vel
+
+
+Stage_johns = zeros(N_T, Float)    
+Veloc_johns = zeros(N_T, Float)
+for i in range(N_T):
+    t=Time[i]
+    Stage_johns[i] = w_at_O(t)
+    Veloc_johns[i] = u_at_O(t)
+
+"""
+num=len(Stage)
+error_w=(1.0/num)*sum(abs(Stage-Stage_johns))*h_0
+error_u=(1.0/num)*sum(abs(Veloc-Veloc_johns))*sqrt(g*h_0)
+print "error_w=", error_w
+print "error_u=", error_u
+
+"""
+
+from pylab import clf,plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+hold(False)
+clf()
+plot1 = subplot(211)
+plot(Time/T,Stage*h_0,'b-', Time/T,Stage_johns*h_0,'k--')
+xlabel('t/T')
+ylabel('Stage')
+#plot1.set_xlim([0.000,0.030])
+#plot1.set_ylim([0.980,1.005]) #([-9.0e-3,9.0e-3])
+legend(('C-G', 'Johns'),
+       'lower left', shadow=False)
+
+plot2 = subplot(212)
+plot(Time/T,Veloc*sqrt(g*h_0),'b-', Time/T,Veloc_johns*sqrt(g*h_0),'k--')
+xlabel('t/T')
+ylabel('Velocity')
+#plot1.set_xlim([0.0,1.1])
+#plot2.set_ylim([-0.05,0.05]) #([-1.0e-12,1.0e-12])
+legend(('C-G', 'Johns'),
+       'upper right', shadow=False)
+
+
+#filename = "discrepancy-closer"
+#filename += str(i)
+#filename += ".eps"
+#savefig(filename)
+#show()
+
+#plot(Time,Vel_at_O)
+#show()
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-plot.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-plot.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-plot.py	(revision 7837)
@@ -0,0 +1,245 @@
+#################Opening analytical solution################
+infile = open('analytical_1230_12300.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+position = zeros(len(table),Float)
+analitW12300 = zeros(len(table),Float)
+analitP12300 = zeros(len(table),Float)
+analitZ12300 = zeros(len(table),Float)
+analitH12300 = zeros(len(table),Float)
+analitU12300 = zeros(len(table),Float)
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==0:
+            position[r] = table[r][c]
+        elif c==1:
+            analitW12300[r] = table[r][c]
+        elif c==2:
+            analitP12300[r] = table[r][c]
+        elif c==3:
+            analitZ12300[r] = table[r][c]
+        elif c==4:
+            analitH12300[r] = table[r][c]
+        elif c==5:
+            analitU12300[r] = table[r][c]            
+
+#################Opening numerical_cg solution################
+infile = open('numerical_cg_1230_12300.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+numeric_cgW12300 = zeros(len(table),Float)
+numeric_cgP12300 = zeros(len(table),Float)
+numeric_cgZ12300 = zeros(len(table),Float)
+numeric_cgH12300 = zeros(len(table),Float)
+numeric_cgU12300 = zeros(len(table),Float)
+
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==1:
+            numeric_cgW12300[r] = table[r][c]
+        elif c==2:
+            numeric_cgP12300[r] = table[r][c]
+        elif c==3:
+            numeric_cgZ12300[r] = table[r][c]
+        elif c==4:
+            numeric_cgH12300[r] = table[r][c]
+        elif c==5:
+            numeric_cgU12300[r] = table[r][c]
+            
+
+
+#################Opening numerical_johns solution################
+infile = open('numerical_johns_1230_12300.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+numeric_johnsW12300 = zeros(len(table),Float)
+numeric_johnsP12300 = zeros(len(table),Float)
+numeric_johnsZ12300 = zeros(len(table),Float)
+numeric_johnsH12300 = zeros(len(table),Float)
+numeric_johnsU12300 = zeros(len(table),Float)
+
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==1:
+            numeric_johnsW12300[r] = table[r][c]
+        elif c==2:
+            numeric_johnsP12300[r] = table[r][c]
+        elif c==3:
+            numeric_johnsZ12300[r] = table[r][c]
+        elif c==4:
+            numeric_johnsH12300[r] = table[r][c]
+        elif c==5:
+            numeric_johnsU12300[r] = table[r][c]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+#################Opening analytical solution################
+infile = open('analytical_1260_12600.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+position = zeros(len(table),Float)
+analitW12600 = zeros(len(table),Float)
+analitP12600 = zeros(len(table),Float)
+analitZ12600 = zeros(len(table),Float)
+analitH12600 = zeros(len(table),Float)
+analitU12600 = zeros(len(table),Float)
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==0:
+            position[r] = table[r][c]
+        elif c==1:
+            analitW12600[r] = table[r][c]
+        elif c==2:
+            analitP12600[r] = table[r][c]
+        elif c==3:
+            analitZ12600[r] = table[r][c]
+        elif c==4:
+            analitH12600[r] = table[r][c]
+        elif c==5:
+            analitU12600[r] = table[r][c]            
+
+#################Opening numerical_cg solution################
+infile = open('numerical_cg_1260_12600.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+numeric_cgW12600 = zeros(len(table),Float)
+numeric_cgP12600 = zeros(len(table),Float)
+numeric_cgZ12600 = zeros(len(table),Float)
+numeric_cgH12600 = zeros(len(table),Float)
+numeric_cgU12600 = zeros(len(table),Float)
+
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==1:
+            numeric_cgW12600[r] = table[r][c]
+        elif c==2:
+            numeric_cgP12600[r] = table[r][c]
+        elif c==3:
+            numeric_cgZ12600[r] = table[r][c]
+        elif c==4:
+            numeric_cgH12600[r] = table[r][c]
+        elif c==5:
+            numeric_cgU12600[r] = table[r][c]
+            
+
+
+#################Opening numerical_johns solution################
+infile = open('numerical_johns_1260_12600.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+numeric_johnsW12600 = zeros(len(table),Float)
+numeric_johnsP12600 = zeros(len(table),Float)
+numeric_johnsZ12600 = zeros(len(table),Float)
+numeric_johnsH12600 = zeros(len(table),Float)
+numeric_johnsU12600 = zeros(len(table),Float)
+
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==1:
+            numeric_johnsW12600[r] = table[r][c]
+        elif c==2:
+            numeric_johnsP12600[r] = table[r][c]
+        elif c==3:
+            numeric_johnsZ12600[r] = table[r][c]
+        elif c==4:
+            numeric_johnsH12600[r] = table[r][c]
+        elif c==5:
+            numeric_johnsU12600[r] = table[r][c]
+
+
+
+#################PLOTTING THE RESULTS##############################################
+from pylab import clf,plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot,ion
+hold(False)
+clf()
+
+plot1 = subplot(311)
+plot(#position*1e-4,analitW12300, position*1e-4,numeric_cgW12300, position*1e-4,numeric_johnsW12300,
+     position*1e-4,analitW12600, position*1e-4,numeric_cgW12600, position*1e-4,numeric_johnsW12600,
+     position*1e-4,analitZ12300,'k-')
+#xlabel('Position')
+ylabel('Stage')
+#plot1.set_xlim([0.0,1.2])
+#plot1.set_ylim([-5.0,3.0])#([-9.0e-3,9.0e-3])
+#legend(('Analytical Solution', 'C-G Solution', 'Johns Solution'),
+#       'lower left', shadow=False)
+
+plot2 = subplot(312)
+plot(#position*1e-4,analitP12300, position*1e-4,numeric_cgP12300, position*1e-4,numeric_johnsP12300)
+     position*1e-4,analitP12600, position*1e-4,numeric_cgP12600, position*1e-4,numeric_johnsP12600)
+#xlabel('Position')
+ylabel('Momentum')
+#plot1.set_xlim([0.0,1.2])
+#plot1.set_ylim([-4.0,3.0])#([-9.0e-3,9.0e-3])
+#legend(('Analytical Solution', 'C-G Solution', 'Johns Solution'),
+#       'lower left', shadow=False)
+
+
+plot3 = subplot(313)
+plot(#position*1e-4,analitU12300, position*1e-4,numeric_cgU12300, position*1e-4,numeric_johnsU12300)
+     position*1e-4,analitU12600, position*1e-4,numeric_cgU12600, position*1e-4,numeric_johnsU12600)
+xlabel('Position/10,000')
+ylabel('Velocity')
+#plot1.set_xlim([0.0,1.2])
+#plot3.set_ylim([-4.0,2.0])#([-9.0e-3,9.0e-3])
+legend(('Exact Solution', 'C-G Solution', 'Johns Solution'),
+       'lower left', shadow=False)
+
+filename = "%s" %("12600.eps")
+#savefig(filename)
+show()
+
+
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-program.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-program.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/run-program.py	(revision 7837)
@@ -0,0 +1,370 @@
+from scipy import sin, cos, sqrt, linspace, pi, dot
+from Numeric import zeros, Float, array
+from gaussPivot import *
+from analytical_prescription import *
+from parameter import *
+import os, time, csv, pprint
+from domain_cg import *
+from config import g, epsilon
+from rootsearch import *
+from bisect import *
+
+#Analytical computations#################################################################
+def root_g(a,b,t):
+    dx = 0.01
+    def g(u):
+        return u + 2.0*A*pi/T*sin(2.0*pi/T*(t+u))
+    while 1:
+        x1,x2 = rootsearch(g,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(g,x1,x2,1)
+        else:
+            break
+    return root
+def shore(t):
+    a = -1.0#-0.2#-1.0
+    b = 1.0#0.2#1.0
+    #dx = 0.01
+    u = root_g(a,b,t)
+    xi = -0.5*u*u + A*cos(2.0*pi/T*(t+u))
+    position = 1.0 + xi
+    return position, u
+
+
+
+
+#Numerical computations###################################################################
+def newtonRaphson2(f,q,tol=1.0e-15): ##1.0e-9 may be too large
+    for i in range(30):                                                                                                                                    
+        h = 1.0e-4      ##1.0e-4 may be too large.
+        n = len(q)
+        jac = zeros((n,n),Float)
+        if 1.0+q[0]-x<0.0:
+            temp1 = 1.0+q[0]-x
+            q[0] = q[0]-temp1
+            q[1] = v
+            return q
+        f0 = f(q)
+        for i in range(n):
+            temp = q[i]
+            q[i] = temp + h
+            f1 = f(q)
+            q[i] = temp
+            jac[:,i] = (f1 - f0)/h
+        if sqrt(dot(f0,f0)/len(q)) < tol: return q
+        dq = gaussPivot(jac,-f0)
+        q = q + dq
+        if sqrt(dot(dq,dq)) < tol*max(max(abs(q)),1.0): return q
+    print 'Too many iterations'
+
+def elevation(X):
+    N = len(X)
+    z = zeros(N,Float)
+    for i in range(N):
+        z[i] = (h_0/L)*X[i] - h_0
+    return z
+
+def height(X):
+    N = len(X)
+    z = zeros(N,Float)
+    for i in range(N):
+        z[i] = h_0 - (h_0/L)*X[i]
+    return z
+
+def velocity(X):
+    N = len(X)
+    return zeros(N,Float)
+    
+boundary = { (0,0): 'left',(N-1,1): 'right'}
+
+domain = Domain(points,boundary)
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.beta = 1.0
+domain.set_limiter("minmod")
+
+
+def f_CG(t):
+    timing = t*sqrt(g*h_0)/L
+    w, u = prescribe(0.0,timing)
+    wO = w*h_0
+    uO = u*sqrt(g*h_0)
+    zO = -h_0
+    hO = wO - zO
+    pO = uO * hO
+    #[    'stage', 'xmomentum', 'elevation', 'height', 'velocity']
+    return [wO,  pO,   zO,      hO,      uO]
+def f_JOHNS(t):
+    timing = t*sqrt(g*h_0)/L
+    w, u = prescribe_at_O_JOHNS(timing)
+    wO = w*h_0
+    uO = u*sqrt(g*h_0)
+    zO = -h_0
+    hO = wO - zO
+    pO = uO * hO
+    #[    'stage', 'xmomentum', 'elevation', 'height', 'velocity']
+    return [wO,  pO,   zO,      hO,      uO]
+
+T1 = Time_boundary(domain,f_CG)
+D2 = Dirichlet_boundary([50.5,  0.0,  50.5,  0.0,  0.0])
+domain.set_boundary({'left':T1,'right':D2})
+
+domain.set_quantity('height',height)
+domain.set_quantity('elevation',elevation)
+domain.set_quantity('velocity',velocity)
+
+
+Ver = domain.vertices
+n_V = len(Ver)
+AnalitW_V = zeros((n_V,2), Float)
+AnalitP_V = zeros((n_V,2), Float)
+AnalitZ_V = zeros((n_V,2), Float)
+AnalitH_V = zeros((n_V,2), Float)
+AnalitU_V = zeros((n_V,2), Float)
+
+Cen = domain.centroids
+n_C = len(Cen)
+AnalitW_C = zeros(n_C, Float)
+AnalitP_C = zeros(n_C, Float)
+AnalitZ_C = zeros(n_C, Float)
+AnalitH_C = zeros(n_C, Float)
+AnalitU_C = zeros(n_C, Float)
+
+waktu = 10.0     #3.0*60.0
+WAKTU = 12690.0  #20.0*Tp  #Note: Tp=15.0*60.0
+yieldstep = finaltime = waktu
+t0 = time.time()
+counter=1
+
+shorelines_numerical_cg = zeros(int(WAKTU/waktu), Float)
+shorelines_analytical = zeros(int(WAKTU/waktu), Float)
+time_instants = zeros(int(WAKTU/waktu), Float)
+
+
+while finaltime < WAKTU+0.1:
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        domain.write_time()
+    time_instants[counter-1] = domain.time
+    
+    Stage = domain.quantities['stage']
+    Momentum = domain.quantities['xmomentum']
+    Elevation = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+    StageV = Stage.vertex_values
+    MomV = Momentum.vertex_values
+    ElevationV = Elevation.vertex_values
+    HeightV = Height.vertex_values
+    VelV = Velocity.vertex_values
+    
+    StageC = Stage.centroid_values
+    MomC = Momentum.centroid_values
+    ElevationC = Elevation.centroid_values
+    HeightC = Height.centroid_values
+    VelC = Velocity.centroid_values
+
+    table = zeros((len(Ver.flat),6),Float)
+    for r in range(len(Ver.flat)):
+        for c in range(6):
+            if c==0:
+                table[r][c] = Ver.flat[r]
+            elif c==1:
+                table[r][c] = StageV.flat[r]
+            elif c==2:
+                table[r][c] = MomV.flat[r]
+            elif c==3:
+                table[r][c] = ElevationV.flat[r]
+            elif c==4:
+                table[r][c] = HeightV.flat[r]                
+            else:
+                table[r][c] = VelV.flat[r]
+
+    outname = "%s%04i%s%f%s" %("numerical_cg_", counter, "_", domain.time, ".csv")                
+    outfile = open(outname, 'w')
+    writer = csv.writer(outfile)
+    for row in table:
+        writer.writerow(row)        
+    outfile.close()    
+    
+
+    for s in range(2*n_V):
+        heiL = HeightV.flat[s]
+        momR = MomV.flat[s+1]
+        if heiL >= 1e-6:
+            if abs(momR)==0.0: #<1e-15:
+                break
+    #print "s+1=",s+1
+    shorelines_numerical_cg[counter-1] = Ver.flat[s+1]
+    #print "shorelines_numerical_cg=",shorelines_numerical_cg[counter-1]
+
+
+    #print "Now the ANALYTIC"
+    pos_shore, vel_shore = shore(domain.time*sqrt(g*h_0)/L) #dimensionless
+    pos_shore = pos_shore*L
+    vel_shore = vel_shore*sqrt(g*h_0)
+
+    shorelines_analytical[counter-1] = pos_shore
+
+    #The following is for calculating the error at centroids
+    for i in range(n_C):
+        x = Cen[i]
+        if x < pos_shore:
+            sta, vel = prescribe(x/L,domain.time*sqrt(g*h_0)/L) #dimensionless
+            AnalitW_C[i] = sta*h_0
+            AnalitU_C[i] = vel                            #It needs dimensionalisation
+            AnalitZ_C[i] = (h_0/L)*x - h_0
+            AnalitH_C[i] = AnalitW_C[i] - AnalitZ_C[i]
+            AnalitP_C[i] = AnalitH_C[i]*AnalitU_C[i]  #It needs dimensionalisation
+        else:
+            AnalitW_C[i] = (h_0/L)*x - h_0                 
+            AnalitU_C[i] = 0.0
+            AnalitZ_C[i] = (h_0/L)*x - h_0
+            AnalitH_C[i] = 0.0
+            AnalitP_C[i] = 0.0
+    AnalitU_C = AnalitU_C*sqrt(g*h_0) #This is the dimensionalisation
+    AnalitP_C = AnalitP_C*sqrt(g*h_0) #This is the dimensionalisation
+
+    error_W = (1.0/n_C)*sum(abs(StageC-AnalitW_C))
+    error_P = (1.0/n_C)*sum(abs(MomC-AnalitP_C))
+    error_U = (1.0/n_C)*sum(abs(VelC-AnalitU_C))
+    table = zeros((1,4),Float)
+    for r in range(1):
+        for c in range(4):
+            if c==0:
+                table[r][c] = domain.time
+            elif c==1:
+                table[r][c] = error_W
+            elif c==2:
+                table[r][c] = error_P
+            else:
+                table[r][c] = error_U
+    outname = "%s%04i%s%f%s" %("error_cg_", counter, "_", domain.time, ".csv")                
+    outfile = open(outname, 'w')
+    writer = csv.writer(outfile)
+    for row in table:
+        writer.writerow(row)        
+    outfile.close()
+
+
+    #The following is for ploting the quantities at vertex values
+    for i in range(n_V):
+        vector_x = Ver[i]
+        for k in range(2):
+            x = vector_x[k]
+            if x < pos_shore:
+                sta, vel = prescribe(x/L,domain.time*sqrt(g*h_0)/L) #dimensionless
+                AnalitW_V[i,k] = sta*h_0
+                AnalitU_V[i,k] = vel                            #It needs dimensionalisation
+                AnalitZ_V[i,k] = (h_0/L)*x - h_0
+                AnalitH_V[i,k] = AnalitW_V[i,k] - AnalitZ_V[i,k]
+                AnalitP_V[i,k] = AnalitH_V[i,k]*AnalitU_V[i,k]  #It needs dimensionalisation
+            else:
+                AnalitW_V[i,k] = (h_0/L)*x - h_0                 
+                AnalitU_V[i,k] = 0.0
+                AnalitZ_V[i,k] = (h_0/L)*x - h_0
+                AnalitH_V[i,k] = 0.0
+                AnalitP_V[i,k] = 0.0
+    AnalitU_V = AnalitU_V*sqrt(g*h_0) #This is the dimensionalisation
+    AnalitP_V = AnalitP_V*sqrt(g*h_0) #This is the dimensionalisation
+
+
+    table = zeros((len(Ver.flat),6),Float)
+    for r in range(len(Ver.flat)):
+        for c in range(6):
+            if c==0:
+                table[r][c] = Ver.flat[r]
+            elif c==1:
+                table[r][c] = AnalitW_V.flat[r]
+            elif c==2:
+                table[r][c] = AnalitP_V.flat[r]
+            elif c==3:
+                table[r][c] = AnalitZ_V.flat[r]
+            elif c==4:
+                table[r][c] = AnalitH_V.flat[r]                
+            else:
+                table[r][c] = AnalitU_V.flat[r]
+
+    outname = "%s%04i%s%f%s" %("analytical_", counter, "_", domain.time, ".csv")                
+    outfile = open(outname, 'w')
+    writer = csv.writer(outfile)
+    for row in table:
+        writer.writerow(row)        
+    outfile.close()
+
+    
+    from pylab import clf,plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot,ion
+    hold(False)
+    clf()
+
+    plot1 = subplot(311)
+    plot(Ver/1e+4,AnalitW_V,'b-',  Ver/1e+4,StageV,'g-',  Ver/1e+4,ElevationV,'k-')
+    #plot(Ver,StageV, Ver,ElevationV)
+    #plot(Ver/L,StageV/h_0,  Ver/L,ElevationV/h_0)
+    #xlabel('Position')
+    ylabel('Stage')
+    #plot1.set_xlim([0.0,1.2])
+    plot1.set_ylim([-6.0,6.0])#([-9.0e-3,9.0e-3])
+    #legend(('Analytical Solution', 'Numerical Solution', 'Discretized Bed'),
+    #       'upper right', shadow=False)
+    
+    plot2 = subplot(312)
+    plot(Ver/1e+4,AnalitP_V,'b-',  Ver/1e+4,MomV,'g-')
+    #plot(Ver/L, VelV/sqrt(g*h_0))
+    #xlabel('Position')
+    ylabel('Momentum')
+    #plot2.set_xlim([0.0,1.2])
+    #legend(('Analytical Solution','Numerical Solution'),
+    #       'upper right', shadow=False)        
+
+    plot3 = subplot(313)
+    plot(Ver/1e+4,AnalitU_V,'b-',  Ver/1e+4,VelV,'g-')
+    #plot(Ver/L, VelV/sqrt(g*h_0))
+    xlabel('Position / 10,000')
+    ylabel('Velocity')
+    #plot2.set_xlim([0.0,1.2])
+    legend(('Analytical Solution','Numerical Solution'),
+           'upper center', shadow=False)
+    
+    #filename = "%s%04i%s%f%s" %("numerical_cg_", counter,"_", domain.time, ".png")
+    #savefig(filename)
+    #show()
+    #raw_input("Press ENTER to continue")
+    
+    counter = counter+1
+    finaltime = finaltime + waktu
+    
+
+table = zeros((int(WAKTU/waktu), 2),Float)
+for r in range(int(WAKTU/waktu)):
+    for c in range(2):
+        if c==0:
+            table[r][c] = time_instants[r]               
+        else:
+            table[r][c] = shorelines_numerical_cg[r]
+
+outname = "%s" %("shore_numerical_cg.csv")                
+outfile = open(outname, 'w')
+writer = csv.writer(outfile)
+for row in table:
+    writer.writerow(row)        
+outfile.close()
+
+
+table = zeros((int(WAKTU/waktu), 2),Float)
+for r in range(int(WAKTU/waktu)):
+    for c in range(2):
+        if c==0:
+            table[r][c] = time_instants[r]               
+        else:
+            table[r][c] = shorelines_analytical[r]
+
+outname = "%s" %("shore_analytical.csv")                
+outfile = open(outname, 'w')
+writer = csv.writer(outfile)
+for row in table:
+    writer.writerow(row)        
+outfile.close()
+
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/swap.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/swap.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/swap.py	(revision 7837)
@@ -0,0 +1,27 @@
+## module swap
+''' swapRows(v,i,j).
+    Swaps rows i and j of vector or matrix [v].
+
+    swapCols(v,i,j).
+    Swaps columns i and j of matrix [v].
+
+def swapRows(v,i,j):
+    if len(v.getshape()) == 1: v[i],v[j] = v[j],v[i]
+    else:
+        temp = v[i].copy()
+        v[i] = v[j]
+        v[j] = temp
+'''
+
+def swapRows(v,i,j):
+    if len(v.flat) == 2:
+        v[i],v[j] = v[j],v[i]
+    else:
+        temp = v[i].copy()
+        v[i] = v[j]
+        v[j] = temp      
+
+def swapCols(v,i,j):
+    temp = v[:,j].copy()
+    v[:,j] = v[:,i]
+    v[:,i] = temp
Index: anuga_work/development/sudi/sw_1d/periodic_waves/cg/util.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/cg/util.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/cg/util.py	(revision 7837)
@@ -0,0 +1,174 @@
+"""
+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 zeros, Float,sqrt,sin,cos
+
+    
+    #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: anuga_work/development/sudi/sw_1d/periodic_waves/johns/analytical_prescription.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/analytical_prescription.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/analytical_prescription.py	(revision 7837)
@@ -0,0 +1,65 @@
+from scipy import sin, cos, sqrt, pi, dot
+from gaussPivot import *
+from parameter import *
+
+def root_g(a,b,t):
+    dx = 0.01
+    def g(u):
+        return u + 2.0*A*pi/T*sin(2.0*pi/T*(t+u))
+    while 1:
+        x1,x2 = rootsearch(g,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(g,x1,x2,1)
+        else:
+            break
+    return root
+def shore(t):
+    a = -0.2#-1.0
+    b = 0.2#1.0
+    #dx = 0.01
+    u = root_g(a,b,t)
+    xi = -0.5*u*u + A*cos(2.0*pi/T*(t+u))
+    #position = 1.0 + xi
+    return [xi, u]#[position, u]
+
+
+
+def prescribe(x,t):
+    from Numeric import array, zeros, Float
+    if x<1.0:
+        q = zeros(2,Float)
+    else:
+        q = shore(t)
+    def fun(q): #Here q=(w, u)
+        f = zeros(2,Float)
+        f[0] = q[0] + 0.5*q[1]**2.0 - A*j0(4.0*pi/T*(1.0+q[0]-x)**0.5)*cos(2.0*pi/T*(t+q[1]))
+        f[1] = q[1] + A*j1(4.0*pi/T*(1.0+q[0]-x)**0.5)*sin(2.0*pi/T*(t+q[1]))/(1+q[0]-x)**0.5
+        return f
+    def newtonRaphson2(f,q,tol=1.0e-15):
+        for i in range(30):                                                                                                                                    
+            h = 1.0e-4      ##1.0e-4 may be too large.
+            n = len(q)
+            jac = zeros((n,n),Float)
+            if 1.0+q[0]-x<0.0:
+                #temp1 = 1.0+q[0]-x
+                #q[0] = q[0]-temp1
+                q[1] = SomethingWRONG
+                #return q
+                #q[0] =0.25
+            f0 = f(q)
+            for i in range(n):
+                temp = q[i]
+                q[i] = temp + h
+                f1 = f(q)
+                q[i] = temp
+                jac[:,i] = (f1 - f0)/h
+            if sqrt(dot(f0,f0)/len(q)) < tol: return q
+            dq = gaussPivot(jac,-f0)
+            q = q + dq
+            if sqrt(dot(dq,dq)) < tol*max(max(abs(q)),1.0): return q
+        print 'Too many iterations'
+    q = newtonRaphson2(fun,q)    
+    return q[0], q[1]
+
+#w,u=prescribe(0.0,0.0)
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/bisect.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/bisect.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/bisect.py	(revision 7837)
@@ -0,0 +1,28 @@
+## module bisect
+''' root = bisect(f,x1,x2,switch=0,tol=1.0e-9).
+    Finds a root of f(x) = 0 by bisection.
+    The root must be bracketed in (x1,x2).
+    Setting switch = 1 returns root = None if
+    f(x) increases as a result of a bisection.
+'''    
+from math import log,ceil
+import error
+
+def bisect(f,x1,x2,switch=0,epsilon=1.0e-15):#9):
+    f1 = f(x1)
+    if f1 == 0.0: return x1
+    f2 = f(x2)
+    if f2 == 0.0: return x2
+    if f1*f2 > 0.0: error.err('Root is not bracketed')
+    n = ceil(log(abs(x2 - x1)/epsilon)/log(2.0))
+    for i in range(n):
+        x3 = 0.5*(x1 + x2); f3 = f(x3)
+        if (switch == 1) and (abs(f3) >abs(f1)) \
+                         and (abs(f3) > abs(f2)):
+            return None   
+        if f3 == 0.0: return x3
+        if f2*f3 < 0.0:
+            x1 = x3; f1 = f3
+        else:
+            x2 = x3; f2 = f3
+    return (x1 + x2)/2.0
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/comp_flux_ext_wellbalanced.c
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/comp_flux_ext_wellbalanced.c	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/comp_flux_ext_wellbalanced.c	(revision 7837)
@@ -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: anuga_work/development/sudi/sw_1d/periodic_waves/johns/config.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/config.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/config.py	(revision 7837)
@@ -0,0 +1,112 @@
+"""Module where global model parameters are set for anuga_1d
+"""
+
+epsilon = 1.0e-6#12
+h0 = 1.0e-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.
+h_min = 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: anuga_work/development/sudi/sw_1d/periodic_waves/johns/desktop.ini
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/desktop.ini	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/desktop.ini	(revision 7837)
@@ -0,0 +1,4 @@
+[ViewState]
+Mode=
+Vid=
+FolderType=Documents
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/domain.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/domain.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/domain.py	(revision 7837)
@@ -0,0 +1,1369 @@
+"""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 array, zeros, Float, Int
+
+        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'
+        self.checkpoint = False
+
+    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 Numeric 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 array, Int
+
+        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 Numeric 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 zeros, Float
+        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 zeros, Float
+        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:
+                # 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
+                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
+
+
+    def evolve_one_euler_step(self, yieldstep, finaltime):
+        """
+        One Euler Time Step
+        Q^{n+1} = E(h) Q^n
+        """
+
+
+        # 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
+        
+
+
+    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()            
+
+        #--------------------------------------
+        # 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()   
+
+
+    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()            
+
+        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       
+        
+
+    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 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 zeros,Float
+
+        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 zeros,Float
+
+        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
+        from parameter import prescribe_at_O_JOHNS, h_0, L
+        from config import g
+        from math import sqrt 
+        def f_JOHNS(t):
+            timing = t*sqrt(g*h_0)/L
+            w, u = prescribe_at_O_JOHNS(timing)
+            wO = w*h_0
+            uO = u*sqrt(g*h_0)
+            zO = -h_0
+            hO = wO - zO
+            pO = uO * hO
+            #[    'stage', 'xmomentum', 'elevation', 'height', 'velocity']
+            return [wO,  pO,   zO,      hO,      uO]
+        tempor = f_JOHNS(self.time)
+        
+        self.quantities['stage'].centroid_values[0]     = tempor[0]
+        self.quantities['xmomentum'].centroid_values[0] = tempor[1]
+        self.quantities['elevation'].centroid_values[0] = tempor[2]
+        self.quantities['height'].centroid_values[0]    = tempor[3]
+        self.quantities['velocity'].centroid_values[0]  = tempor[4]
+        
+        
+    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,1] = VV[0,0] = BV[0]
+            VV[n-1,1] = BV[1]
+        
+        """
+        #Below is just for checking/testing
+        self.quantities['stage'].vertex_values[0,1]     = self.quantities['stage'].vertex_values[0,0]
+        self.quantities['xmomentum'].vertex_values[0,1] = self.quantities['xmomentum'].vertex_values[0,0]
+        self.quantities['elevation'].vertex_values[0,1] = self.quantities['elevation'].vertex_values[0,0]
+        self.quantities['height'].vertex_values[0,1]    = self.quantities['height'].vertex_values[0,0]
+        self.quantities['velocity'].vertex_values[0,1]  = self.quantities['velocity'].vertex_values[0,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 ones, sum, equal, Float
+
+        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: anuga_work/development/sudi/sw_1d/periodic_waves/johns/domain_johns.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/domain_johns.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/domain_johns.py	(revision 7837)
@@ -0,0 +1,1039 @@
+"""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
+"""
+
+
+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)
+        #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__ = 'domain_johns'
+	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)
+
+    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(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 ===============================
+
+#Rotation of momentum vector
+def rotate(q, normal, direction = 1):
+    """Rotate the momentum component q (q[1], q[2])
+    from x,y coordinates to coordinates based on normal vector.
+
+    If direction is negative the rotation is inverted.
+
+    Input vector is preserved
+
+    This function is specific to the shallow water wave equation
+    """
+
+    from Numeric import zeros, Float
+
+    assert len(q) == 3,\
+           'Vector of conserved quantities must have length 3'\
+           'for 2D shallow water equation'
+
+    try:
+        l = len(normal)
+    except:
+        raise 'Normal vector must be an Numeric array'
+
+    assert l == 2, 'Normal vector must have 2 components'
+
+
+    n1 = normal[0]
+    n2 = normal[1]
+
+    r = zeros(len(q), Float) #Rotated quantities
+    r[0] = q[0]              #First quantity, height, is not rotated
+
+    if direction == -1:
+        n2 = -n2
+
+
+    r[1] =  n1*q[1] + n2*q[2]
+    r[2] = -n2*q[1] + n1*q[2]
+
+    return r
+
+
+def flux_function(normal, ql, qr, zl, zr):
+    """Compute fluxes between volumes for the shallow water wave equation
+    cast in terms of w = h+z using the 'central scheme' as described in
+
+    Kurganov, Noelle, Petrova. 'Semidiscrete Central-Upwind Schemes For
+    Hyperbolic Conservation Laws and Hamilton-Jacobi Equations'.
+    Siam J. Sci. Comput. Vol. 23, No. 3, pp. 707-740.
+
+    The implemented formula is given in equation (3.15) on page 714
+
+    Conserved quantities w, uh, are stored as elements 0 and 1
+    in the numerical vectors ql an qr.
+
+    Bed elevations zl and zr.
+    """
+
+    from config import g, epsilon, h0
+    from math import sqrt
+    from Numeric import array
+
+    #Align momentums with x-axis
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+	
+    z = 0.5*(zl+zr) #Take average of field values
+
+    w_left  = q_left[0]   #w=h+z
+    h_left  = w_left-z
+    uh_left = q_left[1]
+
+    if h_left < epsilon:
+        u_left = 0.0  #Could have been negative
+        h_left = 0.0
+    else:
+        u_left  = uh_left/(h_left +  h0/h_left)
+
+
+    uh_left = u_left*h_left
+
+
+    w_right  = q_right[0]  #w=h+z
+    h_right  = w_right-z
+    uh_right = q_right[1]
+
+    if h_right < epsilon:
+        u_right = 0.0  #Could have been negative
+        h_right = 0.0
+    else:
+        u_right  = uh_right/(h_right + h0/h_right)
+
+    uh_right = u_right*h_right
+	
+
+    #We have got h and u at vertex, then the following is the calculation of fluxes!
+    soundspeed_left  = sqrt(g*h_left)
+    soundspeed_right = sqrt(g*h_right)
+
+    #Maximal wave speed
+    s_max = max(u_left+soundspeed_left, u_right+soundspeed_right, 0)
+    
+    #Minimal wave speed
+    s_min = min(u_left-soundspeed_left, u_right-soundspeed_right, 0)
+    
+    #Flux computation
+    flux_left  = array([u_left*h_left,
+                        u_left*uh_left + 0.5*g*h_left*h_left])
+    flux_right = array([u_right*h_right,
+                        u_right*uh_right + 0.5*g*h_right*h_right])
+
+    denom = s_max-s_min
+    if denom == 0.0:
+        edgeflux = array([0.0, 0.0])
+        max_speed = 0.0
+    else:
+        edgeflux = (s_max*flux_left - s_min*flux_right)/denom
+        edgeflux += s_max*s_min*(q_right-q_left)/denom
+        
+        edgeflux[1] = edgeflux[1]*normal
+
+        max_speed = max(abs(s_max), abs(s_min))
+
+    return edgeflux, max_speed
+
+#
+def compute_timestep(domain):
+    import sys
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    
+    stage = Stage.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+
+    stage_bdry = Stage.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+
+    flux = zeros(2, Float) #Work array for summing up fluxes
+    ql = zeros(2, Float)
+    qr = zeros(2, Float)
+
+    #Loop
+    timestep = float(sys.maxint)
+    enter = True
+    for k in range(N):
+
+        flux[:] = 0.  #Reset work array
+        for i in range(2):
+            #Quantities inside volume facing neighbour i
+            ql = [stage[k, i], xmom[k, i]]
+            zl = bed[k, i]
+
+            #Quantities at neighbour on nearest face
+            n = domain.neighbours[k,i]
+            if n < 0:
+                m = -n-1 #Convert negative flag to index
+                qr[0] = stage_bdry[m]
+                qr[1] = xmom_bdry[m]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                m = domain.neighbour_vertices[k,i]
+                qr[0] = stage[n, m]
+                qr[1] =  xmom[n, m]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+
+            edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+
+            #Update optimal_timestep
+            try:
+                timestep = min(timestep, domain.cfl*0.5*domain.areas[k]/max_speed)
+            except ZeroDivisionError:
+                pass
+
+    domain.timestep = timestep
+
+# Compute flux definition
+# ###################################
+def compute_fluxes_C_wellbalanced(domain):
+    import sys
+    from Numeric import zeros, Float
+    
+    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(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 zeros, Float
+    from config import epsilon, h0, h_min
+
+    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] <= 0.01:  #epsilon :
+	    #h_C[i] = 0.0
+	    #w_C[i] = z_C[i]
+	    uh_C[i] = 0.0
+	    u_C[i] = 0.0
+	    
+	if h_C[i] < epsilon: #h_min:
+            h_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 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
+            
+    
+def h_limiter(domain):
+    """Limit slopes for each volume to eliminate artificial variance
+    introduced by e.g. second order extrapolator
+
+    limit on h = w-z
+
+    This limiter depends on two quantities (w,z) so it resides within
+    this module rather than within quantity.py
+    """
+
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+    beta_h = domain.beta_h
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = wc - zc
+
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = wv-zv
+
+    hvbar = zeros(hv.shape, Float) #h-limited values
+
+    #Find min and max of this and neighbour's centroid values
+    hmax = zeros(hc.shape, Float)
+    hmin = zeros(hc.shape, Float)
+
+    for k in range(N):
+        hmax[k] = hmin[k] = hc[k]
+        for i in range(2):   
+            n = domain.neighbours[k,i]
+            if n >= 0:
+                hn = hc[n] #Neighbour's centroid value
+
+                hmin[k] = min(hmin[k], hn)
+                hmax[k] = max(hmax[k], hn)
+
+
+    #Diffences between centroids and maxima/minima
+    dhmax = hmax - hc
+    dhmin = hmin - hc
+
+    #Deltas between vertex and centroid values
+    dh = zeros(hv.shape, Float)
+    for i in range(2):
+        dh[:,i] = hv[:,i] - hc
+
+    #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 (dh[k,i] > 0): r = dhmax[k]/dh[k,i]
+            if (dh[k,i] < 0): r = dhmin[k]/dh[k,i]
+
+            phi = min( min(r*beta_h, 1), phi )
+
+        #Then update using phi limiter
+        for i in range(2):
+            hvbar[k,i] = hc[k] + phi*dh[k,i]
+
+    return hvbar
+
+def balance_deep_and_shallow(domain):
+    """Compute linear combination between stage as computed by
+    gradient-limiters limiting using w, and stage computed by
+    gradient-limiters limiting using h (h-limiter).
+    The former takes precedence when heights are large compared to the
+    bed slope while the latter takes precedence when heights are
+    relatively small.  Anything in between is computed as a balanced
+    linear combination in order to avoid numerical disturbances which
+    would otherwise appear as a result of hard switching between
+    modes.
+
+    The h-limiter is always applied irrespective of the order.
+    """
+
+    #Shortcuts
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = wc - zc
+
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = wv-zv
+
+    #Limit h
+    hvbar = h_limiter(domain)
+
+    for k in range(domain.number_of_elements):
+        #Compute maximal variation in bed elevation
+        #  This quantitiy is
+        #    dz = max_i abs(z_i - z_c)
+        #  and it is independent of dimension
+        #  In the 1d case zc = (z0+z1)/2
+        #  In the 2d case zc = (z0+z1+z2)/3
+
+        dz = max(abs(zv[k,0]-zc[k]),
+                 abs(zv[k,1]-zc[k]))#,
+#                 abs(zv[k,2]-zc[k]))
+
+
+        hmin = min( hv[k,:] )
+
+        #Create alpha in [0,1], where alpha==0 means using the h-limited
+        #stage and alpha==1 means using the w-limited stage as
+        #computed by the gradient limiter (both 1st or 2nd order)
+
+        #If hmin > dz/2 then alpha = 1 and the bed will have no effect
+        #If hmin < 0 then alpha = 0 reverting to constant height above bed.
+
+        if dz > 0.0:
+            alpha = max( min( 2*hmin/dz, 1.0), 0.0 )
+        else:
+            #Flat bed
+            alpha = 1.0
+
+        alpha  = 0.0
+	#Let
+	#
+	#  wvi be the w-limited stage (wvi = zvi + hvi)
+	#  wvi- be the h-limited state (wvi- = zvi + hvi-)
+	#
+	#
+	#where i=0,1,2 denotes the vertex ids
+	#
+        #Weighted balance between w-limited and h-limited stage is
+        #
+	#  wvi := (1-alpha)*(zvi+hvi-) + alpha*(zvi+hvi)
+	#
+        #It follows that the updated wvi is
+        #  wvi := zvi + (1-alpha)*hvi- + alpha*hvi
+        #
+	# Momentum is balanced between constant and limited
+
+
+        #for i in range(3):
+        #    wv[k,i] = zv[k,i] + hvbar[k,i]
+
+	#return
+
+	if alpha < 1:
+
+            #for i in range(3):
+            for i in range(2):
+                wv[k,i] = zv[k,i] + (1.0-alpha)*hvbar[k,i] + alpha*hv[k,i]
+
+            #Momentums at centroids
+            xmomc = domain.quantities['xmomentum'].centroid_values
+
+
+            #Momentums at vertices
+            xmomv = domain.quantities['xmomentum'].vertex_values
+
+
+            # Update momentum as a linear combination of
+            # xmomc and ymomc (shallow) and momentum
+            # from extrapolator xmomv and ymomv (deep).
+            xmomv[k,:] = (1.0-alpha)*xmomc[k] + alpha*xmomv[k,:]
+
+
+
+
+
+#########################
+#Standard forcing terms:
+#
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from util import gradient
+    from Numeric import zeros, Float, 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 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]
+
+def linear_friction(domain):
+    """Apply linear friction to water momentum
+
+    Assumes quantity: 'linear_friction' to be present
+    """
+
+    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
+    tau = domain.quantities['linear_friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+
+    N = domain.number_of_elements
+    eps = domain.minimum_allowed_height
+    g = domain.g #Not necessary? Why was this added?
+
+    for k in range(N):
+        if tau[k] >= eps:
+            if h[k] >= eps:
+            	S = -tau[k]/h[k]
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
+ #           	ymom_update[k] += S*vh[k]
+
+
+
+def check_forcefield(f):
+    """Check that f is either
+    1: a callable object f(t,x,y), where x and y are vectors
+       and that it returns an array or a list of same length
+       as x and y
+    2: a scalar
+    """
+
+    from Numeric import ones, Float, array
+
+
+    if callable(f):
+        N = 2
+        x = ones(2, Float)
+        
+        try:
+            q = f(1.0, x=x)
+        except Exception, e:
+            msg = 'Function %s could not be executed:\n%s' %(f, e)
+	    #FIXME: Reconsider this semantics
+            raise msg
+
+        try:
+            q = array(q).astype(Float)
+        except:
+            msg = 'Return value from vector function %s could ' %f
+            msg += 'not be converted into a Numeric array of floats.\n'
+            msg += 'Specified function should return either list or array.'
+            raise msg
+
+        #Is this really what we want?
+        msg = 'Return vector from function %s ' %f
+        msg += 'must have same lenght as input vectors'
+        assert len(q) == N, msg
+
+    else:
+        try:
+            f = float(f)
+        except:
+            msg = 'Force field %s must be either a scalar' %f
+            msg += ' or a vector function'
+            raise msg
+    return f
+
+class Wind_stress:
+    """Apply wind stress to water momentum in terms of
+    wind speed [m/s] and wind direction [degrees]
+    """
+
+    def __init__(self, *args, **kwargs):
+        """Initialise windfield from wind speed s [m/s]
+        and wind direction phi [degrees]
+
+        Inputs v and phi can be either scalars or Python functions, e.g.
+
+        W = Wind_stress(10, 178)
+
+        #FIXME - 'normal' degrees are assumed for now, i.e. the
+        vector (1,0) has zero degrees.
+        We may need to convert from 'compass' degrees later on and also
+        map from True north to grid north.
+
+        Arguments can also be Python functions of t,x,y as in
+
+        def speed(t,x,y):
+            ...
+            return s
+
+        def angle(t,x,y):
+            ...
+            return phi
+
+        where x and y are vectors.
+
+        and then pass the functions in
+
+        W = Wind_stress(speed, angle)
+
+        The instantiated object W can be appended to the list of
+        forcing_terms as in
+
+        Alternatively, one vector valued function for (speed, angle)
+        can be applied, providing both quantities simultaneously.
+        As in
+        W = Wind_stress(F), where returns (speed, angle) for each t.
+
+        domain.forcing_terms.append(W)
+        """
+
+        from config import rho_a, rho_w, eta_w
+        from Numeric import array, Float
+
+        if len(args) == 2:
+            s = args[0]
+            phi = args[1]
+        elif len(args) == 1:
+            #Assume vector function returning (s, phi)(t,x,y)
+            vector_function = args[0]
+            s = lambda t,x: vector_function(t,x=x)[0]
+            phi = lambda t,x: vector_function(t,x=x)[1]
+        else:
+           #Assume info is in 2 keyword arguments
+
+           if len(kwargs) == 2:
+               s = kwargs['s']
+               phi = kwargs['phi']
+           else:
+               raise 'Assumes two keyword arguments: s=..., phi=....'
+
+        print 'phi', phi
+        self.speed = check_forcefield(s)
+        self.phi = check_forcefield(phi)
+
+        self.const = eta_w*rho_a/rho_w
+
+
+    def __call__(self, domain):
+        """Evaluate windfield based on values found in domain
+        """
+
+        from math import pi, cos, sin, sqrt
+        from Numeric import Float, ones, ArrayType
+
+        xmom_update = domain.quantities['xmomentum'].explicit_update
+
+        N = domain.number_of_elements
+        t = domain.time
+
+        if callable(self.speed):
+            xc = domain.get_centroid_coordinates()
+            s_vec = self.speed(t, xc)
+        else:
+            #Assume s is a scalar
+
+            try:
+                s_vec = self.speed * ones(N, Float)
+            except:
+                msg = 'Speed must be either callable or a scalar: %s' %self.s
+                raise msg
+
+
+        if callable(self.phi):
+            xc = domain.get_centroid_coordinates()
+            phi_vec = self.phi(t, xc)
+        else:
+            #Assume phi is a scalar
+
+            try:
+                phi_vec = self.phi * ones(N, Float)
+            except:
+                msg = 'Angle must be either callable or a scalar: %s' %self.phi
+                raise msg
+
+        #assign_windfield_values(xmom_update, ymom_update,
+        #                        s_vec, phi_vec, self.const)
+        assign_windfield_values(xmom_update, s_vec, phi_vec, self.const)
+
+
+#def assign_windfield_values(xmom_update, ymom_update,
+#                            s_vec, phi_vec, const):
+def assign_windfield_values(xmom_update, s_vec, phi_vec, const):
+    """Python version of assigning wind field to update vectors.
+    A c version also exists (for speed)
+    """
+    from math import pi, cos, sin, sqrt
+
+    N = len(s_vec)
+    for k in range(N):
+        s = s_vec[k]
+        phi = phi_vec[k]
+
+        #Convert to radians
+        phi = phi*pi/180
+
+        #Compute velocity vector (u, v)
+        u = s*cos(phi)
+        v = s*sin(phi)
+
+        #Compute wind stress
+        S = const * u
+        xmom_update[k] += S*u
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/error.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/error.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/error.py	(revision 7837)
@@ -0,0 +1,9 @@
+## module error
+''' err(string).
+    Prints 'string' and terminates program.
+'''    
+import sys
+def err(string):
+    print string
+    raw_input('Press return to exit')
+    sys.exit()
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/gaussPivot.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/gaussPivot.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/gaussPivot.py	(revision 7837)
@@ -0,0 +1,43 @@
+## module gaussPivot
+''' x = gaussPivot(a,b,tol=1.0e-9).
+    Solves [a]{x} = {b} by Gauss elimination with
+    scaled row pivoting
+'''    
+from Numeric import *
+import swap 
+import error
+
+def gaussPivot(a,b,tol=1.0e-12):
+    n = len(b)
+    
+  # Set up scale factors
+    s = zeros((n),Float)
+    for i in range(n):
+        s[i] = max(abs(a[i,:]))
+            
+    for k in range(0,n-1):
+        
+      # Row interchange, if needed
+        p = int(argmax(abs(a[k:n,k])/s[k:n])) + k
+        if abs(a[p,k]) < tol: error.err('Matrix is singular')
+        if p != k:
+            swap.swapRows(b,k,p)
+            swap.swapRows(s,k,p)
+            swap.swapRows(a,k,p)
+            
+      # Elimination
+        for i in range(k+1,n):
+            if a[i,k] != 0.0:
+                lam = a[i,k]/a[k,k]
+                a[i,k+1:n] = a [i,k+1:n] - lam*a[k,k+1:n]
+                b[i] = b[i] - lam*b[k]
+    if abs(a[n-1,n-1]) < tol: error.err('Matrix is singular')
+                   
+  # Back substitution
+    for k in range(n-1,-1,-1):
+        b[k] = (b[k] - dot(a[k,k+1:n],b[k+1:n]))/a[k,k]
+    return b
+
+
+
+        
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/generic_boundary_conditions.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/generic_boundary_conditions.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/generic_boundary_conditions.py	(revision 7837)
@@ -0,0 +1,548 @@
+"""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 zeros, Float
+        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 array, Float
+        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 array, Float
+        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 Numeric 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 array, zeros, Float
+        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 Numeric 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 zeros, Float, 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: anuga_work/development/sudi/sw_1d/periodic_waves/johns/parameter.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/parameter.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/parameter.py	(revision 7837)
@@ -0,0 +1,82 @@
+from scipy.special import jn
+from scipy import pi, sqrt, linspace, pi, sin, cos
+from config import g
+from Numeric import zeros, Float
+from rootsearch import *
+from bisect import *
+
+def j0(x):
+    return jn(0.0, x)
+
+def j1(x):
+    return jn(1.0, x)
+
+def j2(x):
+    return jn(2.0, x)
+
+def j3(x):
+    return jn(3.0, x)
+
+def jm1(x):
+    return jn(-1.0, x)
+
+def jm2(x):
+    return jn(-2.0, x)
+
+
+"""
+##==========================================================================##
+#DIMENSIONAL PARAMETERS
+L = 5e4                 # Length of channel (m)
+h_0 = 5e2               # Height at origin when the water is still
+N = 550                 # Number of computational cells????????????????
+cell_len = 1.1*L/N      # Origin = 0.0
+Tp = 15.0*60.0                           # Period of oscillation
+a = 1.0                                 # Amplitude at origin
+X = linspace(-0.5*cell_len, 1.1*L+0.5*cell_len, N+2)             # Discretized spatial domain
+##=========================================================================##
+"""
+#DIMENSIONAL PARAMETERS
+L = 5e4                 # Length of channel (m)
+h_0 = 5e2               # Height at origin when the water is still
+numb = 550                 # initial Number of computational cells
+cell_len = 100.0#100.0 is actually 1.1*L/numb
+Tp = 15.0*60.0                           # Period of oscillation
+a = 1.0                                  # Amplitude at origin
+               
+points = zeros(numb+2,Float)
+for i in range(numb+2):
+        points[i] = i*cell_len - 0.5*cell_len
+N = len(points)-1       # Number of computational cells
+
+
+#DIMENSIONLESS PARAMETERS
+eps = a/h_0
+T = Tp*sqrt(g*h_0)/L
+A = eps/j0(4.0*pi/T)
+
+
+def w_at_O_JOHNS(t):
+    return eps*cos(2.0*pi*t/T)
+
+def u_at_O_JOHNS(t):
+    a = -1.01#-1.0
+    b = 1.01#1.0
+    dx = 0.01
+    w = w_at_O_JOHNS(t)
+    def fun(u):
+        return u + A*j1(4.0*pi/T*(1.0+w)**0.5)*sin(2.0*pi/T*(t+u))/(1+w)**0.5
+    while 1:
+        x1,x2 = rootsearch(fun,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(fun,x1,x2,1)
+        else:
+            break
+    return root
+
+
+def prescribe_at_O_JOHNS(t):
+    w = w_at_O_JOHNS(t)
+    u = u_at_O_JOHNS(t)
+    return w, u
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/quantity.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/quantity.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/quantity.py	(revision 7837)
@@ -0,0 +1,1035 @@
+"""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 array, zeros, Float
+
+        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 zeros, Float
+        
+        #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 array, Float
+
+        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 concatenate, zeros, Float, Int, 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 sum, equal, ones, Float
+
+        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 array, zeros, Float
+
+        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 array, zeros, Float,sign
+        
+        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 zeros, Float
+
+        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 zeros, Float
+        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):
+            #Note: neighbours=[-1, {0, 1, 2, ..., N-1}, -2]
+            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):
+            #Note: neighbours=[-1, {0, 1, 2, ..., N-1}, -2]            
+            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])
+            elif n1 < 0:
+                phi = (qc[k] - qc[k-1])/(C[k] - C[k-1])
+            else:
+                if limiter == "minmod":
+                    phi = minmod(beta_p[k],beta_m[k])
+                elif limiter == "minmod_kurganov":
+                    # 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 zeros, Float
+        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"
+
+
+##
+##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 domain_johns import Domain    
+    from Numeric 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: anuga_work/development/sudi/sw_1d/periodic_waves/johns/rootsearch.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/rootsearch.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/rootsearch.py	(revision 7837)
@@ -0,0 +1,15 @@
+## module rootsearch
+''' x1,x2 = rootsearch(f,a,b,dx).
+    Searches the interval (a,b) in increments dx for
+    the bounds (x1,x2) of the smallest root of f(x). 
+    Returns x1 = x2 = None if no roots were detected.
+'''   
+def rootsearch(f,a,b,dx):
+    x1 = a; f1 = f(a)
+    x2 = a + dx; f2 = f(x2)
+    while f1*f2 > 0.0:
+        if x1  >=  b: return None,None
+        x1 = x2; f1 = f2
+        x2 = x1 + dx; f2 = f(x2)
+    else:
+        return x1,x2
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-discrepancy.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-discrepancy.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-discrepancy.py	(revision 7837)
@@ -0,0 +1,211 @@
+import os
+from scipy.special import jn
+from scipy import sin, cos, sqrt, linspace, pi, zeros
+from rootsearch import *
+from bisect import *
+from Numeric import zeros,Float,dot
+from gaussPivot import *
+from config import g
+
+def newtonRaphson2(f,q,tol=1.0e-15): ##1.0e-9 may be too large.
+    for i in range(30):                                                                                                                                    
+        h = 1.0e-15      ##1.0e-4 may be too large.
+        n = len(q)
+        jac = zeros((n,n),Float)
+        if 1.0+q[0]-x<0.0:
+            temp1 = 1.0+q[0]-x
+            q[0] = q[0]-temp1
+            q[1] = v
+            return q
+        f0 = f(q)
+        for i in range(n):
+            temp = q[i]
+            q[i] = temp + h
+            f1 = f(q)
+            q[i] = temp
+            jac[:,i] = (f1 - f0)/h
+        if sqrt(dot(f0,f0)/len(q)) < tol: return q
+        dq = gaussPivot(jac,-f0)
+        q = q + dq
+        if sqrt(dot(dq,dq)) < tol*max(max(abs(q)),1.0): return q
+    print 'Too many iterations'
+
+
+def j0(x):
+    return jn(0.0, x)
+
+def j1(x):
+    return jn(1.0, x)
+
+def j2(x):
+    return jn(2.0, x)
+
+def j3(x):
+    return jn(3.0, x)
+
+def jm1(x):
+    return jn(-1.0, x)
+
+def jm2(x):
+    return jn(-2.0, x)
+
+def bed(x):
+    return x-1.0
+
+def prescribe(x,t):
+    q = zeros(2, Float)
+    def fun(q): #Here q=(z, u)
+        f = zeros(2,Float)
+        f[0] = q[0] + 0.5*q[1]**2.0 - A*j0(4.0*pi/T*(1.0+q[0]-x)**0.5)*cos(2.0*pi/T*(t+q[1]))
+        f[1] = q[1] + A*j1(4.0*pi/T*(1.0+q[0]-x)**0.5)*sin(2.0*pi/T*(t+q[1]))/(1+q[0]-x)**0.5
+        return f
+    def newtonRaphson2(f,q,tol=1.0e-15): ##1.0e-9 may be too large.
+        for i in range(30):                                                                                                                                    
+            h = 1.0e-15      ##1.0e-4 may be too large.
+            n = len(q)
+            jac = zeros((n,n),Float)
+            if 1.0+q[0]-x<0.0:
+                temp1 = 1.0+q[0]-x
+                q[0] = q[0]-temp1
+                q[1] = v
+                return q
+            f0 = f(q)
+            for i in range(n):
+                temp = q[i]
+                q[i] = temp + h
+                f1 = f(q)
+                q[i] = temp
+                jac[:,i] = (f1 - f0)/h
+            if sqrt(dot(f0,f0)/len(q)) < tol: return q
+            dq = gaussPivot(jac,-f0)
+            q = q + dq
+            if sqrt(dot(dq,dq)) < tol*max(max(abs(q)),1.0): return q
+        print 'Too many iterations'
+    q = newtonRaphson2(fun,q)
+    return q[0], q[1]
+
+
+def root_g(a,b,t):
+    dx = 0.01
+    def g(u):
+        #It was u + 8.0*A*pi/T*sin(2.0*pi/T*(t+u)). See equation (10) in Johns. Use L'Hospital rule.
+        #Note that there is misprint in equation (10) in Johns.
+        return u + 2.0*A*pi/T*sin(2.0*pi/T*(t+u))
+    while 1:
+        x1,x2 = rootsearch(g,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(g,x1,x2,1)
+        else:
+            break
+    return root
+
+
+def shore(t):
+    a = -0.2#-1.0
+    b = 0.2#1.0
+    #dx = 0.01
+    u = root_g(a,b,t)
+    xi = -0.5*u*u + A*cos(2.0*pi/T*(t+u))
+    position = 1.0 + xi
+    return position, u
+
+
+def w_at_O(t):
+    return eps*cos(2.0*pi*t/T)
+
+def u_at_O(t):
+    a = -1.01#-1.0
+    b = 1.01#1.0
+    dx = 0.01
+    w = w_at_O(t)
+    def fun(u):
+        return u + A*j1(4.0*pi/T*(1.0+w)**0.5)*sin(2.0*pi/T*(t+u))/(1+w)**0.5
+    while 1:
+        x1,x2 = rootsearch(fun,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(fun,x1,x2,1)
+        else:
+            break
+    return root
+
+
+##==========================================================================##
+#DIMENSIONAL PARAMETERS
+L = 5e4                 # Length of channel (m)
+h_0 = 5e2               # Height at origin when the water is still
+#N = 100#400                 # Number of computational cells
+#cell_len = 1.1*L/N      # Origin = 0.0
+Tp = 15.0*60.0                           # Period of oscillation
+a = 1.0                                 # Amplitude at origin
+#X_dimensionless = linspace(0.0, 1.1*L, N)             # Discretized spatial domain
+##=========================================================================##
+#DIMENSIONLESS PARAMETERS
+eps = a/h_0
+T = Tp*sqrt(g*h_0)/L
+A = eps/j0(4.0*pi/T)
+Time = linspace(0.0,T,1000)
+#X = X_dimensionless/L
+#Z = bed(X)
+#N_X = len(X)
+N_T = len(Time)
+
+
+Stage = zeros(N_T, Float)    
+Veloc = zeros(N_T, Float)
+for i in range(N_T):
+    t=Time[i]
+    zet, vel = prescribe(0.0,t)
+    Stage[i] = zet
+    Veloc[i] = vel
+
+
+Stage_johns = zeros(N_T, Float)    
+Veloc_johns = zeros(N_T, Float)
+for i in range(N_T):
+    t=Time[i]
+    Stage_johns[i] = w_at_O(t)
+    Veloc_johns[i] = u_at_O(t)
+
+
+num=len(Stage)
+error_w=(1.0/num)*sum(abs(Stage-Stage_johns))*h_0
+error_u=(1.0/num)*sum(abs(Veloc-Veloc_johns))*sqrt(g*h_0)
+print "error_w=", error_w
+print "error_u=", error_u
+
+"""
+
+from pylab import clf,plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+hold(False)
+clf()
+plot1 = subplot(111)
+plot(Time/T,Stage*h_0,'b-', Time/T,Stage_johns*h_0,'k--')
+xlabel('t/T')
+ylabel('Stage')
+plot1.set_xlim([0.000,0.030])
+plot1.set_ylim([0.980,1.005]) #([-9.0e-3,9.0e-3])
+legend(('C-G', 'Johns'),
+       'lower left', shadow=False)
+
+plot2 = subplot(212)
+plot(Time/T,Veloc*sqrt(g*h_0),'b-', Time/T,Veloc_johns*sqrt(g*h_0),'k--')
+xlabel('t/T')
+ylabel('Velocity')
+#plot1.set_xlim([0.0,1.1])
+#plot2.set_ylim([-0.05,0.05]) #([-1.0e-12,1.0e-12])
+legend(('C-G', 'Johns'),
+       'upper right', shadow=False)
+
+
+filename = "discrepancy-closer"
+#filename += str(i)
+filename += ".eps"
+savefig(filename)
+#show()
+
+#plot(Time,Vel_at_O)
+#show()
+"""
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-plot.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-plot.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-plot.py	(revision 7837)
@@ -0,0 +1,245 @@
+#################Opening analytical solution################
+infile = open('analytical_1230_12300.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+position = zeros(len(table),Float)
+analitW12300 = zeros(len(table),Float)
+analitP12300 = zeros(len(table),Float)
+analitZ12300 = zeros(len(table),Float)
+analitH12300 = zeros(len(table),Float)
+analitU12300 = zeros(len(table),Float)
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==0:
+            position[r] = table[r][c]
+        elif c==1:
+            analitW12300[r] = table[r][c]
+        elif c==2:
+            analitP12300[r] = table[r][c]
+        elif c==3:
+            analitZ12300[r] = table[r][c]
+        elif c==4:
+            analitH12300[r] = table[r][c]
+        elif c==5:
+            analitU12300[r] = table[r][c]            
+
+#################Opening numerical_cg solution################
+infile = open('numerical_cg_1230_12300.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+numeric_cgW12300 = zeros(len(table),Float)
+numeric_cgP12300 = zeros(len(table),Float)
+numeric_cgZ12300 = zeros(len(table),Float)
+numeric_cgH12300 = zeros(len(table),Float)
+numeric_cgU12300 = zeros(len(table),Float)
+
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==1:
+            numeric_cgW12300[r] = table[r][c]
+        elif c==2:
+            numeric_cgP12300[r] = table[r][c]
+        elif c==3:
+            numeric_cgZ12300[r] = table[r][c]
+        elif c==4:
+            numeric_cgH12300[r] = table[r][c]
+        elif c==5:
+            numeric_cgU12300[r] = table[r][c]
+            
+
+
+#################Opening numerical_johns solution################
+infile = open('numerical_johns_1230_12300.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+numeric_johnsW12300 = zeros(len(table),Float)
+numeric_johnsP12300 = zeros(len(table),Float)
+numeric_johnsZ12300 = zeros(len(table),Float)
+numeric_johnsH12300 = zeros(len(table),Float)
+numeric_johnsU12300 = zeros(len(table),Float)
+
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==1:
+            numeric_johnsW12300[r] = table[r][c]
+        elif c==2:
+            numeric_johnsP12300[r] = table[r][c]
+        elif c==3:
+            numeric_johnsZ12300[r] = table[r][c]
+        elif c==4:
+            numeric_johnsH12300[r] = table[r][c]
+        elif c==5:
+            numeric_johnsU12300[r] = table[r][c]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+#################Opening analytical solution################
+infile = open('analytical_1260_12600.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+position = zeros(len(table),Float)
+analitW12600 = zeros(len(table),Float)
+analitP12600 = zeros(len(table),Float)
+analitZ12600 = zeros(len(table),Float)
+analitH12600 = zeros(len(table),Float)
+analitU12600 = zeros(len(table),Float)
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==0:
+            position[r] = table[r][c]
+        elif c==1:
+            analitW12600[r] = table[r][c]
+        elif c==2:
+            analitP12600[r] = table[r][c]
+        elif c==3:
+            analitZ12600[r] = table[r][c]
+        elif c==4:
+            analitH12600[r] = table[r][c]
+        elif c==5:
+            analitU12600[r] = table[r][c]            
+
+#################Opening numerical_cg solution################
+infile = open('numerical_cg_1260_12600.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+numeric_cgW12600 = zeros(len(table),Float)
+numeric_cgP12600 = zeros(len(table),Float)
+numeric_cgZ12600 = zeros(len(table),Float)
+numeric_cgH12600 = zeros(len(table),Float)
+numeric_cgU12600 = zeros(len(table),Float)
+
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==1:
+            numeric_cgW12600[r] = table[r][c]
+        elif c==2:
+            numeric_cgP12600[r] = table[r][c]
+        elif c==3:
+            numeric_cgZ12600[r] = table[r][c]
+        elif c==4:
+            numeric_cgH12600[r] = table[r][c]
+        elif c==5:
+            numeric_cgU12600[r] = table[r][c]
+            
+
+
+#################Opening numerical_johns solution################
+infile = open('numerical_johns_1260_12600.000000.csv', 'r')
+table = []
+for row in csv.reader(infile):
+    table.append(row)
+infile.close()
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        table[r][c] = float(table[r][c])
+
+numeric_johnsW12600 = zeros(len(table),Float)
+numeric_johnsP12600 = zeros(len(table),Float)
+numeric_johnsZ12600 = zeros(len(table),Float)
+numeric_johnsH12600 = zeros(len(table),Float)
+numeric_johnsU12600 = zeros(len(table),Float)
+
+for r in range(len(table)):
+    for c in range(len(table[0])):
+        if c==1:
+            numeric_johnsW12600[r] = table[r][c]
+        elif c==2:
+            numeric_johnsP12600[r] = table[r][c]
+        elif c==3:
+            numeric_johnsZ12600[r] = table[r][c]
+        elif c==4:
+            numeric_johnsH12600[r] = table[r][c]
+        elif c==5:
+            numeric_johnsU12600[r] = table[r][c]
+
+
+
+#################PLOTTING THE RESULTS##############################################
+from pylab import clf,plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot,ion
+hold(False)
+clf()
+
+plot1 = subplot(311)
+plot(#position*1e-4,analitW12300, position*1e-4,numeric_cgW12300, position*1e-4,numeric_johnsW12300,
+     position*1e-4,analitW12600, position*1e-4,numeric_cgW12600, position*1e-4,numeric_johnsW12600,
+     position*1e-4,analitZ12300,'k-')
+#xlabel('Position')
+ylabel('Stage')
+#plot1.set_xlim([0.0,1.2])
+#plot1.set_ylim([-5.0,3.0])#([-9.0e-3,9.0e-3])
+#legend(('Analytical Solution', 'C-G Solution', 'Johns Solution'),
+#       'lower left', shadow=False)
+
+plot2 = subplot(312)
+plot(#position*1e-4,analitP12300, position*1e-4,numeric_cgP12300, position*1e-4,numeric_johnsP12300)
+     position*1e-4,analitP12600, position*1e-4,numeric_cgP12600, position*1e-4,numeric_johnsP12600)
+#xlabel('Position')
+ylabel('Momentum')
+#plot1.set_xlim([0.0,1.2])
+#plot1.set_ylim([-4.0,3.0])#([-9.0e-3,9.0e-3])
+#legend(('Analytical Solution', 'C-G Solution', 'Johns Solution'),
+#       'lower left', shadow=False)
+
+
+plot3 = subplot(313)
+plot(#position*1e-4,analitU12300, position*1e-4,numeric_cgU12300, position*1e-4,numeric_johnsU12300)
+     position*1e-4,analitU12600, position*1e-4,numeric_cgU12600, position*1e-4,numeric_johnsU12600)
+xlabel('Position/10,000')
+ylabel('Velocity')
+#plot1.set_xlim([0.0,1.2])
+#plot3.set_ylim([-4.0,2.0])#([-9.0e-3,9.0e-3])
+legend(('Exact Solution', 'C-G Solution', 'Johns Solution'),
+       'lower left', shadow=False)
+
+filename = "%s" %("12600.eps")
+#savefig(filename)
+show()
+
+
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-program.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-program.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/run-program.py	(revision 7837)
@@ -0,0 +1,373 @@
+from scipy import sin, cos, sqrt, linspace, pi, dot
+from Numeric import zeros, Float, array
+from gaussPivot import *
+from analytical_prescription import *
+from parameter import *
+import os, time, csv, pprint
+from domain_johns import *
+from config import g, epsilon
+from rootsearch import *
+from bisect import *
+
+#Analytical computations#################################################################
+def root_g(a,b,t):
+    dx = 0.01
+    def g(u):
+        return u + 2.0*A*pi/T*sin(2.0*pi/T*(t+u))
+    while 1:
+        x1,x2 = rootsearch(g,a,b,dx)
+        if x1 != None:
+            a = x2
+            root = bisect(g,x1,x2,1)
+        else:
+            break
+    return root
+def shore(t):
+    a = -1.0#-0.2#-1.0
+    b = 1.0#0.2#1.0
+    #dx = 0.01
+    u = root_g(a,b,t)
+    xi = -0.5*u*u + A*cos(2.0*pi/T*(t+u))
+    position = 1.0 + xi
+    return position, u
+
+
+
+
+#Numerical computations###################################################################
+def newtonRaphson2(f,q,tol=1.0e-15): ##1.0e-9 may be too large
+    for i in range(30):                                                                                                                                    
+        h = 1.0e-4      ##1.0e-4 may be too large.
+        n = len(q)
+        jac = zeros((n,n),Float)
+        if 1.0+q[0]-x<0.0:
+            temp1 = 1.0+q[0]-x
+            q[0] = q[0]-temp1
+            q[1] = v
+            return q
+        f0 = f(q)
+        for i in range(n):
+            temp = q[i]
+            q[i] = temp + h
+            f1 = f(q)
+            q[i] = temp
+            jac[:,i] = (f1 - f0)/h
+        if sqrt(dot(f0,f0)/len(q)) < tol: return q
+        dq = gaussPivot(jac,-f0)
+        q = q + dq
+        if sqrt(dot(dq,dq)) < tol*max(max(abs(q)),1.0): return q
+    print 'Too many iterations'
+
+def elevation(X):
+    N = len(X)
+    z = zeros(N,Float)
+    for i in range(N):
+        z[i] = (h_0/L)*X[i] - h_0
+    return z
+
+def height(X):
+    N = len(X)
+    z = zeros(N,Float)
+    for i in range(N):
+        z[i] = h_0 - (h_0/L)*X[i]
+    return z
+
+def velocity(X):
+    N = len(X)
+    return zeros(N,Float)
+    
+boundary = { (0,0): 'left',(N-1,1): 'right'}
+
+domain = Domain(points,boundary)
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.beta = 1.0
+domain.set_limiter("minmod")
+
+
+def f_CG(t):
+    timing = t*sqrt(g*h_0)/L
+    w, u = prescribe(0.0,timing)
+    wO = w*h_0
+    uO = u*sqrt(g*h_0)
+    zO = -h_0
+    hO = wO - zO
+    pO = uO * hO
+    #[    'stage', 'xmomentum', 'elevation', 'height', 'velocity']
+    return [wO,  pO,   zO,      hO,      uO]
+def f_JOHNS(t):
+    timing = t*sqrt(g*h_0)/L
+    w, u = prescribe_at_O_JOHNS(timing)
+    wO = w*h_0
+    uO = u*sqrt(g*h_0)
+    zO = -h_0
+    hO = wO - zO
+    pO = uO * hO
+    #[    'stage', 'xmomentum', 'elevation', 'height', 'velocity']
+    return [wO,  pO,   zO,      hO,      uO]
+
+T1 = Time_boundary(domain,f_JOHNS)
+D2 = Dirichlet_boundary([50.5,  0.0,  50.5,  0.0,  0.0])
+domain.set_boundary({'left':T1,'right':D2})
+
+domain.set_quantity('height',height)
+domain.set_quantity('elevation',elevation)
+domain.set_quantity('velocity',velocity)
+
+
+Ver = domain.vertices
+n_V = len(Ver)
+AnalitW_V = zeros((n_V,2), Float)
+AnalitP_V = zeros((n_V,2), Float)
+AnalitZ_V = zeros((n_V,2), Float)
+AnalitH_V = zeros((n_V,2), Float)
+AnalitU_V = zeros((n_V,2), Float)
+
+Cen = domain.centroids
+n_C = len(Cen)
+AnalitW_C = zeros(n_C, Float)
+AnalitP_C = zeros(n_C, Float)
+AnalitZ_C = zeros(n_C, Float)
+AnalitH_C = zeros(n_C, Float)
+AnalitU_C = zeros(n_C, Float)
+
+waktu = 10.0     #3.0*60.0
+WAKTU = 12690.0  #Note: Tp=15.0*60.0
+yieldstep = finaltime = waktu
+t0 = time.time()
+counter=1
+
+shorelines_numerical_johns = zeros(int(WAKTU/waktu), Float)
+shorelines_analytical = zeros(int(WAKTU/waktu), Float)
+time_instants = zeros(int(WAKTU/waktu), Float)
+print "the initial time_instants=", time_instants
+
+
+while finaltime < WAKTU+0.1:
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        domain.write_time()
+    time_instants[counter-1] = domain.time
+    
+    Stage = domain.quantities['stage']
+    Momentum = domain.quantities['xmomentum']
+    Elevation = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+    StageV = Stage.vertex_values
+    MomV = Momentum.vertex_values
+    ElevationV = Elevation.vertex_values
+    HeightV = Height.vertex_values
+    VelV = Velocity.vertex_values
+
+    StageC = Stage.centroid_values
+    MomC = Momentum.centroid_values
+    ElevationC = Elevation.centroid_values
+    HeightC = Height.centroid_values
+    VelC = Velocity.centroid_values
+
+    table = zeros((len(Ver.flat),6),Float)
+    for r in range(len(Ver.flat)):
+        for c in range(6):
+            if c==0:
+                table[r][c] = Ver.flat[r]
+            elif c==1:
+                table[r][c] = StageV.flat[r]
+            elif c==2:
+                table[r][c] = MomV.flat[r]
+            elif c==3:
+                table[r][c] = ElevationV.flat[r]
+            elif c==4:
+                table[r][c] = HeightV.flat[r]                
+            else:
+                table[r][c] = VelV.flat[r]
+
+    outname = "%s%04i%s%f%s" %("numerical_johns_", counter, "_", domain.time, ".csv")                
+    outfile = open(outname, 'w')
+    writer = csv.writer(outfile)
+    for row in table:
+        writer.writerow(row)        
+    outfile.close()    
+
+
+    for s in range(2*n_V):
+        heiL = HeightV.flat[s]
+        momR = MomV.flat[s+1]
+        if heiL >= 1e-6:
+            if abs(momR)==0.0: #<1e-15:
+                break
+    #print "s+1=",s+1
+    shorelines_numerical_johns[counter-1] = Ver.flat[s+1]
+    #print "shorelines_numerical_johns=",shorelines_numerical_johns[counter-1]
+
+
+    
+    #print "Now the ANALYTIC"
+    pos_shore, vel_shore = shore(domain.time*sqrt(g*h_0)/L) #dimensionless
+    pos_shore = pos_shore*L
+    vel_shore = vel_shore*sqrt(g*h_0)
+
+    shorelines_analytical[counter-1] = pos_shore
+
+    #The following is for calculating the error at centroids
+    for i in range(n_C):
+        x = Cen[i]
+        if x < pos_shore:
+            sta, vel = prescribe(x/L,domain.time*sqrt(g*h_0)/L) #dimensionless
+            AnalitW_C[i] = sta*h_0
+            AnalitU_C[i] = vel                            #It needs dimensionalisation
+            AnalitZ_C[i] = (h_0/L)*x - h_0
+            AnalitH_C[i] = AnalitW_C[i] - AnalitZ_C[i]
+            AnalitP_C[i] = AnalitH_C[i]*AnalitU_C[i]  #It needs dimensionalisation
+        else:
+            AnalitW_C[i] = (h_0/L)*x - h_0                 
+            AnalitU_C[i] = 0.0
+            AnalitZ_C[i] = (h_0/L)*x - h_0
+            AnalitH_C[i] = 0.0
+            AnalitP_C[i] = 0.0
+    AnalitU_C = AnalitU_C*sqrt(g*h_0) #This is the dimensionalisation
+    AnalitP_C = AnalitP_C*sqrt(g*h_0) #This is the dimensionalisation
+
+    error_W = (1.0/n_C)*sum(abs(StageC-AnalitW_C))
+    error_P = (1.0/n_C)*sum(abs(MomC-AnalitP_C))
+    error_U = (1.0/n_C)*sum(abs(VelC-AnalitU_C))
+    table = zeros((1,4),Float)
+    for r in range(1):
+        for c in range(4):
+            if c==0:
+                table[r][c] = domain.time
+            elif c==1:
+                table[r][c] = error_W
+            elif c==2:
+                table[r][c] = error_P
+            else:
+                table[r][c] = error_U
+    outname = "%s%04i%s%f%s" %("error_johns_", counter, "_", domain.time, ".csv")                
+    outfile = open(outname, 'w')
+    writer = csv.writer(outfile)
+    for row in table:
+        writer.writerow(row)        
+    outfile.close()
+
+
+    #The following is for ploting the quantities at vertex values
+    for i in range(n_V):
+        vector_x = Ver[i]
+        for k in range(2):
+            x = vector_x[k]
+            if x < pos_shore:
+                sta, vel = prescribe(x/L,domain.time*sqrt(g*h_0)/L) #dimensionless
+                AnalitW_V[i,k] = sta*h_0
+                AnalitU_V[i,k] = vel                            #It needs dimensionalisation
+                AnalitZ_V[i,k] = (h_0/L)*x - h_0
+                AnalitH_V[i,k] = AnalitW_V[i,k] - AnalitZ_V[i,k]
+                AnalitP_V[i,k] = AnalitH_V[i,k]*AnalitU_V[i,k]  #It needs dimensionalisation
+            else:
+                AnalitW_V[i,k] = (h_0/L)*x - h_0                 
+                AnalitU_V[i,k] = 0.0
+                AnalitZ_V[i,k] = (h_0/L)*x - h_0
+                AnalitH_V[i,k] = 0.0
+                AnalitP_V[i,k] = 0.0
+    AnalitU_V = AnalitU_V*sqrt(g*h_0) #This is the dimensionalisation
+    AnalitP_V = AnalitP_V*sqrt(g*h_0) #This is the dimensionalisation
+
+
+    table = zeros((len(Ver.flat),6),Float)
+    for r in range(len(Ver.flat)):
+        for c in range(6):
+            if c==0:
+                table[r][c] = Ver.flat[r]
+            elif c==1:
+                table[r][c] = AnalitW_V.flat[r]
+            elif c==2:
+                table[r][c] = AnalitP_V.flat[r]
+            elif c==3:
+                table[r][c] = AnalitZ_V.flat[r]
+            elif c==4:
+                table[r][c] = AnalitH_V.flat[r]                
+            else:
+                table[r][c] = AnalitU_V.flat[r]
+
+    outname = "%s%04i%s%f%s" %("analytical_", counter, "_", domain.time, ".csv")                
+    outfile = open(outname, 'w')
+    writer = csv.writer(outfile)
+    for row in table:
+        writer.writerow(row)        
+    outfile.close()
+
+    #put this
+    from pylab import clf,plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot,ion
+    hold(False)
+    clf()
+
+    plot1 = subplot(311)
+    plot(Ver/1e+4,AnalitW_V,'b-',  Ver/1e+4,StageV,'g-',  Ver/1e+4,ElevationV,'k-')
+    #plot(Ver,StageV, Ver,ElevationV)
+    #plot(Ver/L,StageV/h_0,  Ver/L,ElevationV/h_0)
+    #xlabel('Position')
+    ylabel('Stage')
+    #plot1.set_xlim([0.0,1.2])
+    plot1.set_ylim([-6.0,6.0])#([-9.0e-3,9.0e-3])
+    #legend(('Analytical Solution', 'Numerical Solution', 'Discretized Bed'),
+    #       'upper right', shadow=False)
+    
+    plot2 = subplot(312)
+    plot(Ver/1e+4,AnalitP_V,'b-',  Ver/1e+4,MomV,'g-')
+    #plot(Ver/L, VelV/sqrt(g*h_0))
+    #xlabel('Position')
+    ylabel('Momentum')
+    #plot2.set_xlim([0.0,1.2])
+    #legend(('Analytical Solution','Numerical Solution'),
+    #       'upper right', shadow=False)        
+
+    plot3 = subplot(313)
+    plot(Ver/1e+4,AnalitU_V,'b-',  Ver/1e+4,VelV,'g-')
+    #plot(Ver/L, VelV/sqrt(g*h_0))
+    xlabel('Position / 10,000')
+    ylabel('Velocity')
+    #plot2.set_xlim([0.0,1.2])
+    legend(('Analytical Solution','Numerical Solution'),
+           'upper center', shadow=False)
+    
+    filename = "%s%04i%s%f%s" %("numerical_johns_", counter,"_", domain.time, ".png")
+    savefig(filename)
+    #show()
+    #raw_input("Press ENTER to continue")
+    #put this
+    counter = counter+1
+    finaltime = finaltime + waktu
+
+
+
+table = zeros((int(WAKTU/waktu), 2),Float)
+for r in range(int(WAKTU/waktu)):
+    for c in range(2):
+        if c==0:
+            table[r][c] = time_instants[r]               
+        else:
+            table[r][c] = shorelines_numerical_johns[r]
+
+outname = "%s" %("shore_numerical_johns.csv")                
+outfile = open(outname, 'w')
+writer = csv.writer(outfile)
+for row in table:
+    writer.writerow(row)        
+outfile.close()
+
+
+table = zeros((int(WAKTU/waktu), 2),Float)
+for r in range(int(WAKTU/waktu)):
+    for c in range(2):
+        if c==0:
+            table[r][c] = time_instants[r]               
+        else:
+            table[r][c] = shorelines_analytical[r]
+
+outname = "%s" %("shore_analytical.csv")                
+outfile = open(outname, 'w')
+writer = csv.writer(outfile)
+for row in table:
+    writer.writerow(row)        
+outfile.close()
+
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/swap.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/swap.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/swap.py	(revision 7837)
@@ -0,0 +1,27 @@
+## module swap
+''' swapRows(v,i,j).
+    Swaps rows i and j of vector or matrix [v].
+
+    swapCols(v,i,j).
+    Swaps columns i and j of matrix [v].
+
+def swapRows(v,i,j):
+    if len(v.getshape()) == 1: v[i],v[j] = v[j],v[i]
+    else:
+        temp = v[i].copy()
+        v[i] = v[j]
+        v[j] = temp
+'''
+
+def swapRows(v,i,j):
+    if len(v.flat) == 2:
+        v[i],v[j] = v[j],v[i]
+    else:
+        temp = v[i].copy()
+        v[i] = v[j]
+        v[j] = temp      
+
+def swapCols(v,i,j):
+    temp = v[:,j].copy()
+    v[:,j] = v[:,i]
+    v[:,i] = temp
Index: anuga_work/development/sudi/sw_1d/periodic_waves/johns/util.py
===================================================================
--- anuga_work/development/sudi/sw_1d/periodic_waves/johns/util.py	(revision 7837)
+++ anuga_work/development/sudi/sw_1d/periodic_waves/johns/util.py	(revision 7837)
@@ -0,0 +1,174 @@
+"""
+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 zeros, Float,sqrt,sin,cos
+
+    
+    #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: anuga_work/development/sudi/sw_2d/yoon_parabolic_basin_cross_mesh.py
===================================================================
--- anuga_work/development/sudi/sw_2d/yoon_parabolic_basin_cross_mesh.py	(revision 7837)
+++ anuga_work/development/sudi/sw_2d/yoon_parabolic_basin_cross_mesh.py	(revision 7837)
@@ -0,0 +1,177 @@
+"""Example of shallow water wave equation analytical solution
+consists of a parabolic profile in a parabolic basin. Analytical
+solutiuon to this problem was derived by Thacker
+and used by Yoon and Chou.
+
+   Copyright 2005
+   Christopher Zoppou, Stephen Roberts, ANU, Geoscience Australia
+
+"""
+
+#---------------
+# Module imports
+#from anuga.shallow_water_balanced.swb_domain import Domain, Transmissive_boundary, Reflective_boundary,\
+#     Dirichlet_boundary
+
+from anuga.interface import Domain, Transmissive_boundary, Reflective_boundary,\
+     Dirichlet_boundary
+from math import sqrt, cos, sin, pi
+from anuga.interface import rectangular_cross
+from anuga.utilities.polygon import inside_polygon, is_inside_triangle
+from numpy import asarray
+
+
+#-------------------------------
+# Domain
+n = 20#200
+m = 20#200
+lenx = 8000.0
+leny = 8000.0
+origin = (-4000.0, -4000.0)
+
+points, elements, boundary = rectangular_cross(m, n, lenx, leny, origin)
+domain = Domain(points, elements, boundary)
+
+#----------------
+# Order of scheme
+# Good compromise between
+# limiting and CFL
+#---------------
+domain.set_default_order(2)
+domain.set_timestepping_method(2)
+domain.set_beta(0.7)
+domain.set_CFL(0.6)
+
+domain.smooth = True
+
+#-------------------------------------
+# Provide file name for storing output
+domain.store = False
+domain.format = 'sww'
+domain.set_name('yoon_mesh_second_order_cross')
+print 'Number of triangles = ', len(domain)
+
+#----------------------------------------------------------
+# Decide which quantities are to be stored at each timestep
+domain.quantities_to_be_stored = ['stage', 'xmomentum', 'ymomentum']
+
+#------------------------------------------
+# Reduction operation for get_vertex_values
+from anuga.utilities.numerical_tools import mean
+domain.reduction = mean #domain.reduction = min  #Looks better near steep slopes
+
+#------------------
+# Initial condition
+print 'Initial condition'
+t = 0.0
+D0 = 1.
+L = 2500.
+R0 = 2000.
+g = 9.81
+
+A = (L**4 - R0**4)/(L**4 + R0**4)
+omega = 2./L*sqrt(2.*g*D0)
+T = pi/omega
+
+#------------------
+# Set bed elevation
+def x_slope(x,y):
+    n = x.shape[0]
+    z = 0*x
+    for i in range(n):
+        r = sqrt(x[i]*x[i] + y[i]*y[i])
+        z[i] = -D0*(1.-r*r/L/L)
+    return z
+domain.set_quantity('elevation', x_slope)
+
+#----------------------------
+# Set the initial water level
+def level(x,y):
+    z = x_slope(x,y)
+    n = x.shape[0]
+    h = 0*x
+    for i in range(n):
+        r = sqrt(x[i]*x[i] + y[i]*y[i])
+        h[i] = D0*((sqrt(1-A*A))/(1.-A*cos(omega*t))
+                -1.-r*r/L/L*((1.-A*A)/((1.-A*cos(omega*t))**2)-1.))
+    if h[i] < z[i]:
+        h[i] = z[i]
+    return h
+domain.set_quantity('stage', level)
+
+#---------
+# Boundary
+print 'Boundary conditions'
+R = Reflective_boundary(domain)
+T = Transmissive_boundary(domain)
+D = Dirichlet_boundary([0.0, 0.0, 0.0])
+domain.set_boundary({'left': D, 'right': D, 'top': D, 'bottom': D})
+
+#---------------------------------------------
+# Find triangle that contains the point points
+# and print to file
+
+
+
+points = (0.0, 0.0)
+for n in range(len(domain.triangles)):
+    tri = domain.get_vertex_coordinates(n)
+
+    if is_inside_triangle(points,tri):
+        #print 'Point is within triangle with vertices '+'%s'%tri
+        n_point = n
+
+print 'n_point = ',n_point
+t = domain.triangles[n_point]
+print 't = ', t
+tri = domain.get_vertex_coordinates(n)
+
+filename=domain.get_name()
+file = open(filename,'w')
+
+#----------
+# Evolution
+import time
+t0 = time.time()
+
+time_array = []
+stage_array = []
+Stage     = domain.quantities['stage']
+Xmomentum = domain.quantities['xmomentum']
+Ymomentum = domain.quantities['ymomentum']
+
+for t in domain.evolve(yieldstep = 20.0, finaltime = 17700.0 ):
+    domain.write_time()
+
+    #tri_array = asarray(tri)
+    #t_array = asarray([[0,1,2]])
+    #interp = Interpolation(tri_array,t_array,[points])
+
+
+    stage     = Stage.get_values(location='centroids',indices=[n_point])
+    xmomentum = Xmomentum.get_values(location='centroids',indices=[n_point])
+    ymomentum = Ymomentum.get_values(location='centroids',indices=[n_point])
+    #print '%10.6f   %10.6f  %10.6f   %10.6f\n'%(t,stage,xmomentum,ymomentum)
+    file.write( '%10.6f   %10.6f  %10.6f   %10.6f\n'%(t,stage,xmomentum,ymomentum) )
+
+    time_array.append(t)
+    stage_array.append(stage)
+
+file.close()
+print 'That took %.2f seconds' %(time.time()-t0)
+
+
+from pylab import *
+ion()
+hold(False)
+plot(time_array, stage_array, 'r.-')
+#title('Gauge %s' %name)
+xlabel('time(s)')
+ylabel('stage (m)')
+#legend(('Observed', 'Modelled'), shadow=True, loc='upper left')
+#savefig(name, dpi = 300)
+
+raw_input('Next')
+show()
+
+
