Index: /anuga_work/development/shallow_water_1d/analytic_dam_sudi.py
===================================================================
--- /anuga_work/development/shallow_water_1d/analytic_dam_sudi.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/analytic_dam_sudi.py	(revision 4959)
@@ -0,0 +1,142 @@
+
+
+class AnalyticDam:
+
+    def __init__(self, h0 = 5.0, h1 = 10.0, L = 2000.0):
+        from math import sqrt
+        
+        self.h0 = h0 # depth upstream (m)
+        self.h1 = h1 # depth downstream (m)
+        self.L  = L  # length of domain
+
+        g  = 9.81    # gravity (m/s^2)
+        
+        c0 = sqrt(g*h0) #left celerity
+        c1 = sqrt(g*h1) #right celerity
+        
+        zmin=-100.0
+        zmax=101.0
+        for i in range(100):
+            z=(zmin+zmax)/2.0
+            u2=z-c0*c0/4.0/z*(1.0+sqrt(1.0+8.0*z*z/c0/c0))
+            c2=c0*sqrt(0.5*(sqrt(1.0+8.0*z*z/c0/c0)-1.0))
+            func=2.0*c1/c0-u2/c0-2.0*c2/c0
+            if (func > 0.0):
+                zmin=z
+            else:
+                zmax=z
+
+        if( abs(z) > 99.0):
+            print 'no convergence'
+
+        self.u2 = u2
+        self.c0 = c0
+        self.c1 = c1
+        self.c2 = c2
+        self.g = g
+        self.z = z
+
+
+
+    def __call__(self, C,t):
+        
+        from Numeric import zeros,Float
+        from math import sqrt
+    
+        #t  = 0.0     # time (s)
+        h0 = self.h0    
+        h1 = self.h1    
+        L = self.L 
+        n = len(C)    # number of cells
+
+        u2 = self.u2
+        c0 = self.c0
+        c1 = self.c1
+        c2 = self.c2
+        
+        g = self.g
+        z = self.z
+
+        u = zeros(n,Float)
+        h = zeros(n,Float)
+        uh = zeros(n,Float)
+        x = C-3*L/4.0
+        #x = zeros(n,Float)
+        #for i in range(n):
+        #    x[i] = C[i]-1000.0
+
+        # Upstream and downstream boundary conditions are set to the intial water
+        # depth for all time.
+
+        # Calculate Shock Speed
+        #h2 = 7.2692044
+        
+        #S2 = 2*h2/(h2-h0)*(sqrt(g*h1)-sqrt(g*h2))
+        #u2 = S2 - g*h0/(4*S2)*(1+sqrt(1+8*S2*S2/(g*h0)))
+
+        h2=h0/(1.0-u2/z)
+        x3=(u2-c2)*t
+        x2=z*t
+        x1=-c1*t
+        x1_ = -1*L/2.0-x1
+        x2_ = -1*L/2.0+2*x1
+        #x3_ = -1*L/2.0-x3
+        #t=50 
+        #x = (-L/2:L/2) 
+        for i in range(n):
+            # Calculate Analytical Solution at time t > 0
+            u3 = 2.0/3.0*(sqrt(g*h1)+x[i]/t) 
+            h3 = 4.0/(9.0*g)*(sqrt(g*h1)-x[i]/(2.0*t))*(sqrt(g*h1)-x[i]/(2.0*t))
+            u3_ = 2.0/3.0*((x[i]+L/2.0)/t-sqrt(g*h1))
+            h3_ = 1.0/(9.0*g)*((x[i]+L/2.0)/t+2*sqrt(g*h1))*((x[i]+L/2.0)/t+2*sqrt(g*h1))
+            #if t == 30:
+            #    x[i] = 500
+            #    print 'x2',x2
+            #    print 'x3',x3
+            #    print 'x1',x1
+            if ( x[i] <= x2_ ):
+                #print 'here x2_=', x2_
+                u[i] = 0.0
+                h[i] = 0.0
+                uh [i] = u[i]*h[i]
+            #elif ( x[i] <= x3_ ):
+            #    print 'here x3_=', x3_
+            #    u[i] = -1*u2 
+            #    h[i] = h2
+            #    uh[i] = u[i]*h[i]
+            elif ( x[i] <= x1_ ):
+                #print 'here x1_=', x1_
+                u[i] = u3_ 
+                h[i] = h3_
+                uh[i] = u[i]*h[i]
+            #else:
+            #    u[i] = 0.0 
+            #    h[i] = h0
+            #    uh[i] = u[i]*h[i]
+
+            #elif ( x[i] <= x1/2.0 ):
+            #    u[i] = 0.0 
+            #    h[i] = h1
+            #    uh[i] = u[i]*h[i]
+            elif ( x[i] <= x1 ):
+                #print 'here x1=', x1
+                u[i] = 0.0 
+                h[i] = h1
+                uh[i] = u[i]*h[i]
+            elif ( x[i] <= x3 ):
+                #print 'here x3=', x3
+                u[i] = u3 
+                h[i] = h3
+                uh[i] = u[i]*h[i]
+            elif ( x[i] < x2 ):
+                #print 'here x2=', x2
+                u[i] = u2 
+                h[i] = h2
+                uh[i] = u[i]*h[i]
+            else:
+                #print 'here the last section'
+                u[i] = 0.0 
+                h[i] = h0
+                uh[i] = u[i]*h[i]
+
+        return h , uh
Index: /anuga_work/development/shallow_water_1d/dam_h.py
===================================================================
--- /anuga_work/development/shallow_water_1d/dam_h.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/dam_h.py	(revision 4959)
@@ -0,0 +1,92 @@
+import os
+#from math import sqrt, pi
+from shallow_water_h import Domain, Reflective_boundary
+from Numeric import zeros, Float
+#from config import g, epsilon
+from analytic_dam import AnalyticDam
+
+
+h0 = 5.0
+h1 = 10.0
+
+analytical_sol = AnalyticDam(h0, h1)
+
+def newLinePlot(title='Simple Plot'):
+    import Gnuplot
+    g = Gnuplot.Gnuplot(persist=0)
+    g.title(title)
+    g('set data style linespoints') 
+    g.xlabel('x')
+    g.ylabel('y')
+    return g
+
+def linePlot(g,x1,y1,x2,y2):
+    import Gnuplot
+    plot1 = Gnuplot.PlotItems.Data(x1.flat,y1.flat,with="linespoints")
+    plot2 = Gnuplot.PlotItems.Data(x2.flat,y2.flat,with="lines 3")
+    g.plot(plot1,plot2)
+    
+
+print "TEST 1D-SOLUTION I"
+
+L = 2000.0     # Length of channel (m)
+N = 100        # Number of computational cells
+cell_len = L/N # Origin = 0.0
+
+points = zeros(N+1,Float)
+for i in range(N+1):
+    points[i] = i*cell_len
+
+domain = Domain(points)
+
+def height(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        if x[i]<=1000.0:
+            y[i] = h1
+        else:
+            y[i] = h0
+    return y
+
+
+domain.set_quantity('height', height)
+
+domain.default_order = 2
+domain.order = 2
+domain.default_time_order = 1
+domain.cfl = 0.8
+#domain.beta = 1.0
+domain.split = False
+print "domain.order", domain.order
+domain.limiter = "minmod"
+
+
+domain.set_boundary({'exterior': Reflective_boundary(domain)})
+
+X = domain.vertices
+C = domain.centroids
+plot1 = newLinePlot("Height")
+plot2 = newLinePlot("Momentum")
+
+import time
+t0 = time.time()
+yieldstep = 1.0
+finaltime = 20.0
+print "integral", domain.quantities['height'].get_integral()
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+    print "integral", domain.quantities['height'].get_integral()
+    if t > 0.0:
+        HeightQ = domain.quantities['height'].vertex_values
+        y , my = analytical_sol(X.flat,domain.time)
+        linePlot(plot1,X,HeightQ,X,y)
+        MomentumQ = domain.quantities['xmomentum'].vertex_values
+        linePlot(plot2,X,MomentumQ,X,my)
+    #raw_input('press_return')
+
+    #pass
+
+print 'That took %.2f seconds' %(time.time()-t0)
+
+#C = domain.quantities['height'].centroid_values
+
Index: /anuga_work/development/shallow_water_1d/dam_h_sudi.py
===================================================================
--- /anuga_work/development/shallow_water_1d/dam_h_sudi.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/dam_h_sudi.py	(revision 4959)
@@ -0,0 +1,123 @@
+import os
+from math import sqrt
+from shallow_water_h import *
+from Numeric import zeros, Float
+from analytic_dam_sudi import AnalyticDam
+
+h0=5.0
+h1=10.0
+
+analytical_sol=AnalyticDam(h0,h1)
+
+"""
+def newLinePlot(title='Simple Plot'):
+    import Gnuplot
+    gg=Gnuplot.Gnuplot(persist=0)
+    gg.title(title)
+    gg('set data style linespoints')
+    gg.xlabel('x')
+    gg.ylabel('y')
+    return gg
+
+def linePlot(gg, x1, y1, x2, y2):
+    import Gnuplot
+    plot1=Gnuplot.PlotItems.Data(x1.flat, y1.flat, with="linespoints")
+    plot2=Gnuplot.PlotItems.Data(x2.flat, y2.flat, with="lines 3")
+    gg.plot(plot1, plot2)
+"""
+
+
+print "TEST 1D-SOLUTION I"
+
+L=2000.0
+N=100
+
+cell_len=L/N
+
+points=zeros(N+1, Float)
+for i in range(N+1):
+    points[i]=i*cell_len
+
+domain=Domain(points)
+
+domain.default_order = 1
+domain.default_time_order = 1
+#domain.cfl = 1.0
+#domain.limiter = "minmod"
+
+
+
+
+
+    
+    
+def height(x):
+    y=zeros(len(x), Float)
+    for i in range (len(x)):
+        if x[i]<=L/4.0:
+            y[i]=0.0 #h0
+        elif x[i]<=3*L/4.0:
+            y[i]=h1
+        else:
+            y[i]=h0
+    return y
+
+domain.set_quantity('height', height)
+domain.order=domain.default_order
+print "domain order", domain.order
+
+domain.set_boundary({'exterior':Reflective_boundary(domain)})
+
+X=domain.vertices
+C=domain.centroids
+#plot1x=newLinePlot("Height")
+#plot2x=newLinePlot("Momentum")
+
+
+import time
+t0=time.time()
+yieldstep=30.0
+finaltime=30.0
+print "integral", domain.quantities['height'].get_integral()
+for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+    domain.write_time()
+    print "integral", domain.quantities['height'].get_integral()
+    if t>0.0:
+        HeightQ=domain.quantities['height'].vertex_values
+        MomentumQ=domain.quantities['xmomentum'].vertex_values
+        h, uh=analytical_sol(X.flat, domain.time)
+        #linePlot(plot1x, X, HeightQ, X, h)
+        #linePlot(plot2x, X, MomentumQ, X, uh)
+        #print "press return"
+        #pass
+    
+        from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+        #print 'Test1'
+        hold(False)
+        #print 'test 2'
+        plot1 = subplot(211)
+        #print 'test 3'
+    
+        plot(X,h,X,HeightQ)
+        #print 'Test4'
+        plot1.set_ylim([0,11])
+        xlabel('Position')
+        ylabel('Stage')
+        #legend(('Analytical Solution', 'Numerical Solution'),
+        #   'lower right', shadow=False)
+        plot2 = subplot(212)
+        plot(X,uh,X,MomentumQ)
+        #plot2.set_ylim([-5,35])
+        legend(('Analytical Solution', 'Numerical Solution'),
+           'lower right', shadow=False)
+    
+        xlabel('Position')
+        ylabel('Xmomentum')
+        
+        file = "dam_h_"
+        #file += str(number_of_cells[i])
+        file += ".eps"
+        #savefig(file)
+        show()
+
+print 'That took %.2f seconds'%(time.time()-t0)
Index: /anuga_work/development/shallow_water_1d/domain_adjust.py
===================================================================
--- /anuga_work/development/shallow_water_1d/domain_adjust.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/domain_adjust.py	(revision 4959)
@@ -0,0 +1,1130 @@
+"""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 *
+from coordinate_transforms.geo_reference import Geo_reference
+
+class Domain:
+
+    def __init__(self, coordinates, boundary = None,
+                 conserved_quantities = None, other_quantities = None,
+                 tagged_elements = None, geo_reference = None):
+        """
+        Build 1D elements from x coordinates
+        """
+
+        from Numeric import array, zeros, Float, Int
+        
+        #Store Points
+        self.coordinates = array(coordinates)
+
+        if geo_reference is None:
+            self.geo_reference = Geo_reference() #Use defaults 
+        else:
+            self.geo_reference = geo_reference
+
+        #Register number of Elements
+        self.number_of_elements = N = len(self.coordinates)-1
+
+        self.beta = 1.0
+        self.limiter = "minmod_kurganov"
+        self.split = False
+        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_edges = 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.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
+            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)
+            
+##         print 'N', N
+##         print 'Centroid', self.centroids
+##         print 'Areas', self.areas
+##         print 'Vertex_Coordinates', self.vertices
+            
+            #Initialise Neighbours (-1 means that it is a boundary neighbour)
+            self.neighbours[i, :] = [-1, -1]
+            #Initialise edge ids of neighbours
+            #Initialise vertex ids of neighbours
+            #In case of boundaries this slot is not used
+            #self.neighbour_edges[i, :] = [-1, -1]
+            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, edge) to symbolic tags
+        #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_adjust 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 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.conserved_quantities:
+            self.quantities[name] = Conserved_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
+        self.CFL = CFL
+
+        #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.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 = self.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            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_edge = 0
+        #r_edge = 1
+        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.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            a = self.vertices[i,0]
+            b = self.vertices[i,1]
+            
+            """
+            if neighbourdict.has_key((a,b)):
+                    msg = "Edge 2 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[a,b][1],neighbourdict[a,b][0])
+                    raise msg
+            if neighbourdict.has_key((b,c)):
+                    msg = "Edge 0 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[b,c][1],neighbourdict[b,c][0])
+                    raise msg
+            if neighbourdict.has_key((c,a)):
+                    msg = "Edge 1 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[c,a][1],neighbourdict[c,a][0])
+                    raise msg
+                    """
+            #neighbourdict[a,b] = (i, 2) #(id, edge)
+            #neighbourdict[b,c] = (i, 0) #(id, edge)
+            #neighbourdict[c,a] = (i, 1) #(id, edge)
+            #neighbourdict[a,b] = (i, 1) #(id, edge)
+            #neighbourdict[b,a] = (i, 0) #(id, edge)
+            #neighbourdict[a,l_edge] = (i, 0) #(id, edge)
+            #neighbourdict[b,r_edge] = (i, 1) #(id, edge)
+            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.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            
+            a = self.vertices[i,0]
+            b = self.vertices[i,1]
+            
+            #self.number_of_boundaries[i] = 3
+            self.number_of_boundaries[i] = 2
+            #if neighbourdict.has_key((b,l_edge)):
+            if neighbourdict.has_key((b,l_vertex)):
+                #self.neighbours[i, 1] = neighbourdict[b,l_edge][0]
+                #self.neighbour_edges[i, 1] = neighbourdict[b,l_edge][1]
+                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_edge)):
+            if neighbourdict.has_key((a,r_vertex)):
+                #self.neighbours[i, 0] = neighbourdict[a,r_edge][0]
+                #self.neighbour_edges[i, 0] = neighbourdict[a,r_edge][1]
+                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
+                
+            #if neighbourdict.has_key((b,a)):
+            #    self.neighbours[i, 1] = neighbourdict[b,a][0]
+            #    self.neighbour_edges[i, 1] = neighbourdict[b,a][1]
+            #    self.number_of_boundaries[i] -= 1
+
+            #if neighbourdict.has_key((c,b)):
+            #    self.neighbours[i, 0] = neighbourdict[c,b][0]
+            #    self.neighbour_edges[i, 0] = neighbourdict[c,b][1]
+            #    self.number_of_boundaries[i] -= 1
+
+            #if neighbourdict.has_key((a,b)):
+            #    self.neighbours[i, 0] = neighbourdict[a,b][0]
+            #    self.neighbour_edges[i, 0] = neighbourdict[a,b][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 edge_id in range(0, 3):
+                #for edge_id in range(0, 2):
+                for vertex_id in range(0, 2):    
+                    #if self.neighbours[vol_id, edge_id] < 0:
+                    if self.neighbours[vol_id, vertex_id] < 0:   
+                        #boundary[(vol_id, edge_id)] = default_boundary_tag
+                        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, edge_id)
+                msg = 'Segment (%d, %d) does not exist' %(vol_id, vertex_id)
+                a, b = self.neighbours.shape
+                #assert vol_id < a and edge_id < b, msg
+                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 edge_id in range(0, 3):
+                #for edge_id in range(0, 2):
+                for vertex_id in range(0, 2):    
+                    #if self.neighbours[vol_id, edge_id] < 0:
+                    if self.neighbours[vol_id, vertex_id] < 0:    
+                        #if not boundary.has_key( (vol_id, edge_id) ):
+                        if not boundary.has_key( (vol_id, vertex_id) ):    
+                            msg = 'WARNING: Given boundary does not contain '
+                            #msg += 'tags for edge (%d, %d). '\
+                            #       %(vol_id, edge_id)
+                            msg += 'tags for vertex (%d, %d). '\
+                                   %(vol_id, vertex_id)
+                            msg += 'Assigning default tag (%s).'\
+                                   %default_boundary_tag
+
+                            #FIXME: Print only as per verbosity
+                            #print msg
+
+                            #FIXME: Make this situation an error in the future
+                            #and make another function which will
+                            #enable default boundary-tags where
+                            #tags a not specified
+                            #boundary[ (vol_id, edge_id) ] =\
+                            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
+        #print "tagged_elements", tagged_elements
+        self.tagged_elements = tagged_elements
+
+    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.vertex_coordinates
+            V = self.vertices
+            #return concatenate( (V[:,0:2], V[:,2:4], V[:,4:6]), axis=0)
+
+            N = V.shape[0]
+            #return reshape(V, (3*N, 2))
+            return reshape(V, (N, 2))
+        else:    
+            #return self.vertex_coordinates
+            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
+
+        #if not (vertex is None):# or edge is None):
+        #    msg = 'Values for both vertex and edge was specified.'
+        #    msg += 'Only one (or none) is allowed.'
+       #     raise msg
+
+        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]
+            #elif edge is not None:
+            #    q[i] = Q.edge_values[vol_id, edge]
+            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 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.
+        """
+
+        #FIXME (Ole): Allow new quantities here
+        #from quantity import Quantity, Conserved_quantity
+        #Create appropriate quantity object
+        ##if name in self.conserved_quantities:
+        ##    self.quantities[name] = Conserved_quantity(self)
+        ##else:
+        ##    self.quantities[name] = Quantity(self)
+
+
+        #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, edge_id) in enumerate(x):
+        for k, (vol_id, vertex_id) in enumerate(x):
+            #tag = self.boundary[ (vol_id, edge_id) ]
+            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
+
+        ##assert hasattr(self, 'boundary_objects')
+
+    def write_time(self):
+        print self.timestepping_statistics()
+
+    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
+
+    #Main components of evolve
+    def evolve(self, yieldstep = None, finaltime = None,
+               skip_initial_step = False):
+        """Evolve model from time=0.0 to finaltime yielding results
+        every yieldstep.
+
+        Internally, smaller timesteps may be taken.
+
+        Evolve is implemented as a generator and is to be called as such, e.g.
+
+        for t in domain.evolve(timestep, yieldstep, finaltime):
+            <Do something with domain and t>
+
+        """
+
+        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 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
+
+        ##self.set_defaults()
+
+        if yieldstep is None:
+            yieldstep = max_timestep
+        else:
+            yieldstep = float(yieldstep)
+
+        self.order = self.default_order
+        self.time_order = self.default_time_order
+
+        self.yieldtime = 0.0 #Time between 'yields'
+
+        #Initialise interval of timestep sizes (for reporting only)
+        # SEEMS WIERD
+        self.min_timestep = max_timestep
+        self.max_timestep = min_timestep
+        self.finaltime = finaltime
+        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()
+
+        self.distribute_stage_to_height()
+
+        #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:
+            if self.time_order == 1:
+                #Compute fluxes across each element edge
+                self.compute_fluxes()
+                #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(self.timestep)
+
+                self.adjust_partially_submerged_cells()
+                #update ghosts
+                #self.update_ghosts()
+                #Update vertex and edge values
+                self.distribute_to_vertices_and_edges()
+                self.distribute_stage_to_height()
+                #Update boundary values
+                self.update_boundary()
+
+            elif self.time_order == 2:
+                
+                self.compute_timestep()
+
+                #Solve inhomogeneous operator for half a timestep
+                self.solve_inhomogenous_second_order(yieldstep, finaltime)
+                
+                #Solve homogeneous operator for full timestep using
+                #Harten second order timestepping
+                self.solve_homogenous_second_order(yieldstep,finaltime)
+
+                #Solve inhomogeneous operator for half a timestep
+                self.solve_inhomogenous_second_order(yieldstep, finaltime)
+                
+            #Update time
+            self.time += self.timestep
+            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 abs(self.time - finaltime) < epsilon:
+
+	        #FIXME: There is a rare situation where the
+	        #final time step is stored twice. Can we make a test?
+
+                # Yield final time and stop
+                yield(self.time)
+                break
+
+
+            if abs(self.yieldtime - yieldstep) < epsilon:
+                # 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 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)
+        self.adjust_partially_submerged_cells()
+        #Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+        self.distribute_stage_to_height()
+        #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
+
+        self.adjust_partially_submerged_cells()
+        #Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+        self.distribute_stage_to_height()
+        #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
+
+        self.adjust_partially_submerged_cells()
+        
+        #Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+        self.distribute_stage_to_height()
+        #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'
+            #Q.interpolate_from_vertices_to_edges()
+
+
+    def update_boundary(self):
+        """Go through list of boundary objects and update boundary values
+        for all conserved quantities on boundary.
+        """
+
+        #FIXME: Update only those that change (if that can be worked out)
+        #FIXME: Boundary objects should not include ghost nodes.
+        #for i, ((vol_id, edge_id), B) in enumerate(self.boundary_objects):
+        #    q = B.evaluate(vol_id, edge_id)
+        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.conserved_quantities):
+                Q = self.quantities[name]
+                Q.boundary_values[i] = q[j]
+
+    def update_timestep(self, yieldstep, finaltime):
+
+        from config import min_timestep
+
+        # self.timestep is calculated from speed of characteristics
+        # Apply CFL condition here
+        timestep = self.CFL*self.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 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
+        """
+        #print "in compute_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,timestep):
+        """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()
+
+        #print "in update conserved quantities"
+
+        #Update conserved_quantities
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            #print "integral", Q.get_integral()
+            Q.update(timestep)
+            #print "integral", Q.get_integral()
+
+            #Clean up
+            #Note that Q.explicit_update is reset by compute_fluxes
+
+            #MH090605 commented out the following since semi_implicit_update is now re-initialized
+            #at the end of the _update function in quantity_ext.c (This is called by the
+            #preceeding Q.update(timestep) statement above).
+            #For run_profile.py with N=128, the time of update_conserved_quantities is cut from 14.00 secs
+            #to 8.35 secs
+
+            #Q.semi_implicit_update[:] = 0.0
+
+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
+
+    #points2 = [0.0, 1.0, 2.0, 3.0, 2.5]
+    #D2 = Domain(points2)
+
Index: /anuga_work/development/shallow_water_1d/domain_order2.py
===================================================================
--- /anuga_work/development/shallow_water_1d/domain_order2.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/domain_order2.py	(revision 4959)
@@ -0,0 +1,1031 @@
+"""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 *
+from coordinate_transforms.geo_reference import Geo_reference
+
+class Domain:
+
+    def __init__(self, coordinates, boundary = None,
+                 conserved_quantities = None, other_quantities = None,
+                 tagged_elements = None, geo_reference = None):
+        """
+        Build 1D elements from x coordinates
+        """
+
+        from Numeric import array, zeros, Float, Int
+        
+        #Store Points
+        self.coordinates = array(coordinates)
+
+        if geo_reference is None:
+            self.geo_reference = Geo_reference() #Use defaults 
+        else:
+            self.geo_reference = geo_reference
+
+        #Register number of Elements
+        self.number_of_elements = N = len(self.coordinates)-1
+
+        self.beta = 1.0
+        self.limiter = "minmod_kurganov"
+        self.split = False
+        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_edges = 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.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)
+            
+##         print 'N', N
+##         print 'Centroid', self.centroids
+##         print 'Areas', self.areas
+##         print 'Vertex_Coordinates', self.vertices
+            
+            #Initialise Neighbours (-1 means that it is a boundary neighbour)
+            self.neighbours[i, :] = [-1, -1]
+            #Initialise edge ids of neighbours
+            #Initialise vertex ids of neighbours
+            #In case of boundaries this slot is not used
+            #self.neighbour_edges[i, :] = [-1, -1]
+            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, edge) to symbolic tags
+        #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
+        from quantity_domain 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 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.conserved_quantities:
+            self.quantities[name] = Conserved_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
+        self.CFL = CFL
+
+        #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.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 = self.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            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_edge = 0
+        #r_edge = 1
+        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.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            a = self.vertices[i,0]
+            b = self.vertices[i,1]
+            
+            """
+            if neighbourdict.has_key((a,b)):
+                    msg = "Edge 2 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[a,b][1],neighbourdict[a,b][0])
+                    raise msg
+            if neighbourdict.has_key((b,c)):
+                    msg = "Edge 0 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[b,c][1],neighbourdict[b,c][0])
+                    raise msg
+            if neighbourdict.has_key((c,a)):
+                    msg = "Edge 1 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[c,a][1],neighbourdict[c,a][0])
+                    raise msg
+                    """
+            #neighbourdict[a,b] = (i, 2) #(id, edge)
+            #neighbourdict[b,c] = (i, 0) #(id, edge)
+            #neighbourdict[c,a] = (i, 1) #(id, edge)
+            #neighbourdict[a,b] = (i, 1) #(id, edge)
+            #neighbourdict[b,a] = (i, 0) #(id, edge)
+            #neighbourdict[a,l_edge] = (i, 0) #(id, edge)
+            #neighbourdict[b,r_edge] = (i, 1) #(id, edge)
+            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.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            
+            a = self.vertices[i,0]
+            b = self.vertices[i,1]
+            
+            #self.number_of_boundaries[i] = 3
+            self.number_of_boundaries[i] = 2
+            #if neighbourdict.has_key((b,l_edge)):
+            if neighbourdict.has_key((b,l_vertex)):
+                #self.neighbours[i, 1] = neighbourdict[b,l_edge][0]
+                #self.neighbour_edges[i, 1] = neighbourdict[b,l_edge][1]
+                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_edge)):
+            if neighbourdict.has_key((a,r_vertex)):
+                #self.neighbours[i, 0] = neighbourdict[a,r_edge][0]
+                #self.neighbour_edges[i, 0] = neighbourdict[a,r_edge][1]
+                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
+                
+            #if neighbourdict.has_key((b,a)):
+            #    self.neighbours[i, 1] = neighbourdict[b,a][0]
+            #    self.neighbour_edges[i, 1] = neighbourdict[b,a][1]
+            #    self.number_of_boundaries[i] -= 1
+
+            #if neighbourdict.has_key((c,b)):
+            #    self.neighbours[i, 0] = neighbourdict[c,b][0]
+            #    self.neighbour_edges[i, 0] = neighbourdict[c,b][1]
+            #    self.number_of_boundaries[i] -= 1
+
+            #if neighbourdict.has_key((a,b)):
+            #    self.neighbours[i, 0] = neighbourdict[a,b][0]
+            #    self.neighbour_edges[i, 0] = neighbourdict[a,b][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 edge_id in range(0, 3):
+                #for edge_id in range(0, 2):
+                for vertex_id in range(0, 2):    
+                    #if self.neighbours[vol_id, edge_id] < 0:
+                    if self.neighbours[vol_id, vertex_id] < 0:   
+                        #boundary[(vol_id, edge_id)] = default_boundary_tag
+                        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, edge_id)
+                msg = 'Segment (%d, %d) does not exist' %(vol_id, vertex_id)
+                a, b = self.neighbours.shape
+                #assert vol_id < a and edge_id < b, msg
+                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 edge_id in range(0, 3):
+                #for edge_id in range(0, 2):
+                for vertex_id in range(0, 2):    
+                    #if self.neighbours[vol_id, edge_id] < 0:
+                    if self.neighbours[vol_id, vertex_id] < 0:    
+                        #if not boundary.has_key( (vol_id, edge_id) ):
+                        if not boundary.has_key( (vol_id, vertex_id) ):    
+                            msg = 'WARNING: Given boundary does not contain '
+                            #msg += 'tags for edge (%d, %d). '\
+                            #       %(vol_id, edge_id)
+                            msg += 'tags for vertex (%d, %d). '\
+                                   %(vol_id, vertex_id)
+                            msg += 'Assigning default tag (%s).'\
+                                   %default_boundary_tag
+
+                            #FIXME: Print only as per verbosity
+                            #print msg
+
+                            #FIXME: Make this situation an error in the future
+                            #and make another function which will
+                            #enable default boundary-tags where
+                            #tags a not specified
+                            #boundary[ (vol_id, edge_id) ] =\
+                            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
+        #print "tagged_elements", tagged_elements
+        self.tagged_elements = tagged_elements
+
+    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.vertex_coordinates
+            V = self.vertices
+            #return concatenate( (V[:,0:2], V[:,2:4], V[:,4:6]), axis=0)
+
+            N = V.shape[0]
+            #return reshape(V, (3*N, 2))
+            return reshape(V, (N, 2))
+        else:    
+            #return self.vertex_coordinates
+            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
+
+        #if not (vertex is None):# or edge is None):
+        #    msg = 'Values for both vertex and edge was specified.'
+        #    msg += 'Only one (or none) is allowed.'
+       #     raise msg
+
+        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]
+            #elif edge is not None:
+            #    q[i] = Q.edge_values[vol_id, edge]
+            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 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.
+        """
+
+        #FIXME (Ole): Allow new quantities here
+        #from quantity import Quantity, Conserved_quantity
+        #Create appropriate quantity object
+        ##if name in self.conserved_quantities:
+        ##    self.quantities[name] = Conserved_quantity(self)
+        ##else:
+        ##    self.quantities[name] = Quantity(self)
+
+
+        #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, edge_id) in enumerate(x):
+        for k, (vol_id, vertex_id) in enumerate(x):
+            #tag = self.boundary[ (vol_id, edge_id) ]
+            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
+
+        ##assert hasattr(self, 'boundary_objects')
+
+    def write_time(self):
+        print self.timestepping_statistics()
+
+    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
+
+#Main components of evolve
+    def evolve(self, yieldstep = None, finaltime = None,
+               skip_initial_step = False):
+        """Evolve model from time=0.0 to finaltime yielding results
+        every yieldstep.
+
+        Internally, smaller timesteps may be taken.
+
+        Evolve is implemented as a generator and is to be called as such, e.g.
+
+        for t in domain.evolve(timestep, yieldstep, finaltime):
+            <Do something with domain and t>
+
+        """
+
+        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 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
+
+        ##self.set_defaults()
+
+        if yieldstep is None:
+            yieldstep = max_timestep
+        else:
+            yieldstep = float(yieldstep)
+
+        self.order = self.default_order
+        self.time_order = self.default_time_order
+
+        self.yieldtime = 0.0 #Time between 'yields'
+
+        #Initialise interval of timestep sizes (for reporting only)
+        # SEEMS WIERD
+        self.min_timestep = max_timestep
+        self.max_timestep = min_timestep
+        self.finaltime = finaltime
+        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()
+
+        #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
+
+        if self.time_order == 2:
+            self.compute_timestep()
+
+        while True:
+            if self.time_order == 1:
+                #Compute fluxes across each element edge
+                self.compute_fluxes()
+                #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(self.timestep)
+                #update ghosts
+                #self.update_ghosts()
+                #Update vertex and edge values
+                self.distribute_to_vertices_and_edges()                
+                #Update boundary values
+                self.update_boundary()
+
+            elif self.time_order == 2:
+                if self.flux_first:
+                    #Solve homogeneous operator for half a timestep
+                    self.compute_fluxes()
+                    self.update_timestep(yieldstep, finaltime)
+                    self.update_conserved_quantities(0.5*self.timestep)
+                    self.distribute_to_vertices_and_edges()
+                    self.update_boundary()
+
+                    #Solve inhomogeneous operator for full timestep
+                    self.compute_forcing_terms()
+                    self.update_conserved_quantities(self.timestep)
+                    self.distribute_to_vertices_and_edges()
+                    self.update_boundary()
+
+                    #Solve homogeneous operator for half a timestep
+                    self.compute_fluxes()
+                    #self.update_timestep(yieldstep, finaltime)
+                    self.update_conserved_quantities(0.5*self.timestep)
+                    self.distribute_to_vertices_and_edges()
+                    self.update_boundary()
+                
+                elif not self.flux_first:                
+                    #Solve inhomogeneous operator for half a timestep
+                    #self.compute_timestep()
+                    self.update_timestep(yieldstep, finaltime) #note adding this line improves performance
+                    #TEMP FIX: Need to develop better way to calculate timestep
+                    #This uses previous timestep as new timestep
+                    self.compute_forcing_terms()
+                    self.update_conserved_quantities(0.5*self.timestep)
+                    self.distribute_to_vertices_and_edges()
+                    self.update_boundary()
+
+                    #Solve homogeneous operator for full timestep
+                    #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(self.timestep)
+                    #Update vertex and edge values
+                    self.distribute_to_vertices_and_edges()
+                    #Update boundary values
+                    self.update_boundary()
+
+
+                    ##Solve inhomogeneous operator for half a timestep
+                    self.compute_forcing_terms()
+                    self.update_conserved_quantities(0.5*self.timestep)
+                    self.distribute_to_vertices_and_edges()
+                    self.update_boundary()
+
+            
+            #print 'timestep', self.timestep
+
+            #Update time
+            self.time += self.timestep
+            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 abs(self.time - finaltime) < epsilon:
+
+	        #FIXME: There is a rare situation where the
+	        #final time step is stored twice. Can we make a test?
+
+                # Yield final time and stop
+                yield(self.time)
+                break
+
+
+            if abs(self.yieldtime - yieldstep) < epsilon:
+                # 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 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'
+            #Q.interpolate_from_vertices_to_edges()
+
+
+    def update_boundary(self):
+        """Go through list of boundary objects and update boundary values
+        for all conserved quantities on boundary.
+        """
+
+        #FIXME: Update only those that change (if that can be worked out)
+        #FIXME: Boundary objects should not include ghost nodes.
+        #for i, ((vol_id, edge_id), B) in enumerate(self.boundary_objects):
+        #    q = B.evaluate(vol_id, edge_id)
+        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.conserved_quantities):
+                Q = self.quantities[name]
+                Q.boundary_values[i] = q[j]
+
+    def update_timestep(self, yieldstep, finaltime):
+
+        from config import min_timestep
+
+        # self.timestep is calculated from speed of characteristics
+        # Apply CFL condition here
+        timestep = self.CFL*self.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 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,timestep):
+        """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)
+
+            #Clean up
+            #Note that Q.explicit_update is reset by compute_fluxes
+
+            #MH090605 commented out the following since semi_implicit_update is now re-initialized
+            #at the end of the _update function in quantity_ext.c (This is called by the
+            #preceeding Q.update(timestep) statement above).
+            #For run_profile.py with N=128, the time of update_conserved_quantities is cut from 14.00 secs
+            #to 8.35 secs
+
+            #Q.semi_implicit_update[:] = 0.0
+
+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
+
+    #points2 = [0.0, 1.0, 2.0, 3.0, 2.5]
+    #D2 = Domain(points2)
+
Index: /anuga_work/development/shallow_water_1d/domain_t2.py
===================================================================
--- /anuga_work/development/shallow_water_1d/domain_t2.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/domain_t2.py	(revision 4959)
@@ -0,0 +1,1112 @@
+"""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 *
+from coordinate_transforms.geo_reference import Geo_reference
+
+class Domain:
+
+    def __init__(self, coordinates, boundary = None,
+                 conserved_quantities = None, other_quantities = None,
+                 tagged_elements = None, geo_reference = None):
+        """
+        Build 1D elements from x coordinates
+        """
+
+        from Numeric import array, zeros, Float, Int
+        
+        #Store Points
+        self.coordinates = array(coordinates)
+
+        if geo_reference is None:
+            self.geo_reference = Geo_reference() #Use defaults 
+        else:
+            self.geo_reference = geo_reference
+
+        #Register number of Elements
+        self.number_of_elements = N = len(self.coordinates)-1
+
+        self.beta = 1.0
+        self.limiter = "minmod_kurganov"
+        self.split = False
+        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_edges = 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.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)
+            
+##         print 'N', N
+##         print 'Centroid', self.centroids
+##         print 'Areas', self.areas
+##         print 'Vertex_Coordinates', self.vertices
+            
+            #Initialise Neighbours (-1 means that it is a boundary neighbour)
+            self.neighbours[i, :] = [-1, -1]
+            #Initialise edge ids of neighbours
+            #Initialise vertex ids of neighbours
+            #In case of boundaries this slot is not used
+            #self.neighbour_edges[i, :] = [-1, -1]
+            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, edge) to symbolic tags
+        #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
+        #from quantity_domain 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 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.conserved_quantities:
+            self.quantities[name] = Conserved_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
+        self.CFL = CFL
+
+        #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.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 = self.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            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_edge = 0
+        #r_edge = 1
+        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.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            a = self.vertices[i,0]
+            b = self.vertices[i,1]
+            
+            """
+            if neighbourdict.has_key((a,b)):
+                    msg = "Edge 2 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[a,b][1],neighbourdict[a,b][0])
+                    raise msg
+            if neighbourdict.has_key((b,c)):
+                    msg = "Edge 0 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[b,c][1],neighbourdict[b,c][0])
+                    raise msg
+            if neighbourdict.has_key((c,a)):
+                    msg = "Edge 1 of triangle %d is duplicating edge %d of triangle %d.\n" %(i,neighbourdict[c,a][1],neighbourdict[c,a][0])
+                    raise msg
+                    """
+            #neighbourdict[a,b] = (i, 2) #(id, edge)
+            #neighbourdict[b,c] = (i, 0) #(id, edge)
+            #neighbourdict[c,a] = (i, 1) #(id, edge)
+            #neighbourdict[a,b] = (i, 1) #(id, edge)
+            #neighbourdict[b,a] = (i, 0) #(id, edge)
+            #neighbourdict[a,l_edge] = (i, 0) #(id, edge)
+            #neighbourdict[b,r_edge] = (i, 1) #(id, edge)
+            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.triangles[i, 0]
+            #b = self.triangles[i, 1]
+            #c = self.triangles[i, 2]
+            
+            a = self.vertices[i,0]
+            b = self.vertices[i,1]
+            
+            #self.number_of_boundaries[i] = 3
+            self.number_of_boundaries[i] = 2
+            #if neighbourdict.has_key((b,l_edge)):
+            if neighbourdict.has_key((b,l_vertex)):
+                #self.neighbours[i, 1] = neighbourdict[b,l_edge][0]
+                #self.neighbour_edges[i, 1] = neighbourdict[b,l_edge][1]
+                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_edge)):
+            if neighbourdict.has_key((a,r_vertex)):
+                #self.neighbours[i, 0] = neighbourdict[a,r_edge][0]
+                #self.neighbour_edges[i, 0] = neighbourdict[a,r_edge][1]
+                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
+                
+            #if neighbourdict.has_key((b,a)):
+            #    self.neighbours[i, 1] = neighbourdict[b,a][0]
+            #    self.neighbour_edges[i, 1] = neighbourdict[b,a][1]
+            #    self.number_of_boundaries[i] -= 1
+
+            #if neighbourdict.has_key((c,b)):
+            #    self.neighbours[i, 0] = neighbourdict[c,b][0]
+            #    self.neighbour_edges[i, 0] = neighbourdict[c,b][1]
+            #    self.number_of_boundaries[i] -= 1
+
+            #if neighbourdict.has_key((a,b)):
+            #    self.neighbours[i, 0] = neighbourdict[a,b][0]
+            #    self.neighbour_edges[i, 0] = neighbourdict[a,b][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 edge_id in range(0, 3):
+                #for edge_id in range(0, 2):
+                for vertex_id in range(0, 2):    
+                    #if self.neighbours[vol_id, edge_id] < 0:
+                    if self.neighbours[vol_id, vertex_id] < 0:   
+                        #boundary[(vol_id, edge_id)] = default_boundary_tag
+                        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, edge_id)
+                msg = 'Segment (%d, %d) does not exist' %(vol_id, vertex_id)
+                a, b = self.neighbours.shape
+                #assert vol_id < a and edge_id < b, msg
+                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 edge_id in range(0, 3):
+                #for edge_id in range(0, 2):
+                for vertex_id in range(0, 2):    
+                    #if self.neighbours[vol_id, edge_id] < 0:
+                    if self.neighbours[vol_id, vertex_id] < 0:    
+                        #if not boundary.has_key( (vol_id, edge_id) ):
+                        if not boundary.has_key( (vol_id, vertex_id) ):    
+                            msg = 'WARNING: Given boundary does not contain '
+                            #msg += 'tags for edge (%d, %d). '\
+                            #       %(vol_id, edge_id)
+                            msg += 'tags for vertex (%d, %d). '\
+                                   %(vol_id, vertex_id)
+                            msg += 'Assigning default tag (%s).'\
+                                   %default_boundary_tag
+
+                            #FIXME: Print only as per verbosity
+                            #print msg
+
+                            #FIXME: Make this situation an error in the future
+                            #and make another function which will
+                            #enable default boundary-tags where
+                            #tags a not specified
+                            #boundary[ (vol_id, edge_id) ] =\
+                            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
+        #print "tagged_elements", tagged_elements
+        self.tagged_elements = tagged_elements
+
+    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.vertex_coordinates
+            V = self.vertices
+            #return concatenate( (V[:,0:2], V[:,2:4], V[:,4:6]), axis=0)
+
+            N = V.shape[0]
+            #return reshape(V, (3*N, 2))
+            return reshape(V, (N, 2))
+        else:    
+            #return self.vertex_coordinates
+            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
+
+        #if not (vertex is None):# or edge is None):
+        #    msg = 'Values for both vertex and edge was specified.'
+        #    msg += 'Only one (or none) is allowed.'
+       #     raise msg
+
+        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]
+            #elif edge is not None:
+            #    q[i] = Q.edge_values[vol_id, edge]
+            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 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.
+        """
+
+        #FIXME (Ole): Allow new quantities here
+        #from quantity import Quantity, Conserved_quantity
+        #Create appropriate quantity object
+        ##if name in self.conserved_quantities:
+        ##    self.quantities[name] = Conserved_quantity(self)
+        ##else:
+        ##    self.quantities[name] = Quantity(self)
+
+
+        #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, edge_id) in enumerate(x):
+        for k, (vol_id, vertex_id) in enumerate(x):
+            #tag = self.boundary[ (vol_id, edge_id) ]
+            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
+
+        ##assert hasattr(self, 'boundary_objects')
+
+    def write_time(self):
+        print self.timestepping_statistics()
+
+    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
+
+#Main components of evolve
+    def evolve(self, yieldstep = None, finaltime = None,
+               skip_initial_step = False):
+        """Evolve model from time=0.0 to finaltime yielding results
+        every yieldstep.
+
+        Internally, smaller timesteps may be taken.
+
+        Evolve is implemented as a generator and is to be called as such, e.g.
+
+        for t in domain.evolve(timestep, yieldstep, finaltime):
+            <Do something with domain and t>
+
+        """
+
+        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 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
+
+        ##self.set_defaults()
+
+        if yieldstep is None:
+            yieldstep = max_timestep
+        else:
+            yieldstep = float(yieldstep)
+
+        self.order = self.default_order
+        self.time_order = self.default_time_order
+
+        self.yieldtime = 0.0 #Time between 'yields'
+
+        #Initialise interval of timestep sizes (for reporting only)
+        # SEEMS WIERD
+        self.min_timestep = max_timestep
+        self.max_timestep = min_timestep
+        self.finaltime = finaltime
+        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()
+
+        #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:
+            if self.time_order == 1:
+                #Compute fluxes across each element edge
+                self.compute_fluxes()
+                #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(self.timestep)
+                #update ghosts
+                #self.update_ghosts()
+                #Update vertex and edge values
+                self.distribute_to_vertices_and_edges()                
+                #Update boundary values
+                self.update_boundary()
+
+            elif self.time_order == 2:
+                
+                self.compute_timestep()
+
+                #Solve inhomogeneous operator for half a timestep
+                self.solve_inhomogenous_second_order(yieldstep, finaltime)
+                
+                #Solve homogeneous operator for full timestep using
+                #Harten second order timestepping
+                self.solve_homogenous_second_order(yieldstep,finaltime)
+
+                #Solve inhomogeneous operator for half a timestep
+                self.solve_inhomogenous_second_order(yieldstep, finaltime)
+                
+            #Update time
+            self.time += self.timestep
+            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 abs(self.time - finaltime) < epsilon:
+
+	        #FIXME: There is a rare situation where the
+	        #final time step is stored twice. Can we make a test?
+
+                # Yield final time and stop
+                yield(self.time)
+                break
+
+
+            if abs(self.yieldtime - yieldstep) < epsilon:
+                # 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 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'
+            #Q.interpolate_from_vertices_to_edges()
+
+
+    def update_boundary(self):
+        """Go through list of boundary objects and update boundary values
+        for all conserved quantities on boundary.
+        """
+
+        #FIXME: Update only those that change (if that can be worked out)
+        #FIXME: Boundary objects should not include ghost nodes.
+        #for i, ((vol_id, edge_id), B) in enumerate(self.boundary_objects):
+        #    q = B.evaluate(vol_id, edge_id)
+        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.conserved_quantities):
+                Q = self.quantities[name]
+                Q.boundary_values[i] = q[j]
+
+    def update_timestep(self, yieldstep, finaltime):
+
+        from config import min_timestep
+
+        # self.timestep is calculated from speed of characteristics
+        # Apply CFL condition here
+        timestep = self.CFL*self.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 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,timestep):
+        """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)
+
+            #Clean up
+            #Note that Q.explicit_update is reset by compute_fluxes
+
+            #MH090605 commented out the following since semi_implicit_update is now re-initialized
+            #at the end of the _update function in quantity_ext.c (This is called by the
+            #preceeding Q.update(timestep) statement above).
+            #For run_profile.py with N=128, the time of update_conserved_quantities is cut from 14.00 secs
+            #to 8.35 secs
+
+            #Q.semi_implicit_update[:] = 0.0
+
+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
+
+    #points2 = [0.0, 1.0, 2.0, 3.0, 2.5]
+    #D2 = Domain(points2)
+
Index: /anuga_work/development/shallow_water_1d/dry_dam.py
===================================================================
--- /anuga_work/development/shallow_water_1d/dry_dam.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/dry_dam.py	(revision 4959)
@@ -0,0 +1,156 @@
+import os
+from math import sqrt, pi
+from shallow_water_1d import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+def analytical_sol(C,t):
+    
+    #t  = 0.0     # time (s)
+    g  = 9.81    # gravity (m/s^2)
+    h1 = 10.0    # depth upstream (m)
+    h0 = 0.0     # depth downstream (m)
+    L = 2000.0   # length of stream/domain (m)
+    n = len(C)    # number of cells
+
+    u = zeros(n,Float)
+    h = zeros(n,Float)
+    x = C-L/2.0
+    #x = zeros(n,Float)
+    #for i in range(n):
+    #    x[i] = C[i]-1000.0
+
+    for i in range(n):
+        # Calculate Analytical Solution at time t > 0
+        u3 = 2.0/3.0*(sqrt(g*h1)+x[i]/t) 
+        h3 = 4.0/(9.0*g)*(sqrt(g*h1)-x[i]/(2.0*t))*(sqrt(g*h1)-x[i]/(2.0*t)) 
+
+        if ( x[i] <= -t*sqrt(g*h1) ):
+            u[i] = 0.0 
+            h[i] = h1 
+        elif ( x[i] <= 2.0*t*sqrt(g*h1) ):
+            u[i] = u3 
+            h[i] = h3 
+        else:
+            u[i] = 0.0 
+            h[i] = h0 
+
+    return h , u*h
+
+def newLinePlot(title='Simple Plot'):
+    import Gnuplot
+    gg = Gnuplot.Gnuplot(persist=0)
+    gg.terminal(postscript)
+    gg.title(title)
+    gg('set data style linespoints') 
+    gg.xlabel('x')
+    gg.ylabel('y')
+    return gg
+
+def linePlot(gg,x1,y1,x2,y2):
+    import Gnuplot
+    plot1 = Gnuplot.PlotItems.Data(x1.flat,y1.flat,with="linespoints")
+    plot2 = Gnuplot.PlotItems.Data(x2.flat,y2.flat, with="lines 3")
+    g.plot(plot1,plot2)
+
+#debug = False
+
+print "TEST 1D-SOLUTION III -- DRY BED"
+
+L = 2000.0     # Length of channel (m)
+N = 100        # Number of compuational cells
+cell_len = L/N # Origin = 0.0
+
+points = zeros(N+1,Float)
+for i in range(N+1):
+    points[i] = i*cell_len
+
+domain = Domain(points)
+
+def stage(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        if x[i]<=1000.0:
+            y[i] = 10.0
+        else:
+            y[i] = 0.0
+    return y
+
+
+import time
+
+finaltime = 30.0
+yieldstep = 1
+L = 2000.0     # Length of channel (m)
+number_of_cells = [100]#,200,500,1000,2000,5000,10000,20000]
+h_error = zeros(len(number_of_cells),Float)
+uh_error = zeros(len(number_of_cells),Float)
+k = 0
+for i in range(len(number_of_cells)):
+    N = int(number_of_cells[i])
+    print "Evaluating domain with %d cells" %N
+    cell_len = L/N # Origin = 0.0
+    points = zeros(N+1,Float)
+    for j in range(N+1):
+        points[j] = j*cell_len
+        
+    domain = Domain(points)
+    
+    domain.set_quantity('stage', stage)
+    domain.set_boundary({'exterior': Reflective_boundary(domain)})
+    domain.default_order = 2
+    domain.default_time_order = 1
+    domain.cfl = 1.0
+    domain.limiter = "vanleer"
+
+    t0 = time.time()
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        pass
+    N = float(N)
+    StageC = domain.quantities['stage'].centroid_values
+    XmomC = domain.quantities['xmomentum'].centroid_values
+    C = domain.centroids
+    h, uh = analytical_sol(C,domain.time)
+    h_error[k] = 1.0/(N)*sum(abs(h-StageC))
+    uh_error[k] = 1.0/(N)*sum(abs(uh-XmomC))
+    print "h_error %.10f" %(h_error[k])
+    print "uh_error %.10f"% (uh_error[k])
+    k = k+1
+    print 'That took %.2f seconds' %(time.time()-t0)
+    X = domain.vertices
+    StageQ = domain.quantities['stage'].vertex_values
+    XmomQ = domain.quantities['xmomentum'].vertex_values
+    h, uh = analytical_sol(X.flat,domain.time)
+    #from pylab import * # this command stuffs up setting of new domain
+    from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+    print 'test2'
+    #hold(False)
+    #subplot(211)
+    #plot1 = plot(X,h,X,StageQ)
+    hold(False)
+    plot1 = subplot(211)
+    plot(X,h,X,StageQ)
+    plot1.set_ylim([-1,11])
+    #plot1 = plot(X,StageQ,'o',X,h)
+    #set(markersize=1)
+    #title('Free Surface Elevation of a Dry Dam-Break')
+    xlabel('Position')
+    ylabel('Stage')
+    legend(('Analytical Solution', 'Numerical Solution'),
+           'upper right', shadow=True)
+    plot2 = subplot(212)
+    plot(X,uh,X,XmomQ)
+    plot2.set_ylim([-5,35])
+    #title('Xmomentum Profile of a Dry Dam-Break')
+    xlabel('Position')
+    ylabel('Xmomentum')
+    #legend(('Analytical Solution', 'Numerical Solution'),
+    #       'upper right', shadow=True)
+    file = "dry_bed_"
+    file += str(number_of_cells[i])
+    file += ".eps"
+    #savefig(file)
+    show()
+    
+print "Error in height", h_error
+print "Error in xmom", uh_error
Index: /anuga_work/development/shallow_water_1d/dry_dam_sudi.py
===================================================================
--- /anuga_work/development/shallow_water_1d/dry_dam_sudi.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/dry_dam_sudi.py	(revision 4959)
@@ -0,0 +1,154 @@
+import os
+from math import sqrt, pi
+from shallow_water_1d import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+def analytical_sol(C,t):
+    
+    #t  = 0.0     # time (s)
+    g  = 9.81    # gravity (m/s^2)
+    h1 = 10.0    # depth upstream (m)
+    h0 = 0.0     # depth downstream (m)
+    L = 2000.0   # length of stream/domain (m)
+    n = len(C)    # number of cells
+
+    u = zeros(n,Float)
+    h = zeros(n,Float)
+    x = C-3*L/4.0
+    
+
+    for i in range(n):
+        # Calculate Analytical Solution at time t > 0
+        u3 = 2.0/3.0*(sqrt(g*h1)+x[i]/t) 
+        h3 = 4.0/(9.0*g)*(sqrt(g*h1)-x[i]/(2.0*t))*(sqrt(g*h1)-x[i]/(2.0*t)) 
+
+        if ( x[i] <= -t*sqrt(g*h1) ):
+            u[i] = 0.0 
+            h[i] = h1 
+        elif ( x[i] <= 2.0*t*sqrt(g*h1) ):
+            u[i] = u3 
+            h[i] = h3 
+        else:
+            u[i] = 0.0 
+            h[i] = h0 
+
+    return h , u*h
+
+#def newLinePlot(title='Simple Plot'):
+#   import Gnuplot
+#    gg = Gnuplot.Gnuplot(persist=0)
+#    gg.terminal(postscript)
+#    gg.title(title)
+#    gg('set data style linespoints') 
+#    gg.xlabel('x')
+#    gg.ylabel('y')
+#    return gg
+
+#def linePlot(gg,x1,y1,x2,y2):
+#    import Gnuplot
+#    plot1 = Gnuplot.PlotItems.Data(x1.flat,y1.flat,with="linespoints")
+#    plot2 = Gnuplot.PlotItems.Data(x2.flat,y2.flat, with="lines 3")
+#    g.plot(plot1,plot2)
+
+
+
+print "TEST 1D-SOLUTION III -- DRY BED"
+
+L = 2000.0     # Length of channel (m)
+N = 100        # Number of compuational cells
+cell_len = L/N # Origin = 0.0
+
+points = zeros(N+1,Float)
+for i in range(N+1):
+    points[i] = i*cell_len
+
+domain = Domain(points)
+
+def stage(x):
+    h1 = 10.0
+    h0 = 0.0
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        if x[i]<=L/4.0:
+            y[i] = h0
+        elif x[i]<=3*L/4.0:
+            y[i] = h1
+        else:
+            y[i] = h0
+    return y
+
+
+import time
+
+finaltime = 20.0
+yieldstep = 1.0
+L = 2000.0     # Length of channel (m)
+number_of_cells = [100]#,200,500,1000,2000,5000,10000,20000]
+h_error = zeros(len(number_of_cells),Float)
+uh_error = zeros(len(number_of_cells),Float)
+k = 0
+for i in range(len(number_of_cells)):
+    N = int(number_of_cells[i])
+    print "Evaluating domain with %d cells" %N
+    cell_len = L/N # Origin = 0.0
+    points = zeros(N+1,Float)
+    for j in range(N+1):
+        points[j] = j*cell_len
+        
+    domain = Domain(points)
+    
+    domain.set_quantity('stage', stage)
+    domain.set_boundary({'exterior': Reflective_boundary(domain)})
+    domain.default_order = 2
+    domain.default_time_order = 1
+    domain.cfl = 1.0
+    domain.limiter = "vanleer"
+
+    t0 = time.time()
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        pass
+    N = float(N)
+    StageC = domain.quantities['stage'].centroid_values
+    XmomC = domain.quantities['xmomentum'].centroid_values
+    C = domain.centroids
+    h, uh = analytical_sol(C,domain.time)
+    h_error[k] = 1.0/(N)*sum(abs(h-StageC))
+    uh_error[k] = 1.0/(N)*sum(abs(uh-XmomC))
+    print "h_error %.10f" %(h_error[k])
+    print "uh_error %.10f"% (uh_error[k])
+    k = k+1
+    print 'That took %.2f seconds' %(time.time()-t0)
+    X = domain.vertices
+    StageQ = domain.quantities['stage'].vertex_values
+    XmomQ = domain.quantities['xmomentum'].vertex_values
+    h, uh = analytical_sol(X.flat,domain.time)
+  
+    from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+    print 'test2'
+    hold(False)
+    print 'test 3'
+    plot1 = subplot(211)
+    print 'test 4'
+    plot(X,h,X,StageQ)
+    print 'test 5'
+    plot1.set_ylim([-1,11])
+    xlabel('Position')
+    ylabel('Stage')
+    legend(('Analytical Solution', 'Numerical Solution'),
+           'upper right', shadow=True)
+    plot2 = subplot(212)
+    plot(X,uh,X,XmomQ)
+    plot2.set_ylim([-35,35])
+    
+    xlabel('Position')
+    ylabel('Xmomentum')
+   
+    file = "dry_bed_"
+    file += str(number_of_cells[i])
+    file += ".eps"
+    #savefig(file)
+    show()
+    
+print "Error in height", h_error
+print "Error in xmom", uh_error
Index: /anuga_work/development/shallow_water_1d/generic_boundary_conditions.py
===================================================================
--- /anuga_work/development/shallow_water_1d/generic_boundary_conditions.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/generic_boundary_conditions.py	(revision 4959)
@@ -0,0 +1,504 @@
+"""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 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, edge_id):
+        """Transmissive boundaries return the edge values
+        of the volume they serve.
+        """
+
+        q = self.domain.get_conserved_quantities(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.conserved_quantities)
+        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/shallow_water_1d/parabolic_cannal.py
===================================================================
--- /anuga_work/development/shallow_water_1d/parabolic_cannal.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/parabolic_cannal.py	(revision 4959)
@@ -0,0 +1,168 @@
+import os
+from math import sqrt, pi, sin, cos
+from shallow_water_1d import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+def newLinePlot(title='Simple Plot'):
+    import Gnuplot
+    g = Gnuplot.Gnuplot(persist=0)
+    g.title(title)
+    g('set data style linespoints') 
+    g.xlabel('x')
+    g.ylabel('y')
+    return g
+
+def linePlot(g,x1,y1,x2,y2,x3,y3):
+    import Gnuplot
+    plot1 = Gnuplot.PlotItems.Data(x1.flat,y1.flat,with="lines 2")
+    plot2 = Gnuplot.PlotItems.Data(x2.flat,y2.flat,with="lines 3")
+    plot3 = Gnuplot.PlotItems.Data(x3.flat,y3.flat,with="linespoints 1")
+    g.plot(plot1,plot2,plot3)
+
+
+def analytic_cannal(C,t):
+    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
+    
+    for i in range(N):
+        z_b[i] = z_infty*(x[i]**2/L_x**2)
+        u[i] = -A0*omega*sin(omega*t)
+        z[i] = z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))
+
+    h = z-z_b
+    return u,h,z,z_b
+
+
+#plot2 = newLinePlot("Momentum")  
+
+L_x = 2500.0     # Length of channel (m)
+N = 8         # Number of compuational cells
+cell_len = 4*L_x/N   # Origin = 0.0
+
+points = zeros(N+1,Float)
+for i in range(N+1):
+        points[i] = -2*L_x +i*cell_len
+
+domain = Domain(points)
+
+domain.order = 2 #make this unnecessary
+domain.default_order = 2
+domain.default_time_order = 2
+domain.cfl = 1.0
+domain.beta = 1.0
+#domain.limiter = "minmod_kurganov"
+#domain.limiter = "vanleer"
+#domain.limiter = "vanalbada"
+#domain.limiter = "superbee"
+domain.limiter = "steve_minmod"
+
+def stage(x):
+
+    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
+    t=0.0
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        #xy[i] = z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))
+        y[i] = 12.0
+    return y
+
+def elevation(x):
+    N = len(x)
+    z_infty = 10.0
+    z = zeros(N,Float)
+    L_x = 2500.0
+    A0 = 0.5*L_x
+    omega = sqrt(2*g*z_infty)/L_x
+    for i in range(N):
+        z[i] = z_infty*(x[i]**2/L_x**2)
+    return z
+
+def height(x):
+    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
+    t=0.0
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i] = max(z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))-z_infty*(x[i]**2/L_x**2),0.0)
+    return y
+
+    
+domain.set_quantity('stage', stage)
+domain.set_quantity('elevation',elevation)
+#domain.set_quantity('height',height)
+
+domain.set_boundary({'exterior': Reflective_boundary(domain)})
+ 
+import time
+t0 = time.time()
+finaltime = 1122.0*0.75
+yieldstep = finaltime
+yieldstep = 10.0
+plot1 = newLinePlot("Stage")
+plot2 = newLinePlot("Xmomentum")
+C = domain.centroids
+X = domain.vertices
+StageQ = domain.quantities['stage'].vertex_values
+XmomQ = domain.quantities['xmomentum'].vertex_values
+import time
+t0 = time.time()
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    #pass
+    domain.write_time()
+    u,h,z,z_b = analytic_cannal(X.flat,t)
+    linePlot(plot1,X,z,X,z_b,X,StageQ)
+    linePlot(plot2,X,u*h,X,u*h,X,XmomQ)
+    HeightQ = domain.quantities['stage'].centroid_values-domain.quantities['elevation'].centroid_values
+    u,hc,z,z_b = analytic_cannal(C,t)
+    #for k in range(N):
+    #    if hc[k] < 0.0:
+    #        hc[k] = 0.0
+    error = 1.0/(N)*sum(abs(hc-HeightQ))
+    print 'Error measured at centroids', error
+    #raw_input()         
+
+#from Gnuplot import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+#import Gnuplot  
+X = domain.vertices
+u,h,z,z_b = analytic_cannal(X.flat,domain.time)
+StageQ = domain.quantities['stage'].vertex_values
+XmomQ = domain.quantities['xmomentum'].vertex_values
+hold(False)
+plot1 = subplot(211)
+plot(X,h,X,StageQ)
+#plot1.set_ylim([4,11])
+#title('Free Surface Elevation of a Dry Dam-Break')
+xlabel('Position')
+ylabel('Stage')
+legend(('Analytical Solution', 'Numerical Solution'),
+       'upper right', shadow=True)
+plot2 = subplot(212)
+plot(X,u*h,X,XmomQ)
+#plot2.set_ylim([-1,25])
+#title('Xmomentum Profile of a Dry Dam-Break')
+xlabel('Position')
+ylabel('Xmomentum')
+show()
Index: /anuga_work/development/shallow_water_1d/parabolic_cannal_adjust.py
===================================================================
--- /anuga_work/development/shallow_water_1d/parabolic_cannal_adjust.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/parabolic_cannal_adjust.py	(revision 4959)
@@ -0,0 +1,238 @@
+import os
+from math import sqrt, pi, sin, cos
+from shallow_water_adjust import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+def newLinePlot(title='Simple Plot'):
+    import Gnuplot
+    g = Gnuplot.Gnuplot(persist=0)
+    g.title(title)
+    g('set data style linespoints') 
+    g.xlabel('x')
+    g.ylabel('y')
+    return g
+
+def linePlot(g,x1,y1,x2,y2,x3,y3):
+    import Gnuplot
+    plot1 = Gnuplot.PlotItems.Data(x1.flat,y1.flat,with="lines 2")
+    plot2 = Gnuplot.PlotItems.Data(x2.flat,y2.flat,with="lines 3")
+    plot3 = Gnuplot.PlotItems.Data(x3.flat,y3.flat,with="linespoints 1")
+    g.plot(plot1,plot2,plot3)
+
+
+def analytic_cannal(C,t):
+    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
+    
+    for i in range(N):
+        z_b[i] = z_infty*(x[i]**2/L_x**2)
+        u[i] = -A0*omega*sin(omega*t)
+        z[i] = z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))
+
+    h = z-z_b
+    return u,h,z,z_b
+
+
+#plot2 = newLinePlot("Momentum")  
+
+L_x = 2500.0     # Length of channel (m)
+N = 400         # Number of compuational cells
+cell_len = 4*L_x/N   # Origin = 0.0
+
+points = zeros(N+1,Float)
+for i in range(N+1):
+        points[i] = -2*L_x +i*cell_len
+
+domain = Domain(points)
+
+domain.order = 2 #make this unnecessary
+domain.default_order = 2
+domain.default_time_order = 1
+domain.cfl = 1.0
+domain.beta = 1.0
+#domain.limiter = "minmod_kurganov"
+domain.limiter = "vanleer"
+#domain.limiter = "vanalbada"
+#domain.limiter = "superbee"
+#domain.limiter = "minmod"
+
+def stage(x):
+
+    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
+    t=0.0
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i] = z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))
+    return y
+
+def elevation(x):
+    N = len(x)
+    z_infty = 10.0
+    z = zeros(N,Float)
+    L_x = 2500.0
+    A0 = 0.5*L_x
+    omega = sqrt(2*g*z_infty)/L_x
+    for i in range(N):
+        z[i] = z_infty*(x[i]**2/L_x**2)
+    return z
+
+def height(x):
+    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
+    t=0.0
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i] = max(z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))-z_infty*(x[i]**2/L_x**2),0.0)
+    return y
+
+    
+domain.set_quantity('stage', stage)
+domain.set_quantity('elevation',elevation)
+#domain.set_quantity('height',height)
+
+domain.set_boundary({'exterior': Reflective_boundary(domain)})
+ 
+import time
+t0 = time.time()
+#yieldstep = 50.0
+#yieldstep = 10.0
+#yieldstep = 1122.0
+
+#finaltime = 1122.0*0.999488
+finaltime=0.75*1122.0
+yieldstep = finaltime
+#yieldstep = finaltime
+#finaltime = 1122.0*4.0
+#finaltime = 2000.0
+
+plot1 = newLinePlot("Stage")
+plot2 = newLinePlot("Xmomentum")
+C = domain.centroids
+X = domain.vertices
+
+ElevationQ = domain.quantities['elevation'].vertex_values
+StageQ = domain.quantities['stage'].vertex_values
+XmomQ = domain.quantities['xmomentum'].vertex_values
+#HeightC = domain.quantities['stage'].centroid_values-domain.quantities['elevation'].centroid_values
+HeightC = domain.quantities['height'].centroid_values
+XmomC = domain.quantities['xmomentum'].centroid_values
+from util import calculate_wetted_area
+import time
+
+t0 = time.time()
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    pass
+    #print StageQ
+    #print "integral %f"%domain.quantities['height'].get_integral()
+    #if t == 0.0:
+    #     initial_integral = domain.quantities['height'].get_integral()
+    #assert(allclose(initial_integral,domain.quantities['height'].get_integral()))
+    #domain.write_time()
+    u,h,z,z_b = analytic_cannal(X.flat,t)
+    linePlot(plot1,X,z,X,z_b,X,StageQ)
+    linePlot(plot2,X,u*h,X,u*h,X,XmomQ)
+    #HeightQ = domain.quantities['stage'].centroid_values-domain.quantities['elevation'].centroid_values
+    #u,hc,z,z_b = analytic_cannal(C,t)
+    #for k in range(N):
+    #    if hc[k] < 0.0:
+    #        hc[k] = 0.0
+    #error = 1.0/(N)*sum(abs(hc-HeightQ))
+    #print 'Error measured at centroids', error
+    
+#assert(allclose(initial_integral,domain.quantities['height'].get_integral()))
+              
+u,h,z,z_b = analytic_cannal(C.flat,t)
+z_infty = 10.0       
+L_x = 2500.0
+A0 = 0.5*L_x    
+omega = sqrt(2*g*z_infty)/L_x
+x1 = A0*cos(omega*t)-L_x # left shoreline
+x2 = A0*cos(omega*t)+L_x # right shoreline
+for j in range(N):
+    if (C[j]<x1) | (C[j] > x2):
+            u[j] = 0.0
+            h[j] = 0.0
+#print h
+#print HeightC
+h_error = 1.0/(N)*sum(abs(h-HeightC))
+uh_error = 1.0/(N)*sum(abs(u*h-XmomC))
+print "h_error %.10f" %(h_error)
+print "uh_error %.10f"% (uh_error)
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot,rc
+rc('text', usetex=True)
+X = domain.vertices
+u,h,z,z_b = analytic_cannal(X.flat,domain.time)
+StageQ = domain.quantities['stage'].vertex_values
+XmomQ = domain.quantities['xmomentum'].vertex_values
+hold(False)
+plot1 = subplot(211)
+z_infty = 10.0       
+L_x = 2500.0
+A0 = 0.5*L_x    
+omega = sqrt(2*g*z_infty)/L_x
+x1 = A0*cos(omega*t)-L_x # left shoreline
+x2 = A0*cos(omega*t)+L_x # right shoreline
+for n in range(N):
+    m = 2*n
+    for j in range(2):
+        if (X.flat[m+j]<x1) | (X.flat[m+j] > x2):
+            u[m+j] = 0.0
+plot(X,z,X,StageQ,X,z_b)
+#plot1.set_ylim([4,11])
+#title('Free Surface Elevation of a Dry Dam-Break')
+#xlabel('x (m)')
+ylabel('Stage (m)')
+legend(('Analytical Solution', 'Numerical Solution'),
+       'upper right', shadow=True)
+plot2 = subplot(212)
+plot(X,u*h,X,XmomQ)
+#plot2.set_ylim([-1,25])
+#title('Xmomentum Profile of a Dry Dam-Break')
+xlabel('x (m)')
+ylabel(r'x-momentum ($m^2/s$)')
+filename = "parabolic_adjust_no_fix_"
+filename += domain.limiter
+filename += str(finaltime)
+filename += ".eps"
+print filename
+savefig(filename)
+show()
+
+"""
+parabolic_adjust_no_fix_vanleer1121.425536.eps
+h_error 0.0620113496
+uh_error 0.7105544340
+parabolic_adjust_anlty_mom_fix_vanleer1121.425536.eps
+h_error 0.4820676350
+uh_error 2.4370614797
+parabolic_adjust_mom_fix_vanleer1121.425536.eps
+h_error 0.1460889018
+uh_error 1.2977862625
+parabolic_adjust_no_fix_vanleer841.5.eps
+error 0.0613796233
+uh_error 0.4579430471
+
+"""
Index: /anuga_work/development/shallow_water_1d/parabolic_cannal_h.py
===================================================================
--- /anuga_work/development/shallow_water_1d/parabolic_cannal_h.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/parabolic_cannal_h.py	(revision 4959)
@@ -0,0 +1,162 @@
+import os
+from math import sqrt, pi, sin, cos
+from shallow_water_h import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+def newLinePlot(title='Simple Plot'):
+    import Gnuplot
+    g = Gnuplot.Gnuplot(persist=0)
+    g.title(title)
+    g('set data style linespoints') 
+    g.xlabel('x')
+    g.ylabel('y')
+    return g
+
+def linePlot(g,x1,y1,x2,y2,x3,y3):
+    import Gnuplot
+    plot1 = Gnuplot.PlotItems.Data(x1.flat,y1.flat,with="lines 2")
+    plot2 = Gnuplot.PlotItems.Data(x2.flat,y2.flat,with="lines 3")
+    plot3 = Gnuplot.PlotItems.Data(x3.flat,y3.flat,with="linespoints 1")
+    g.plot(plot1,plot2,plot3)
+
+
+def analytic_cannal(C,t):
+    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
+
+    for i in range(N):
+        z_b[i] = z_infty*(x[i]**2/L_x**2) ## or A0*cos(omega*t)\pmL_x
+        u[i] = -A0*omega*sin(omega*t)
+        z[i] = z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))
+
+    h = z-z_b
+    return u,h,z,z_b
+
+
+#plot2 = newLinePlot("Momentum")  
+
+L_x = 2500.0     # Length of channel (m)
+N = 100          # Number of compuational cells
+cell_len = 4*L_x/N   # Origin = 0.0
+
+points = zeros(N+1,Float)
+for i in range(N+1):
+        points[i] = -2*L_x +i*cell_len
+
+domain = Domain(points)
+
+domain.default_order = 2
+domain.default_time_order = 2
+domain.cfl = 1.0
+domain.beta = 1.0
+domain.flux_first = False
+
+
+
+def stage(x):
+
+    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
+    t=0.0
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i] = z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))
+    return y
+
+def elevation(x):
+    N = len(x)
+    z_infty = 10.0
+    z = zeros(N,Float)
+    L_x = 2500.0
+    A0 = 0.5*L_x
+    omega = sqrt(2*g*z_infty)/L_x
+    for i in range(N):
+        z[i] = z_infty*(x[i]**2/L_x**2)
+    return z
+
+def height(x):
+    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
+    t=0.0
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i] = max(z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x[i]/L_x-0.5*A0/(L_x)*cos(omega*t))-z_infty*(x[i]**2/L_x**2),0.0)
+        #y[i] = 12.0-z_infty*(x[i]**2/L_x**2)
+    return y
+
+    
+#domain.set_quantity('stage', stage)
+domain.set_quantity('elevation',elevation)
+domain.set_quantity('height',height)
+#print "Centroid Heights"
+#print domain.quantities['height'].centroid_values
+#print "Vertex Heights"
+#print domain.quantities['height'].vertex_values
+#print "Centroids Stage"
+#print domain.quantities['height'].centroid_values+domain.quantities['elevation'].centroid_values
+#raw_input()
+domain.set_boundary({'exterior': Reflective_boundary(domain)})
+ 
+import time
+t0 = time.time()
+#yieldstep = 50.0
+yieldstep = 1122.0
+#yieldstep = 1.0
+finaltime = 1122.0
+
+plot1 = newLinePlot("Stage")
+plot2 = newLinePlot("Xmomentum")
+C = domain.centroids
+X = domain.vertices
+HeightQ = domain.quantities['height'].vertex_values
+ElevationQ = domain.quantities['elevation'].vertex_values
+XmomQ = domain.quantities['xmomentum'].vertex_values
+
+#StageQ = domain.quantities['stage'].centroid_values       
+StageQ = ElevationQ+HeightQ
+u,h,z,z_b = analytic_cannal(X.flat,0.0)
+linePlot(plot1,X,z,X,z_b,X,StageQ)
+raw_input()
+print "integral height %f"%domain.quantities['height'].get_integral()
+print "integral xmom %f"%domain.quantities['xmomentum'].get_integral()
+C = domain.centroids
+import time
+t0 = time.time()
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+    print "integral height %f"%domain.quantities['height'].get_integral()
+    print "integral xmom %f"%domain.quantities['xmomentum'].get_integral()
+    u,h,z,z_b = analytic_cannal(X.flat,t)
+    StageQ = HeightQ+ElevationQ
+    #print "yield",HeightQ
+    linePlot(plot1,X,z,X,z_b,X,StageQ)
+    linePlot(plot2,X,u*h,X,u*h,X,XmomQ)
+    u,hc,z,z_b = analytic_cannal(C,t)
+    HeightQC = domain.quantities['height'].centroid_values
+    #print HeightQC
+    for k in range(N):
+        if hc[k] < 0.0:
+            hc[k] = 0.0
+    error = 1.0/(N)*sum(abs(hc-HeightQC))
+    print 'Error measured at centroids', error
+   # raw_input()
+    
+print 'That took %.2f seconds' %(time.time()-t0)
Index: /anuga_work/development/shallow_water_1d/quantity.py
===================================================================
--- /anuga_work/development/shallow_water_1d/quantity.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/quantity.py	(revision 4959)
@@ -0,0 +1,974 @@
+"""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):
+
+        #from domain import Domain
+        #from domain_order2 import Domain
+        from domain_t2 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.edge_values = zeros((N, 2), Float)
+        #edge values are values of the ends of each interval
+      
+        #Intialise centroid values
+        self.interpolate()
+
+    #Methods for operator overloading
+    def __len__(self):
+        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 Nx3
+
+        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']:#, 'edges']:
+            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, edges, 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', 'edges', 'unique vertices']:
+        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 == 'edges':
+        #    if (indices ==  None):
+        #        indices = range(len(self))
+        #    return take(self.edge_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:
+                triangles = self.domain.vertexlist[unique_vert_id]
+
+                #In case there are unused points
+                if triangles is None:
+                    msg = 'Unique vertex not associated with triangles'
+                    raise msg
+
+                # Go through all triangle, vertex pairs
+                # Average the values
+                sum = 0
+                for triangle_id, vertex_id in triangles:
+                    sum += self.vertex_values[triangle_id, vertex_id]
+                vert_values.append(sum/len(triangles))
+            return Numeric.array(vert_values)
+        else:
+            if (indices ==  None):
+                indices = range(len(self))
+            return take(self.vertex_values,indices)
+
+    #Method for outputting model results
+    #FIXME: Split up into geometric and numeric stuff.
+    #FIXME: Geometric (X,Y,V) should live in mesh.py
+    #FIXME: STill remember to move XY to mesh
+    def get_vertex_values(self,
+                          #xy=True,
+                          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 and Y.
+
+        The connectivity is represented as an integer array, V, of dimension
+        M x 3, where M is the number of volumes. Each row has three indices
+        into the X, Y, A arrays defining the triangle.
+
+        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 and vertices 2
+
+
+        Calling convention
+        if xy is True:
+           X,Y,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 xy is True:
+            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 xy is True:
+            if x is True:
+                C = self.domain.get_vertex_coordinates()
+
+                X = C[:,0:6:2].copy()
+                Y = C[:,1:6:2].copy()
+
+                return X.flat, Y.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
+
+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)
+
+        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 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]
+
+        #print "pre update",self.centroid_values
+        #print "timestep",timestep
+        #print min(self.domain.areas)
+        #print "explicit_update", self.explicit_update
+
+        #Explicit updates
+        self.centroid_values += timestep*self.explicit_update
+
+        #print "post update",self.centroid_values
+        
+        #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.
+        """
+
+
+        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
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+
+                #Gradient
+                G[k] = (q1 - q0)/(x1 - x0)
+
+            elif k == N-1:
+
+                #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)
+
+            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.
+        """
+
+        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
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+
+                #Gradient
+                G[k] = (q1 - q0)/(x1 - x0)
+
+            elif k == N-1:
+
+                #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 == "steve_minmod":
+            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
+        
+        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])
+            elif n1 < 0:
+                phi = (qc[k] - qc[k-1])/(C[k] - C[k-1])
+            elif (self.domain.wet_nodes[k,0] == 2) & (self.domain.wet_nodes[k,1] == 2):
+                phi = 0.0
+            else:
+                if limiter == "minmod":
+                    phi = minmod(beta_p[k],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 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))
+
+
+
+
+
+if __name__ == "__main__":
+    #from domain import Domain
+    from shallow_water_1d 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 = Conserved_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.beta = 1.0
+    Q1.extrapolate_second_order()
+    Q1.limit_minmod()
+
+    g1 = newLinePlot('plot 1')
+    linePlot(g1,Xc,Qc)
+
+    points2 = arange(10)
+    D2 = Domain(points2)
+
+    Q2 = Conserved_quantity(D2)
+    Q2.set_values(fun,'vertices')
+    Xc = Q2.domain.vertices
+    Qc = Q2.vertex_values
+
+    g2 = newLinePlot('plot 2')
+    linePlot(g2,Xc,Qc)
+
+
+    
+    Q2.extrapolate_second_order()
+    Q2.limit_minmod()
+    Xc = Q2.domain.vertices
+    Qc = Q2.vertex_values
+
+    print Q2.centroid_values
+    print Qc
+    raw_input('press_return')
+    
+    g3 = newLinePlot('plot 3')
+    linePlot(g3,Xc,Qc)
+    raw_input('press return')
+
+
+    for i in range(10):
+        fun = FunClass(i/10.0)
+        Q2.set_values(fun,'vertices')
+        Qc = Q2.vertex_values
+        linePlot(g3,Xc,Qc)
+
+    raw_input('press return')
+
Index: /anuga_work/development/shallow_water_1d/quantity_adjust.py
===================================================================
--- /anuga_work/development/shallow_water_1d/quantity_adjust.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/quantity_adjust.py	(revision 4959)
@@ -0,0 +1,975 @@
+"""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):
+
+        #from domain import Domain
+        #from domain_adjust import Domain
+        from domain_t2 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.edge_values = zeros((N, 2), Float)
+        #edge values are values of the ends of each interval
+      
+        #Intialise centroid values
+        self.interpolate()
+
+    #Methods for operator overloading
+    def __len__(self):
+        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
+
+    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 Nx3
+
+        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']:#, 'edges']:
+            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, edges, 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', 'edges', 'unique vertices']:
+        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 == 'edges':
+        #    if (indices ==  None):
+        #        indices = range(len(self))
+        #    return take(self.edge_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:
+                triangles = self.domain.vertexlist[unique_vert_id]
+
+                #In case there are unused points
+                if triangles is None:
+                    msg = 'Unique vertex not associated with triangles'
+                    raise msg
+
+                # Go through all triangle, vertex pairs
+                # Average the values
+                sum = 0
+                for triangle_id, vertex_id in triangles:
+                    sum += self.vertex_values[triangle_id, vertex_id]
+                vert_values.append(sum/len(triangles))
+            return Numeric.array(vert_values)
+        else:
+            if (indices ==  None):
+                indices = range(len(self))
+            return take(self.vertex_values,indices)
+
+    #Method for outputting model results
+    #FIXME: Split up into geometric and numeric stuff.
+    #FIXME: Geometric (X,Y,V) should live in mesh.py
+    #FIXME: STill remember to move XY to mesh
+    def get_vertex_values(self,
+                          #xy=True,
+                          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 and Y.
+
+        The connectivity is represented as an integer array, V, of dimension
+        M x 3, where M is the number of volumes. Each row has three indices
+        into the X, Y, A arrays defining the triangle.
+
+        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 and vertices 2
+
+
+        Calling convention
+        if xy is True:
+           X,Y,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 xy is True:
+            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 xy is True:
+            if x is True:
+                C = self.domain.get_vertex_coordinates()
+
+                X = C[:,0:6:2].copy()
+                Y = C[:,1:6:2].copy()
+
+                return X.flat, Y.flat, A, V
+            else:
+                return A, V
+
+    def get_integral(self):
+        """Compute the integral of quantity across entire domain
+        """
+        integral = 0
+        xv = self.domain.vertices
+        for k in range(self.domain.number_of_elements):
+            area = xv[k,1]-xv[k,0]
+            #area = self.domain.areas[k]
+            qc = self.centroid_values[k]
+            integral += qc*area
+
+        return integral
+
+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)
+
+        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 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]
+
+        #print "pre update",self.centroid_values
+        #print "timestep",timestep
+        #print min(self.domain.areas)
+        #print "explicit_update", self.explicit_update
+
+        #Explicit updates
+        self.centroid_values += timestep*self.explicit_update
+
+        #print "post update",self.centroid_values
+        
+        #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.
+        """
+
+
+        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
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+
+                #Gradient
+                G[k] = (q1 - q0)/(x1 - x0)
+
+            elif k == N-1:
+
+                #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)
+
+            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.
+        """
+
+        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
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+
+                #Gradient
+                G[k] = (q1 - q0)/(x1 - x0)
+
+            elif k == N-1:
+
+                #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.
+        """
+
+        #self.limit_range()
+        self.limit_minmod()
+        
+##         #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)
+
+    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
+            #if (self.domain.wet_nodes[k,0] != 2) & (self.domain.wet_nodes[k,1] != 2):
+            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
+        
+        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])
+            elif n1 < 0:
+                phi = (qc[k] - qc[k-1])/(C[k] - C[k-1])
+            elif (self.domain.wet_nodes[k,0] == 2) & (self.domain.wet_nodes[k,1] == 2):
+                phi = 0.0
+                print "cell",k
+            else:
+                if limiter == "minmod":
+                    phi = minmod(beta_p[k],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 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))
+
+
+
+
+
+if __name__ == "__main__":
+    #from domain import Domain
+    from domain_t2 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 = Conserved_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.beta = 1.0
+    Q1.extrapolate_second_order()
+    Q1.limit()
+
+    g1 = newLinePlot('plot 1')
+    linePlot(g1,Xc,Qc)
+
+    points2 = arange(10)
+    D2 = Domain(points2)
+
+    Q2 = Conserved_quantity(D2)
+    Q2.set_values(fun,'vertices')
+    Xc = Q2.domain.vertices
+    Qc = Q2.vertex_values
+
+    g2 = newLinePlot('plot 2')
+    linePlot(g2,Xc,Qc)
+
+
+    
+    Q2.extrapolate_second_order()
+    Q2.limit()
+    Xc = Q2.domain.vertices
+    Qc = Q2.vertex_values
+
+    print Q2.centroid_values
+    print Qc
+    raw_input('press_return')
+    
+    g3 = newLinePlot('plot 3')
+    linePlot(g3,Xc,Qc)
+    raw_input('press return')
+
+
+    for i in range(10):
+        fun = FunClass(i/10.0)
+        Q2.set_values(fun,'vertices')
+        Qc = Q2.vertex_values
+        linePlot(g3,Xc,Qc)
+
+    raw_input('press return')
+
Index: /anuga_work/development/shallow_water_1d/quantity_domain.py
===================================================================
--- /anuga_work/development/shallow_water_1d/quantity_domain.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/quantity_domain.py	(revision 4959)
@@ -0,0 +1,561 @@
+"""Class Quantity - Implements values at each triangular element
+
+To create:
+
+   Quantity(domain, vertex_values)
+
+   domain: Associated domain structure. Required.
+
+   vertex_values: N x 3 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):
+
+        from domain_t2 import Domain
+        from Numeric import array, zeros, Float
+
+        if vertex_values is None:
+            N = domain.number_of_elements
+            self.vertex_values = zeros((N, 2), Float)
+        else:
+            self.vertex_values = array(vertex_values).astype(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)
+
+        #Intialise centroid values
+        self.interpolate()
+
+
+
+    #Methods for operator overloading
+    def __len__(self):
+        return self.centroid_values.shape[0]
+
+
+    def __neg__(self):
+        """Negate all values in this quantity giving meaning to the
+        expression -Q where Q is an instance of class Quantity
+        """
+
+        Q = Quantity(self.domain)
+        Q.set_values(-self.vertex_values)
+        return Q
+
+
+    def __add__(self, other):
+        """Add to self anything that could populate a quantity
+
+        E.g other can be a constant, an array, a function, another quantity
+        (except for a filename or points, attributes (for now))
+        - see set_values for details
+        """
+
+        Q = Quantity(self.domain)
+        Q.set_values(other)
+
+        result = Quantity(self.domain)
+        result.set_values(self.vertex_values + Q.vertex_values)
+        return result
+
+    def __radd__(self, other):
+        """Handle cases like 7+Q, where Q is an instance of class Quantity
+        """
+        return self + other
+
+
+    def __sub__(self, other):
+        return self + -other  #Invoke __neg__
+
+    def __mul__(self, other):
+        """Multiply self with anything that could populate a quantity
+
+        E.g other can be a constant, an array, a function, another quantity
+        (except for a filename or points, attributes (for now))
+        - see set_values for details
+
+        Note that if two quantitites q1 and q2 are multiplied,
+        vertex values are multiplied entry by entry
+        while centroid and edge values are re-interpolated.
+        Hence they won't be the product of centroid or edge values
+        from q1 and q2.
+        """
+
+        Q = Quantity(self.domain)
+        Q.set_values(other)
+
+        result = Quantity(self.domain)
+        result.set_values(self.vertex_values * Q.vertex_values)
+        return result
+
+    def __rmul__(self, other):
+        """Handle cases like 3*Q, where Q is an instance of class Quantity
+        """
+        return self * other
+
+    def __pow__(self, other):
+        """Raise quantity to (numerical) power
+
+        As with __mul__ vertex values are processed entry by entry
+        while centroid and edge values are re-interpolated.
+
+        Example using __pow__:
+          Q = (Q1**2 + Q2**2)**0.5
+
+        """
+
+        result = Quantity(self.domain)
+        result.set_values(self.vertex_values**other)
+        return result
+
+
+
+    def interpolate(self):
+        """Compute interpolated values at edges and 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 Nx3
+
+        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 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
+        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 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 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
+
+
+
+
+class Conserved_quantity(Quantity):
+    """Class conserved quantity adds to Quantity:
+
+    boundary values, storage and method for updating, and
+    methods for (second order) extrapolation from centroid to vertices inluding
+    gradients and limiters
+    """
+
+    def __init__(self, domain, vertex_values=None):
+        Quantity.__init__(self, domain, vertex_values)
+
+        from Numeric import zeros, Float
+
+        #Allocate space for boundary values
+        L = len(domain.boundary)
+        self.boundary_values = zeros(L, Float)
+
+        #Allocate space for updates of conserved quantities by
+        #flux calculations and forcing functions
+
+        N = domain.number_of_elements
+        self.gradients = zeros(N, Float)
+        self.explicit_update = zeros(N, Float )
+        self.semi_implicit_update = zeros(N, Float )
+
+
+    def update(self, timestep):
+        #Call correct module function
+        #(either from this module or C-extension)
+        return update(self, timestep)
+
+
+    def compute_gradients(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        return compute_gradients(self)
+
+
+    def limit(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        limit(self)
+
+
+    def extrapolate_second_order(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        extrapolate_second_order(self)
+
+
+def update(quantity, timestep):
+    """Update centroid values based on values stored in
+    explicit_update and semi_implicit_update as well as given timestep
+
+    Function implementing forcing terms must take on argument
+    which is the domain and they must update either explicit
+    or implicit updates, e,g,:
+
+    def gravity(domain):
+        ....
+        domain.quantities['xmomentum'].explicit_update = ...
+        domain.quantities['ymomentum'].explicit_update = ...
+
+
+
+    Explicit terms must have the form
+
+        G(q, t)
+
+    and explicit scheme is
+
+       q^{(n+1}) = q^{(n)} + delta_t G(q^{n}, n delta_t)
+
+
+    Semi implicit forcing terms are assumed to have the form
+
+       G(q, t) = H(q, t) q
+
+    and the semi implicit scheme will then be
+
+      q^{(n+1}) = q^{(n)} + delta_t H(q^{n}, n delta_t) q^{(n+1})
+
+
+    """
+
+    from Numeric import sum, equal, ones, exp, Float
+
+    N = quantity.centroid_values.shape[0]
+
+
+    #Divide H by conserved quantity to obtain G (see docstring above)
+
+
+    for k in range(N):
+        x = quantity.centroid_values[k]
+        if x == 0.0:
+            #FIXME: Is this right
+            quantity.semi_implicit_update[k] = 0.0
+        else:
+            quantity.semi_implicit_update[k] /= x
+
+
+    #Semi implicit updates
+    denominator = ones(N, Float)-timestep*quantity.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
+        quantity.centroid_values /= denominator
+
+#    quantity.centroid_values = exp(timestep*quantity.semi_implicit_update)*quantity.centroid_values
+
+
+    #Explicit updates
+    quantity.centroid_values += timestep*quantity.explicit_update
+
+def extrapolate_second_order(quantity):
+    """Extrapolate conserved quantities from centroid to
+    vertices for each volume using
+    second order scheme.
+    """
+
+    quantity.compute_gradients()
+    a = quantity.gradients
+
+    X = quantity.domain.vertices
+    qc = quantity.centroid_values
+    qv = quantity.vertex_values
+
+    #Check each triangle
+    for k in range(quantity.domain.number_of_elements):
+        #Centroid coordinates
+        x = quantity.domain.centroids[k]
+
+        #vertex coordinates
+        x0, x1 = X[k,:]
+
+        #Extrapolate
+        qv[k,0] = qc[k] + a[k]*(x0-x)
+        qv[k,1] = qc[k] + a[k]*(x1-x)
+    
+    quantity.limit()
+
+def compute_gradients(self):
+        """Compute gradients of piecewise linear function defined by centroids of
+        neighbouring volumes.
+        """
+
+
+        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
+
+                q0 = Q[k0]
+                q1 = Q[k1]
+
+                x0 = X[k0] #V0 centroid
+                x1 = X[k1] #V1 centroid
+
+                #Gradient
+                G[k] = (q1 - q0)/(x1 - x0)
+
+            elif k == N-1:
+
+                #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)
+
+            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 limit(quantity):
+    """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 = quantity.domain.number_of_elements
+
+    beta = quantity.domain.beta
+
+    qc = quantity.centroid_values
+    qv = quantity.vertex_values
+
+    #Find min and max of this and neighbour's centroid values
+    qmax = zeros(qc.shape, Float)
+    qmin = zeros(qc.shape, Float)
+
+    for k in range(N):
+        qmax[k] = qmin[k] = qc[k]
+        for i in range(2):
+            n = quantity.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]
Index: /anuga_work/development/shallow_water_1d/shallow_water_1d.py
===================================================================
--- /anuga_work/development/shallow_water_1d/shallow_water_1d.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/shallow_water_1d.py	(revision 4959)
@@ -0,0 +1,1324 @@
+"""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 *
+#from domain_order2 import *
+from domain_t2 import *
+Generic_Domain = Domain #Rename
+
+#Shallow water domain
+class Domain(Generic_Domain):
+
+    def __init__(self, coordinates, boundary = None, tagged_elements = None,
+                 geo_reference = None):
+
+        conserved_quantities = ['stage', 'xmomentum']
+        other_quantities = ['elevation', 'friction']
+        Generic_Domain.__init__(self, coordinates, boundary,
+                                conserved_quantities, other_quantities,
+                                tagged_elements, geo_reference)
+        
+        from config import minimum_allowed_height, g
+        self.minimum_allowed_height = minimum_allowed_height
+        self.g = g
+
+        #forcing terms not included in 1d domain ?WHy?
+        self.forcing_terms.append(gravity)
+        #self.forcing_terms.append(manning_friction)
+        #print "\nI have Removed forcing terms line 64 1dsw"
+
+        #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']
+
+
+    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
+
+    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(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,
+               skip_initial_step = False):
+        """Specialisation of basic evolve method from parent class
+        """
+
+        #Call check integrity here rather than from user scripts
+        #self.check_integrity()
+
+        #msg = 'Parameter beta_h must be in the interval [0, 1)'
+        #assert 0 <= self.beta_h < 1.0, msg
+        #msg = 'Parameter beta_w must be in the interval [0, 1)'
+        #assert 0 <= self.beta_w < 1.0, msg
+
+
+        #Initial update of vertex and edge values before any storage
+        #and or visualisation
+        
+        self.distribute_to_vertices_and_edges()
+        
+        #Initialise real time viz if requested
+        #if self.visualise is True and self.time == 0.0:
+        #    if self.visualiser is None:
+        #        self.initialise_visualiser()
+        #
+        #    self.visualiser.update_timer()
+        #    self.visualiser.setup_all()
+
+        #Store model data, e.g. for visualisation
+        #if self.store is True and self.time == 0.0:
+        #    self.initialise_storage()
+        #    #print 'Storing results in ' + self.writer.filename
+        #else:
+        #    pass
+        #    #print 'Results will not be stored.'
+        #    #print 'To store results set domain.store = True'
+        #    #FIXME: Diagnostic output should be controlled by
+        #    # a 'verbose' flag living in domain (or in a parent class)
+
+        #Call basic machinery from parent class
+        for t in Generic_Domain.evolve(self, yieldstep, finaltime,
+                                       skip_initial_step):
+            #Real time viz
+        #    if self.visualise is True:
+        #        self.visualiser.update_all()
+        #        self.visualiser.update_timer()
+
+
+            #Store model data, e.g. for subsequent visualisation
+        #    if self.store is True:
+        #        self.store_timestep(self.quantities_to_be_stored)
+
+            #FIXME: Could maybe be taken from specified list
+            #of 'store every step' quantities
+
+            #Pass control on to outer loop for more specific actions
+            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
+    from math import sqrt
+    from Numeric import array
+
+    #print 'ql',ql
+
+    #Align momentums with x-axis
+    #q_left  = rotate(ql, normal, direction = 1)
+    #q_right = rotate(qr, normal, direction = 1)
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+
+    #z = (zl+zr)/2 #Take average of field values
+    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
+
+
+    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
+
+    #vh_left  = q_left[2]
+    #vh_right = q_right[2]
+
+    #print h_right
+    #print u_right
+    #print h_left
+    #print u_right
+
+    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**2])
+    #flux_right = array([u_right*h_right,
+    #                    u_right*uh_right + 0.5*g*h_right**2])
+    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 flux_function_split(normal, ql, qr, zl, zr):
+    from config import g, epsilon
+    from math import sqrt
+    from Numeric import array
+
+    #print 'ql',ql
+
+    #Align momentums with x-axis
+    #q_left  = rotate(ql, normal, direction = 1)
+    #q_right = rotate(qr, normal, direction = 1)
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+
+    #z = (zl+zr)/2 #Take average of field values
+    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
+
+
+    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
+
+    #vh_left  = q_left[2]
+    #vh_right = q_right[2]
+
+    #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)
+    s_max = max(u_left, u_right, 0)
+    
+    #Minimal wave speed
+    #s_min = min(u_left-soundspeed_left, u_right-soundspeed_right, 0)
+    s_min = min(u_left, u_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])
+    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_edges[k,i]
+                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]
+
+            if domain.split == False:
+                edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            elif domain.split == True:
+                edgeflux, max_speed = flux_function_split(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
+
+def compute_fluxes(domain):
+    """Compute all fluxes and the timestep suitable for all volumes
+    in domain.
+
+    Compute total flux for each conserved quantity using "flux_function"
+
+    Fluxes across each edge are scaled by edgelengths and summed up
+    Resulting flux is then scaled by area and stored in
+    explicit_update for each of the three conserved quantities
+    stage, xmomentum and ymomentum
+
+    The maximal allowable speed computed by the flux_function for each volume
+    is converted to a timestep that must not be exceeded. The minimum of
+    those is computed as the next overall timestep.
+
+    Post conditions:
+      domain.explicit_update is reset to computed flux values
+      domain.timestep is set to the largest step satisfying all volumes.
+    """
+
+    import sys
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+#    Ymom = domain.quantities['ymomentum']
+    Bed = domain.quantities['elevation']
+
+    #Arrays
+    #stage = Stage.edge_values
+    #xmom =  Xmom.edge_values
+ #   ymom =  Ymom.edge_values
+    #bed =   Bed.edge_values
+    
+    stage = Stage.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+    
+    #print 'stage edge values', stage
+    #print 'xmom edge values', xmom
+    #print 'bed values', bed
+
+    stage_bdry = Stage.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+    #print 'stage_bdry',stage_bdry
+    #print 'xmom_bdry', xmom_bdry
+#    ymom_bdry =  Ymom.boundary_values
+
+#    flux = zeros(3, Float) #Work array for summing up fluxes
+    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(3):
+        for i in range(2):
+            #Quantities inside volume facing neighbour i
+            #ql[0] = stage[k, i]
+            #ql[1] = xmom[k, 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_edges[k,i]
+                m = domain.neighbour_vertices[k,i]
+                #qr = [stage[n, m], xmom[n, m], ymom[n, m]]
+                qr[0] = stage[n, m]
+                qr[1] =  xmom[n, m]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+        
+            #Flux computation using provided function
+            #edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            #print 'ql',ql
+            #print 'qr',qr
+            
+
+            if domain.split == False:
+                edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            elif domain.split == True:
+                edgeflux, max_speed = flux_function_split(normal, ql, qr, zl, zr)
+            #print 'edgeflux', edgeflux
+
+            # THIS IS THE LINE TO DEAL WITH LEFT AND RIGHT FLUXES
+            # flux = edgefluxleft - edgefluxright
+            flux -= edgeflux #* domain.edgelengths[k,i]
+            #Update optimal_timestep
+            try:
+                #timestep = min(timestep, 0.5*domain.radii[k]/max_speed)
+                timestep = min(timestep, domain.cfl*0.5*domain.areas[k]/max_speed)
+            except ZeroDivisionError:
+                pass
+
+        #Normalise by area and store for when all conserved
+        #quantities get updated
+        flux /= domain.areas[k]
+
+        Stage.explicit_update[k] = flux[0]
+        Xmom.explicit_update[k] = flux[1]
+        #Ymom.explicit_update[k] = flux[2]
+        #print "flux cell",k,flux[0]
+
+    domain.timestep = timestep
+    #print domain.quantities['stage'].centroid_values
+
+####################################
+
+# 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)
+    
+
+    #Extrapolate all conserved quantities
+    #if optimised_gradient_limiter:
+    #    #MH090605 if second order,
+    #    #perform the extrapolation and limiting on
+    #    #all of the conserved quantities
+
+    #    if (domain.order == 1):
+    #        for name in domain.conserved_quantities:
+    #            Q = domain.quantities[name]
+    #            Q.extrapolate_first_order()
+    #    elif domain.order == 2:
+    #        domain.extrapolate_second_order_sw()
+    #    else:
+    #        raise 'Unknown order'
+    #else:
+        #old code:
+
+    for name in domain.conserved_quantities:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            #print "add extrapolate second order to shallow water"
+            #if name != 'height':
+            Q.extrapolate_second_order()
+            #Q.limit()
+        else:
+            raise 'Unknown order'
+
+    #Take bed elevation into account when water heights are small
+    #balance_deep_and_shallow(domain)
+    #protect_against_infinitesimal_and_negative_heights(domain)
+
+#Compute edge values by interpolation
+    #for name in domain.conserved_quantities:
+    #    Q = domain.quantities[name]
+    #    Q.interpolate_from_vertices_to_edges()    
+    
+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
+#    ymomc = domain.quantities['ymomentum'].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
+            
+        #N = domain.number_of_elements
+        #if (k == 0) | (k==N-1):
+        #    wc[k] = zc[k] # Contain 'lost mass' error
+        #    wv[k,0] = zv[k,0]
+        #    wv[k,1] = zv[k,1]
+    
+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(3):
+        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(3):
+    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(3):
+        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(3):
+        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
+#            ymomc = domain.quantities['ymomentum'].centroid_values
+
+            #Momentums at vertices
+            xmomv = domain.quantities['xmomentum'].vertex_values
+#           ymomv = domain.quantities['ymomentum'].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,:]
+#            ymomv[k,:] = (1-alpha)*ymomc[k] + alpha*ymomv[k,:]
+
+
+###############################################
+#Boundaries - specific to the shallow water wave equation
+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.stage   = domain.quantities['stage'].edge_values
+        #self.xmom    = domain.quantities['xmomentum'].edge_values
+        #self.ymom    = domain.quantities['ymomentum'].edge_values
+        self.normals = domain.normals
+        self.stage   = domain.quantities['stage'].vertex_values
+        self.xmom    = domain.quantities['xmomentum'].vertex_values
+
+        from Numeric import zeros, Float
+        #self.conserved_quantities = zeros(3, Float)
+        self.conserved_quantities = zeros(2, 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.conserved_quantities
+        q[0] = self.stage[vol_id, edge_id]
+        q[1] = self.xmom[vol_id, edge_id]
+        #q[2] = self.ymom[vol_id, edge_id]
+        #normal = self.normals[vol_id, 2*edge_id:2*edge_id+2]
+        #normal = self.normals[vol_id, 2*edge_id:2*edge_id+1]
+        normal = self.normals[vol_id,edge_id]
+
+        #r = rotate(q, normal, direction = 1)
+        #r[1] = -r[1]
+        #q = rotate(r, normal, direction = -1)
+        r = q
+        r[1] = normal*r[1]
+        r[1] = -r[1]
+        r[1] = normal*r[1]
+        q = r
+        #For start interval there is no outward momentum so do not need to
+        #reverse direction in this case
+
+        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
+
+
+#########################
+#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
+#    ymom = domain.quantities['ymomentum'].explicit_update
+
+    Stage = domain.quantities['stage']
+    Elevation = domain.quantities['elevation']
+    #h = Stage.edge_values - Elevation.edge_values
+    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,:] )/3
+        avg_h = sum( h[k,:] )/2
+
+        #Compute bed slope
+        #x0, y0, x1, y1, x2, y2 = x[k,:]
+        x0, x1 = x[k,:]
+        #z0, z1, z2 = v[k,:]
+        b0, b1 = b[k,:]
+
+        w0, w1 = w[k,:]
+        wx = gradient(x0, x1, w0, w1)
+
+        #zx, zy = gradient(x0, y0, x1, y1, x2, y2, z0, z1, z2)
+        bx = gradient(x0, x1, b0, b1)
+        
+        #Update momentum (explicit update is reset to source values)
+        if domain.split == False:
+            xmom[k] += -g*bx*avg_h
+            #xmom[k] = -g*bx*avg_h
+            #stage[k] = 0.0
+        elif domain.split == True:
+            xmom[k] += -g*wx*avg_h
+            #xmom[k] = -g*wx*avg_h
+        #ymom[k] += -g*zy*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
+    #vh = domain.quantities['ymomentum'].centroid_values
+    eta = domain.quantities['friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+    #ymom_update = domain.quantities['ymomentum'].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 * sqrt((uh[k]**2 + vh[k]**2))
+                S = -g * eta[k]**2 * uh[k]
+            	S /= h[k]**(7.0/3)
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
+            	#ymom_update[k] += S*vh[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
+#    vh = domain.quantities['ymomentum'].centroid_values
+    tau = domain.quantities['linear_friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+#    ymom_update = domain.quantities['ymomentum'].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 = 3
+        N = 2
+        #x = ones(3, Float)
+        #y = ones(3, Float)
+        x = ones(2, Float)
+        #y = ones(2, Float)
+        
+        try:
+            #q = f(1.0, x=x, y=y)
+            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,y: vector_function(t,x=x,y=y)[0]
+            #phi = lambda t,x,y: vector_function(t,x=x,y=y)[1]
+            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
+        #ymom_update = domain.quantities['ymomentum'].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[:,0], xc[:,1])
+            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[:,0], xc[:,1])
+            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 * sqrt(u**2 + v**2)
+        S = const * u
+        xmom_update[k] += S*u
+        #ymom_update[k] += S*v
Index: /anuga_work/development/shallow_water_1d/shallow_water_adjust.py
===================================================================
--- /anuga_work/development/shallow_water_1d/shallow_water_adjust.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/shallow_water_adjust.py	(revision 4959)
@@ -0,0 +1,1697 @@
+"""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 *
+from domain_adjust import *
+Generic_Domain = Domain #Rename
+
+#Shallow water domain
+class Domain(Generic_Domain):
+
+    def __init__(self, coordinates, boundary = None, tagged_elements = None,
+                 geo_reference = None):
+
+        conserved_quantities = ['stage', 'xmomentum','height']
+        other_quantities = ['elevation', 'friction']#, 'height']
+        Generic_Domain.__init__(self, coordinates, boundary,
+                                conserved_quantities, other_quantities,
+                                tagged_elements, geo_reference)
+        
+        from config import minimum_allowed_height, g
+        self.minimum_allowed_height = minimum_allowed_height
+        self.g = g
+
+        #forcing terms not included in 1d domain ?WHy?
+        self.forcing_terms.append(gravity)
+        #self.forcing_terms.append(manning_friction)
+        #print "\nI have Removed forcing terms line 64 1dsw"
+
+        #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']
+
+
+    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
+
+    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(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 distribute_stage_to_height(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        distribute_stage_to_height(self)
+        
+
+    def classify_wet_dry_cells(self):
+        #Call correct module function
+        classify_wet_dry_cells(self)
+
+    def set_initial_conserved_quanitites(self):
+        #Call correct module function
+        set_initial_conserved_quanitites(self)
+    
+        
+    def adjust_partially_submerged_cells(self):
+        #Call correct module function
+        adjust_partially_submerged_cells(self)
+
+    def pre_update(self):
+        #Call correct module function
+        pre_update(self)
+
+    def post_update(self):
+        #Call correct module function
+        post_update(self)
+        
+    def evolve(self, yieldstep = None, finaltime = None,
+               skip_initial_step = False):
+        """Specialisation of basic evolve method from parent class
+        """
+
+        #Call check integrity here rather than from user scripts
+        #self.check_integrity()
+
+        #msg = 'Parameter beta_h must be in the interval [0, 1)'
+        #assert 0 <= self.beta_h < 1.0, msg
+        #msg = 'Parameter beta_w must be in the interval [0, 1)'
+        #assert 0 <= self.beta_w < 1.0, msg
+
+
+        #Initial update of vertex and edge values before any storage
+        #and or visualisation
+
+        print "will not work if stage not set at vertices"
+        self.set_initial_conserved_quanitites()
+        
+        self.distribute_to_vertices_and_edges()
+
+        self.distribute_stage_to_height()
+        
+        #Initialise real time viz if requested
+        #if self.visualise is True and self.time == 0.0:
+        #    if self.visualiser is None:
+        #        self.initialise_visualiser()
+        #
+        #    self.visualiser.update_timer()
+        #    self.visualiser.setup_all()
+
+        #Store model data, e.g. for visualisation
+        #if self.store is True and self.time == 0.0:
+        #    self.initialise_storage()
+        #    #print 'Storing results in ' + self.writer.filename
+        #else:
+        #    pass
+        #    #print 'Results will not be stored.'
+        #    #print 'To store results set domain.store = True'
+        #    #FIXME: Diagnostic output should be controlled by
+        #    # a 'verbose' flag living in domain (or in a parent class)
+
+        #Call basic machinery from parent class
+        for t in Generic_Domain.evolve(self, yieldstep, finaltime,
+                                       skip_initial_step):
+            #Real time viz
+        #    if self.visualise is True:
+        #        self.visualiser.update_all()
+        #        self.visualiser.update_timer()
+
+
+            #Store model data, e.g. for subsequent visualisation
+        #    if self.store is True:
+        #        self.store_timestep(self.quantities_to_be_stored)
+
+            #FIXME: Could maybe be taken from specified list
+            #of 'store every step' quantities
+
+            #Pass control on to outer loop for more specific actions
+            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
+    from math import sqrt
+    from Numeric import array
+
+    #print 'ql',ql
+    #print 'qr', qr
+
+    #Align momentums with x-axis
+    #q_left  = rotate(ql, normal, direction = 1)
+    #q_right = rotate(qr, normal, direction = 1)
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+
+    #z = (zl+zr)/2 #Take average of field values
+    z = 0.5*(zl+zr) #Take average of field values
+
+    h_left  = q_left[0]   #w=h+z
+    w_left  = h_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
+
+
+    h_right  = q_right[0]  #w=h+z
+    w_right  = h_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
+
+    #vh_left  = q_left[2]
+    #vh_right = q_right[2]
+
+    #print "uright %f ulef %f"%(u_right,u_left)
+
+    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**2])
+    #flux_right = array([u_right*h_right,
+    #                    u_right*uh_right + 0.5*g*h_right**2])
+    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 flux_function_split(normal, ql, qr, zl, zr):
+    from config import g, epsilon
+    from math import sqrt
+    from Numeric import array
+
+    #print 'ql',ql
+
+    #Align momentums with x-axis
+    #q_left  = rotate(ql, normal, direction = 1)
+    #q_right = rotate(qr, normal, direction = 1)
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+
+    #z = (zl+zr)/2 #Take average of field values
+    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
+
+
+    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
+
+    #vh_left  = q_left[2]
+    #vh_right = q_right[2]
+
+    #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)
+    s_max = max(u_left, u_right, 0)
+    
+    #Minimal wave speed
+    #s_min = min(u_left-soundspeed_left, u_right-soundspeed_right, 0)
+    s_min = min(u_left, u_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])
+    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_edges[k,i]
+                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]
+
+            if domain.split == False:
+                edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            elif domain.split == True:
+                edgeflux, max_speed = flux_function_split(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
+
+def compute_fluxes(domain):
+    """Compute all fluxes and the timestep suitable for all volumes
+    in domain.
+
+    Compute total flux for each conserved quantity using "flux_function"
+
+    Fluxes across each edge are scaled by edgelengths and summed up
+    Resulting flux is then scaled by area and stored in
+    explicit_update for each of the three conserved quantities
+    stage, xmomentum and ymomentum
+
+    The maximal allowable speed computed by the flux_function for each volume
+    is converted to a timestep that must not be exceeded. The minimum of
+    those is computed as the next overall timestep.
+
+    Post conditions:
+      domain.explicit_update is reset to computed flux values
+      domain.timestep is set to the largest step satisfying all volumes.
+    """
+
+    #print "in compute_fluxes"
+
+    import sys
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    #Stage = domain.quantities['stage']
+    Height = domain.quantities['height']
+    Xmom = domain.quantities['xmomentum']
+#    Ymom = domain.quantities['ymomentum']
+    Bed = domain.quantities['elevation']
+
+    #Arrays
+    #stage = Stage.edge_values
+    #xmom =  Xmom.edge_values
+ #   ymom =  Ymom.edge_values
+    #bed =   Bed.edge_values
+    
+    #stage = Stage.vertex_values
+    height = Height.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+    
+    #print 'stage edge values', stage
+    #print 'xmom edge values', xmom
+    #print 'bed values', bed
+
+    #stage_bdry = Stage.boundary_values
+    height_bdry = Height.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+    #print 'stage_bdry',stage_bdry
+    #print 'xmom_bdry', xmom_bdry
+#    ymom_bdry =  Ymom.boundary_values
+
+#    flux = zeros(3, Float) #Work array for summing up fluxes
+    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(3):
+        for i in range(2):
+            #Quantities inside volume facing neighbour i
+            #ql = [stage[k, i], xmom[k, i]]
+            ql = [height[k, i], xmom[k, i]]
+            zl = bed[k, i]
+            #print "cell",k,"left state",ql[0]
+
+            #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[0] = height_bdry[m]
+                qr[1] = xmom_bdry[m]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                #m = domain.neighbour_edges[k,i]
+                m = domain.neighbour_vertices[k,i]
+                #qr = [stage[n, m], xmom[n, m], ymom[n, m]]
+                #qr[0] = stage[n, m]
+                qr[0] = height[n, m]
+                qr[1] =  xmom[n, m]
+                zr = bed[n, m]
+                #print "cell",k,"right state",qr[0]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+        
+            #Flux computation using provided function
+            #edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            #print 'ql',ql
+            #print 'qr',qr
+            
+
+            if domain.split == False:
+                edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+                #print edgeflux
+            elif domain.split == True:
+                edgeflux, max_speed = flux_function_split(normal, ql, qr, zl, zr)
+            #print 'edgeflux', edgeflux
+
+            # THIS IS THE LINE TO DEAL WITH LEFT AND RIGHT FLUXES
+            # flux = edgefluxleft - edgefluxright
+            flux -= edgeflux #* domain.edgelengths[k,i]
+
+            #Update optimal_timestep
+            try:
+                #timestep = min(timestep, 0.5*domain.radii[k]/max_speed)
+                timestep = min(timestep, domain.cfl*0.5*domain.areas[k]/max_speed)
+                #print "cell %d wet length %f"%(k,domain.areas[k])
+                #print "timestep %f max speed %f hl %f uhl %f hr %f uhr %f" %(timestep,max_speed,ql[0],ql[1],qr[0],qr[1])
+            except ZeroDivisionError:
+                pass
+
+        #Normalise by area and store for when all conserved
+        #quantities get updated
+        flux /= domain.areas[k]
+
+        #try:
+        #    #if flux[0] > 1.0e-6: unecessary because only min is taken
+        #    if Height.centroid_values[k] > 1.0e-3:
+        #        timestep = min(timestep, domain.cfl*0.5*Height.centroid_values[k]*domain.areas[k]/abs(flux[0]))
+        #except ZeroDivisionError:
+        #    pass
+
+
+
+        #Stage.explicit_update[k] = flux[0]
+        Height.explicit_update[k] = flux[0]
+        Xmom.explicit_update[k] = flux[1]
+        #Ymom.explicit_update[k] = flux[2]
+
+
+    domain.timestep = timestep
+    #print "flux"
+    #print Height.explicit_update
+
+    #print "integral %f"%domain.quantities['height'].get_integral()
+
+####################################
+
+# 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
+
+    """
+
+    #print "in distribute to vertices and edges"
+    #print "integral %f"%domain.quantities['height'].get_integral()
+    
+    #from config import optimised_gradient_limiter
+
+    #Remove very thin layers of water
+    #protect_against_infinitesimal_and_negative_heights(domain)
+    
+    #classify_wet_dry_cells(domain)
+    #import copy
+    #print domain.wet_nodes
+    #StageQ = copy.copy(domain.quantities['stage'].centroid_values)
+    #adjust_partially_submerged_cells(domain)
+    #StageQ2 = domain.quantities['stage'].centroid_values
+    #print StageQ-StageQ2
+    
+    #Extrapolate all conserved quantities
+    #if optimised_gradient_limiter:
+    #    #MH090605 if second order,
+    #    #perform the extrapolation and limiting on
+    #    #all of the conserved quantities
+
+    #    if (domain.order == 1):
+    #        for name in domain.conserved_quantities:
+    #            Q = domain.quantities[name]
+    #            Q.extrapolate_first_order()
+    #    elif domain.order == 2:
+    #        domain.extrapolate_second_order_sw()
+    #    else:
+    #        raise 'Unknown order'
+    #else:
+        #old code:
+
+    for name in domain.conserved_quantities:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            #print "add extrapolate second order to shallow water"
+            if (name != 'height'):#& (name != "xmomentum"):
+                Q.extrapolate_second_order()
+            #Q.limit()
+        else:
+            raise 'Unknown order'
+
+    #Take bed elevation into account when water heights are small
+    #balance_deep_and_shallow(domain)
+    protect_dry_beds(domain)
+    
+    #Compute edge values by interpolation
+    #for name in domain.conserved_quantities:
+    #    Q = domain.quantities[name]
+    #    Q.interpolate_from_vertices_to_edges()
+
+    #print domain.quantities['stage'].centroid_values
+    
+def protect_dry_beds(domain):
+    #print "in protect dry beds"
+    #print "integral %f"%domain.quantities['height'].get_integral()
+    
+    N = domain.number_of_elements
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = domain.quantities['height'].centroid_values
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    xmomv = domain.quantities['xmomentum'].vertex_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    min_centroid_height = 1e-3
+
+    for k in range(N):
+        if hc[k] < domain.minimum_allowed_height:
+            if hc[k] < domain.epsilon:
+                wc[k] = zc[k]
+                wv[k,0] = zv[k,0]
+                wv[k,1] = zv[k,1]
+                xmomc[k] = 0.0
+                xmomv[k,:] = 0.0
+        
+
+def set_initial_conserved_quanitites(domain):
+    from util import calculate_new_wet_area, calculate_wetted_area
+    from Numeric import allclose
+    
+    N = domain.number_of_elements
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    xv = domain.vertices
+    zc = domain.quantities['elevation'].centroid_values
+    wc = domain.quantities['stage'].centroid_values
+    hc = domain.quantities['height'].centroid_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    
+    #A1 = domain.quantities['stage'].get_integral()
+    for k in range(N):
+        if hc[k] < 0.0:
+            print "ERROR!!!!!!!!!!!!!!!!!!"
+        #if (domain.wet_nodes[k,0] == 0) | (domain.wet_nodes[k,1] == 0):
+        if (wv[k,0] <  zv[k,0]) | (wv[k,1] <  zv[k,1]):
+            # cell is dry or wetted
+            #print "cell %d is wetted or dry"%k
+            w1 = wv[k,0]
+            w2 = wv[k,1]
+            z1 = zv[k,0]
+            z2 = zv[k,1]
+            x1 = xv[k,0]
+            x2 = xv[k,1]
+            #print w1,w2
+            A = calculate_wetted_area(x1,x2,z1,z2,w1,w2)
+            L = x2-x1
+            w_centroid, wet_len = calculate_new_wet_area(x1,x2,z1,z2,A)
+            #print "cell",k,"stage",w1,w2
+            #print A
+            if A > 0.0:
+                wc[k] = w_centroid # surface is flat in wetted bed
+                #wv[k,0] = w1
+                #wv[k,1] = w2
+                domain.wet_nodes[k,0] = 2  # stops limiter from limiting these cells
+                domain.wet_nodes[k,1] = 2
+                hc[k] = A/L
+               # print "hc %f" %hc[k]
+                #xmomc[k] = 0.0
+                #print "cell",k,"stage",wc[k],hc[k],wet_len
+                #if wet_len > 0.0:
+                    #domain.areas[k] = wet_len
+            else:
+                #print "cell %d is not wetted but dry"%k
+                wc[k] = 0.5*(w1+w2) # bed is completely dry
+                wv[k,0] = zv[k,0]
+                wv[k,1] = zv[k,1]
+                domain.wet_nodes[k,0] = 0
+                domain.wet_nodes[k,1] = 0
+                hc[k] = 0.0
+        else:
+            #print "cell",k,"is wet"
+            hc[k] = wc[k]-zc[k]
+            
+    #A2 = domain.quantities['stage'].get_integral()
+    #assert allclose(A1,A2)
+    print "Must set initial conditions for momentum as well in set_initial_conserved_quanitites and adjust"
+    #print hc
+
+
+def adjust_partially_submerged_cells(domain):
+    #normal#
+    #print "in adjust wetted_cells"
+    #print "integral %f"%domain.quantities['height'].get_integral()
+
+    from util import calculate_new_wet_area, analytic_cannal
+    min_centroid_height = 1.0e-3
+    N = domain.number_of_elements
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    xv = domain.vertices
+    xc = domain.centroids
+    zc = domain.quantities['elevation'].centroid_values
+    wc = domain.quantities['stage'].centroid_values
+    hc = domain.quantities['height'].centroid_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    xmomv = domain.quantities['xmomentum'].vertex_values
+    
+    domain.wet_nodes[:,:] = 0.0
+
+    #print hc
+
+    for k in range(N):
+        domain.areas[k] = xv[k,1]-xv[k,0]
+        
+        if hc[k] <= domain.epsilon:
+            if hc[k] < 0.0:
+                if hc[k+1] > domain.epsilon:
+                  hc[k+1] += hc[k]
+                else: #hc[k-1] > domain.epsilon:
+                    hc[k-1] += hc[k]
+                    
+            hc[k] = 0.0 # if this not here get negative heights means timesteping wrong
+            wc[k] = zc[k]
+            xmomc[k] = 0.0
+            xmomv[k,0] = 0.0
+            xmomv[k,1] = 0.0
+        else: #hc[k] > domain.epsilon: #min_centroid_height:
+            z1 = zv[k,0]
+            z2 = zv[k,1]
+            x1 = xv[k,0]
+            x2 = xv[k,1]
+            L = x2-x1
+            A = hc[k]*L
+            if A > 0.0:
+                w_centroid, wet_len = calculate_new_wet_area(x1,x2,z1,z2,A)
+                if (w_centroid > max(z1,z2)):
+                    wc[k] = w_centroid
+                    #xmomc[k] = 0.5*(uh1+uh2)
+                    #xmomv[k,0] = uh1
+                    #xmomv[k,1] = uh2 # sets xmom to be analytic everwhere
+                    
+                elif (w_centroid > min(z1,z2)):
+                    wc[k] = w_centroid # surface is flat in wetted bed
+                    #wv[k,0] = w1
+                    #wv[k,1] = w2 # this is done by slope limiter
+                    domain.wet_nodes[k,0] = 2  # stops limiter from limiting these cells
+                    domain.wet_nodes[k,1] = 2
+                    #print "cell",k, hc[k], A,L, w1,w2
+                    wcrap,uhc = analytic_cannal(xc[k],domain.time+domain.timestep)
+                    w1,uh1 = analytic_cannal(x1,domain.time+domain.timestep)
+                    w2,uh2 = analytic_cannal(x2,domain.time+domain.timestep)
+            
+                    if (w_centroid > z1):
+                        #w1,uh1 = analytic_cannal(xc[k-1],domain.time+domain.timestep)
+                        #xmomv[k,0] = uh1
+                        xmomv[k,0] = 0.0
+                        xmomv[k,1] = 0.0
+                        #xmomc[k] = uh1
+                        xmomc[k] = 0.0
+                        
+                    else:
+                        #w2,uh2 = analytic_cannal(xc[k+1],domain.time+domain.timestep)
+                        xmomv[k,0] = 0.0
+                        xmomv[k,1] = 0.0
+                        #xmomv[k,1] = uh2
+                        #xmomc[k] = uh2
+                        xmomc[k] = 0.0
+                else:
+                    wc[k] = zc[k] # bed is completely dry
+                    domain.wet_nodes[k,0] = 0
+                    domain.wet_nodes[k,1] = 0
+                    hc[k] = 0.0
+                    xmomc[k] = 0.0
+                    xmomv[k,0] = 0.0
+                    xmomv[k,1] = 0.0
+                #if wet_len > 0.0:
+                    #domain.areas[k] = wet_len
+                    # if wet_len is 0 then bed is flat and area = x2-x1 (as default)
+            else:
+                wc[k] = zc[k] # bed is completely dry
+                domain.wet_nodes[k,0] = 0
+                domain.wet_nodes[k,1] = 0
+                hc[k] = 0.0
+                xmomc[k] = 0.0
+                xmomv[k,0] = 0.0
+                xmomv[k,1] = 0.0
+                
+    #for k in range(N):
+    #    
+    #    wcrap,uhc = analytic_cannal(xc[int(N/2)],domain.time+domain.timestep)
+    #    if (k > 1) & (k<N-2):
+    #        if (wc[k-2] < max(zv[k-2,0],zv[k-2,1])) & (wc[k-2] > min(zv[k-2,0],zv[k-2,1])) & (hc[k+1] < domain.epsilon):
+    #            #print "TRUE"
+    #            xmomc[k] = uhc
+    #        if (wc[k+2] < max(zv[k+2,0],zv[k+2,1])) & (wc[k+2] > min(zv[k+2,0],zv[k+2,1])) & (hc[k-1] < domain.epsilon):
+    #            #print "FALSE"
+    #            xmomc[k] = uhc
+                
+        
+    #print "integral %f"%domain.quantities['height'].get_integral()
+    #print domain.quantities['height'].centroid_values
+    
+def adjust_partially_submerged_cells_analytic(domain):
+    #analytic#
+
+    #print "in adjust wetted_cells"
+    from util import calculate_new_wet_area_analytic
+    min_centroid_height = 1.0e-3
+    N = domain.number_of_elements
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    xv = domain.vertices
+    zc = domain.quantities['elevation'].centroid_values
+    wc = domain.quantities['stage'].centroid_values
+    hc = domain.quantities['height'].centroid_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    xmomv = domain.quantities['xmomentum'].vertex_values
+
+    domain.wet_nodes[:,:] = 0.0
+
+    #print hc
+
+    for k in range(N):
+        domain.areas[k] = xv[k,1]-xv[k,0]
+        if hc[k] > domain.epsilon:#min_centroid_height:
+            z1 = zv[k,0]
+            z2 = zv[k,1]
+            x1 = xv[k,0]
+            x2 = xv[k,1]
+            L = x2-x1
+            A = hc[k]*L
+            if A > 0.0:
+                #print "cell %d is wetted" %k
+                #print "time: %f -- is 1 sec behind real time in adjust. i.e. time has not been updated"%domain.time
+                w1,w2, wet_len,uh1,uh2 = calculate_new_wet_area_analytic(x1,x2,z1,z2,A,domain.time+1.0)
+                xmomc[k] = 0.5*(uh1+uh2)
+                xmomv[k,0] = uh1
+                xmomv[k,1] = uh2
+                if (w1 > z1) & (w2 > z2):
+                    #wc[k] = (w1+w2)*0.5
+                    #wv[k,0] = w1
+                    #wv[k,1] = w2
+                    wc[k] = zc[k]+hc[k]
+                    xmomv[k,0] = uh1
+                    xmomv[k,1] = uh2
+                    xmomc[k] = 0.5*(uh1+uh2)
+                    #print w1,w2
+                elif (w1 > min(z1,z2)) | (w2 > min(z1,z2)):
+                    wc[k] = 0.5*(w1+w2)
+                    wv[k,0] = w1
+                    wv[k,1] = w2
+                    #print "cell %d w1 %f w2 %f" %(k,w1,w2)
+                    # stops limiter from limiting these cells
+                    domain.wet_nodes[k,0] = 2
+                    domain.wet_nodes[k,1] = 2
+                    if (w1 > z1):
+                        xmomv[k,0] = uh1
+                        xmomv[k,1] = 0.0
+                    else:
+                        xmomv[k,0] = 0.0
+                        xmomv[k,1] = uh2
+                else:
+                    wc[k] = zc[k] # bed is completely dry
+                    domain.wet_nodes[k,0] = 0
+                    domain.wet_nodes[k,1] = 0
+                    hc[k] = 0.0
+                    xmomc[k] = 0.0
+                if wet_len > 0.0:
+                    domain.areas[k] = wet_len
+                    #print w1,w2
+                    #print "cell %d wet length %f"%(k,wet_len)
+                    # if wet_len is 0 then bed is flat and area = x2-x1 (as default)
+            else:
+                wc[k] = zc[k] # bed is completely dry
+                domain.wet_nodes[k,0] = 0
+                domain.wet_nodes[k,1] = 0
+                hc[k] = 0.0
+                #xmomc[k] = 0.0
+        else:
+            wc[k] = zc[k]
+            xmomc[k] = 0.0
+
+
+def distribute_stage_to_height(domain):
+
+    #print "in distribute stage to height"
+    #print "integral %f"%domain.quantities['height'].get_integral()
+
+    #print "hv1",domain.quantities['height'].vertex_values
+    #print "hc1",domain.quantities['height'].centroid_values
+    
+    min_centroid_height = 1.0e-3
+    N = domain.number_of_elements
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    hv = domain.quantities['height'].vertex_values
+    hc = domain.quantities['height'].centroid_values
+    for k in range(N):
+        for i in range(2):
+            if hc[k] > domain.epsilon:
+                hv[k,i] = wv[k,i]-zv[k,i]
+            elif hc[k] < 0:
+                print "ERROR"
+            else:
+                hv[k,i] = 0.0
+        
+    #print "hv2",domain.quantities['height'].vertex_values
+    #print "hc2",domain.quantities['height'].centroid_values
+    #print "integral %f"%domain.quantities['height'].get_integral()
+    
+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
+#    ymomc = domain.quantities['ymomentum'].centroid_values
+    hc = wc - zc  #Water depths at centroids
+
+    zv = domain.quantities['elevation'].vertex_values
+    wv = domain.quantities['stage'].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]
+
+            #Control momentum
+            #xmomc[k] = ymomc[k] = 0.0
+            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(3):
+        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(3):
+    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(3):
+        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(3):
+        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
+#            ymomc = domain.quantities['ymomentum'].centroid_values
+
+            #Momentums at vertices
+            xmomv = domain.quantities['xmomentum'].vertex_values
+#           ymomv = domain.quantities['ymomentum'].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,:]
+#            ymomv[k,:] = (1-alpha)*ymomc[k] + alpha*ymomv[k,:]
+
+
+###############################################
+#Boundaries - specific to the shallow water wave equation
+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.stage   = domain.quantities['stage'].edge_values
+        #self.xmom    = domain.quantities['xmomentum'].edge_values
+        #self.ymom    = domain.quantities['ymomentum'].edge_values
+        #self.normals = domain.normals
+        self.stage   = domain.quantities['stage'].vertex_values
+        self.xmom    = domain.quantities['xmomentum'].vertex_values
+        self.height  = domain.quantities['height'].vertex_values
+
+        from Numeric import zeros, Float
+        self.conserved_quantities = zeros(3, Float)
+        #self.conserved_quantities = zeros(2, 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.conserved_quantities
+        q[0] = self.stage[vol_id, edge_id]
+        q[1] = self.xmom[vol_id, edge_id]
+        #q[2] = self.ymom[vol_id, edge_id]
+        q[2] = self.height[vol_id,edge_id] 
+        #normal = self.normals[vol_id, 2*edge_id:2*edge_id+2]
+        #normal = self.normals[vol_id, 2*edge_id:2*edge_id+1]
+
+
+        #r = rotate(q, normal, direction = 1)
+        #r[1] = -r[1]
+        #q = rotate(r, normal, direction = -1)
+        r = q
+        r[1] = -q[1]
+        q = r
+        #For start interval there is no outward momentum so do not need to
+        #reverse direction in this case
+
+        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
+
+
+#########################
+#Standard forcing terms:
+#
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+    #print "in gravity"
+    #print "integral %f"%domain.quantities['height'].get_integral()
+    from util import gradient
+    from Numeric import zeros, Float, array, sum
+
+    xmom = domain.quantities['xmomentum'].explicit_update
+    stage = domain.quantities['stage'].explicit_update
+#    ymom = domain.quantities['ymomentum'].explicit_update
+
+    Stage = domain.quantities['stage']
+    Elevation = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    #h = Stage.edge_values - Elevation.edge_values
+    h = Stage.vertex_values - Elevation.vertex_values
+    hc = Height.centroid_values
+    h = Height.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,:] )/3
+        #avg_h = sum( h[k,:] )/2
+        avg_h = hc[k]
+
+        #Compute bed slope
+        #x0, y0, x1, y1, x2, y2 = x[k,:]
+        x0, x1 = x[k,:]
+        #z0, z1, z2 = v[k,:]
+        b0, b1 = b[k,:]
+
+        w0, w1 = w[k,:]
+        wx = gradient(x0, x1, w0, w1)
+
+        #zx, zy = gradient(x0, y0, x1, y1, x2, y2, z0, z1, z2)
+        bx = gradient(x0, x1, b0, b1)
+        
+        #Update momentum (explicit update is reset to source values)
+        if domain.split == False:
+            xmom[k] += -g*bx*avg_h
+            #xmom[k] = -g*bx*avg_h
+            #stage[k] = 0.0
+        elif domain.split == True:
+            xmom[k] += -g*wx*avg_h
+            #xmom[k] = -g*wx*avg_h
+        #ymom[k] += -g*zy*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
+    #vh = domain.quantities['ymomentum'].centroid_values
+    eta = domain.quantities['friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+    #ymom_update = domain.quantities['ymomentum'].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 * sqrt((uh[k]**2 + vh[k]**2))
+                S = -g * eta[k]**2 * uh[k]
+            	S /= h[k]**(7.0/3)
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
+            	#ymom_update[k] += S*vh[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
+#    vh = domain.quantities['ymomentum'].centroid_values
+    tau = domain.quantities['linear_friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+#    ymom_update = domain.quantities['ymomentum'].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 = 3
+        N = 2
+        #x = ones(3, Float)
+        #y = ones(3, Float)
+        x = ones(2, Float)
+        #y = ones(2, Float)
+        
+        try:
+            #q = f(1.0, x=x, y=y)
+            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,y: vector_function(t,x=x,y=y)[0]
+            #phi = lambda t,x,y: vector_function(t,x=x,y=y)[1]
+            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
+        #ymom_update = domain.quantities['ymomentum'].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[:,0], xc[:,1])
+            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[:,0], xc[:,1])
+            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 * sqrt(u**2 + v**2)
+        S = const * u
+        xmom_update[k] += S*u
+        #ymom_update[k] += S*v
Index: /anuga_work/development/shallow_water_1d/shallow_water_domain.py
===================================================================
--- /anuga_work/development/shallow_water_1d/shallow_water_domain.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/shallow_water_domain.py	(revision 4959)
@@ -0,0 +1,961 @@
+"""Class Domain -
+2D triangular domains for finite-volume computations of
+the shallow water wave equation.
+
+
+$Description:
+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 + G_y = S
+
+where
+
+U = [w, uh, vh]
+E = [uh, u^2h + gh^2/2, uvh]
+G = [vh, uvh, v^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 respectively.
+
+The quantities are
+
+symbol    variable name    explanation
+x         x                horizontal distance from origin [m]
+y         y                vertical 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]
+v                          speed in the y direction [m/s]
+uh        xmomentum        momentum in the x direction [m^2/s]
+vh        ymomentum        momentum in the y direction [m^2/s]
+
+eta                        mannings friction coefficient [to appear]
+nu                         wind stress coefficient [to appear]
+
+The conserved quantities are w, uh, vh
+
+$References
+Catastrophic Collapse of Water Supply Reservoirs in Urban Areas,
+Christopher Zoppou and Stephen Roberts,
+Journal of Hydraulic Engineering, vol. 127, No. 7 July 1999
+
+Hydrodynamic modelling of coastal inundation. 
+Nielsen, O., S. Roberts, D. Gray, A. McPherson and A. Hitchman
+In Zerger, A. and Argent, R.M. (eds) MODSIM 2005 International Congress on
+Modelling and Simulation. Modelling and Simulation Society of Australia and
+New Zealand, December 2005, pp. 518-523. ISBN: 0-9758400-2-9.
+http://www.mssanz.org.au/modsim05/papers/nielsen.pdf
+
+
+Ole Nielsen, Stephen Roberts, Duncan Gray, Christopher Zoppou
+Geoscience Australia, 2004
+
+
+$Author: ole $
+$Revision: 3642 $
+$Date: 2006-09-21 11:30:59 +1000 (Thu, 21 Sep 2006) $
+$LastChangedDate: 2006-09-21 11:30:59 +1000 (Thu, 21 Sep 2006) $
+$LastChangedRevision: 3642 $
+$LastChangedBy: ole $
+$HeadURL: https://datamining/svn/ga/anuga_core/source/anuga/shallow_water/shallow_water_domain.py $
+"""
+
+#Subversion keywords:
+#
+#$LastChangedDate: 2006-09-21 11:30:59 +1000 (Thu, 21 Sep 2006) $
+#$LastChangedRevision: 3642 $
+#$LastChangedBy: ole $
+
+
+from domain_t2 import *
+Generic_Domain = Domain #Rename
+
+#Shallow water domain
+class Domain(Generic_Domain):
+
+    def __init__(self,
+                 coordinates=None,
+                 vertices=None,
+                 boundary=None,
+                 tagged_elements=None,
+                 geo_reference=None):
+
+
+        conserved_quantities = ['stage', 'xmomentum']
+        other_quantities = ['elevation', 'friction']
+        Generic_Domain.__init__(self,
+                                coordinates,
+                                boundary,
+                                conserved_quantities,
+                                other_quantities,
+                                tagged_elements,
+                                geo_reference)
+
+
+        from config import minimum_allowed_height, maximum_allowed_speed, g
+        self.minimum_allowed_height = minimum_allowed_height
+        self.maximum_allowed_speed = maximum_allowed_speed
+        self.g = g
+
+
+        #self.forcing_terms.append(manning_friction)
+        self.forcing_terms.append(gravity)
+
+    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 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
+        
+    def extrapolate_second_order_sw(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        extrapolate_second_order_sw(self)
+
+    def compute_timestep(self):
+        #Call correct module function
+        compute_timestep(self)
+
+    def compute_fluxes(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        compute_fluxes(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):
+        """Specialisation of basic evolve method from parent class
+        """
+
+        #Call check integrity here rather than from user scripts
+        #self.check_integrity()
+
+        msg = 'Parameter beta_h must be in the interval [0, 1['
+        assert 0 <= self.beta_h < 1.0, msg
+        msg = 'Parameter beta_w must be in the interval [0, 1['
+        assert 0 <= self.beta_w < 1.0, msg
+
+
+        #Initial update of vertex and edge values before any storage
+        #and or visualisation
+        self.distribute_to_vertices_and_edges()
+
+        #Call basic machinery from parent class
+        for t in Generic_Domain.evolve(self,
+                                       yieldstep=yieldstep,
+                                       finaltime=finaltime,
+                                       skip_initial_step=skip_initial_step):
+
+
+            #Pass control on to outer loop for more specific actions
+            yield(t)
+
+
+#=============== End of Shallow Water Domain ===============================
+
+
+####################################
+# Flux computation
+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, vh are stored as elements 0, 1 and 2
+    in the numerical vectors ql and qr.
+
+    Bed elevations zl and zr.
+    """
+
+    from config import g, epsilon
+    from math import sqrt
+    from Numeric import array, zeros, Float
+
+    #Align momentums with x-axis
+    #q_left  = rotate(ql, normal, direction = 1)
+    #q_right = rotate(qr, normal, direction = 1)
+    q_left = zeros(len(ql),Float)
+    q_right = zeros(len(qr),Float)
+    
+    q_left[:] = ql[:]
+    q_right[:] = qr[:]
+    
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+
+    z = (zl+zr)/2.0 #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
+
+
+    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
+
+    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
+
+    #FIXME(Ole): Why is it again that we don't
+    #use uh_left and uh_right directly in the first entries?
+    flux_left  = array([u_left*h_left,
+                        u_left*uh_left + 0.5*g*h_left**2])
+    flux_right = array([u_right*h_right,
+                        u_right*uh_right + 0.5*g*h_right**2])
+
+    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 = rotate(edgeflux, normal, direction=-1)
+        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_edges[k,i]
+                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]
+
+            if domain.split == False:
+                edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            elif domain.split == True:
+                edgeflux, max_speed = flux_function_split(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
+
+def compute_fluxes(domain):
+    """Compute all fluxes and the timestep suitable for all volumes
+    in domain.
+
+    Compute total flux for each conserved quantity using "flux_function"
+
+    Fluxes across each edge are scaled by edgelengths and summed up
+    Resulting flux is then scaled by area and stored in
+    explicit_update for each of the three conserved quantities
+    stage, xmomentum and ymomentum
+
+    The maximal allowable speed computed by the flux_function for each volume
+    is converted to a timestep that must not be exceeded. The minimum of
+    those is computed as the next overall timestep.
+
+    Post conditions:
+      domain.explicit_update is reset to computed flux values
+      domain.timestep is set to the largest step satisfying all volumes.
+    """
+
+    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
+
+    #Arrays
+    stage_bdry = Stage.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+
+    flux = zeros(2, Float) #Work array for summing up fluxes
+
+
+    #Loop
+    timestep = float(sys.maxint)
+    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 = [stage_bdry[m], xmom_bdry[m]]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                m = domain.neighbour_vertices[k,i]
+                qr = [stage[n, m], xmom[n, m]]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+
+            #Flux computation using provided function
+            edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            flux -= edgeflux
+
+            #Update optimal_timestep on full cells
+            #if  domain.tri_full_flag[k] == 1:
+            try:
+                timestep = min(timestep, 0.5*domain.areas[k]/max_speed)
+            except ZeroDivisionError:
+                pass
+
+        #Normalise by area and store for when all conserved
+        #quantities get updated
+        flux /= domain.areas[k]
+        Stage.explicit_update[k] = flux[0]
+        Xmom.explicit_update[k] = flux[1]
+
+    domain.timestep = timestep
+
+####################################
+# 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
+
+    """
+
+    #Remove very thin layers of water
+    protect_against_infinitesimal_and_negative_heights(domain)
+
+    #Extrapolate all conserved quantities
+    #old code:
+    for name in domain.conserved_quantities:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            Q.extrapolate_second_order()
+        else:
+            raise 'Unknown order'
+
+
+    #Take bed elevation into account when water heights are small
+    balance_deep_and_shallow(domain)
+
+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
+
+    #Update
+    #FIXME: Modify accroditg to c-version - or discard altogether.
+    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
+
+            #Control momentum
+            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.0), 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]))
+
+
+        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.0*hmin/dz, 1.0), 0.0 )
+        else:
+            #Flat bed
+            alpha = 1.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(2):
+                wv[k,i] = zv[k,i] + (1-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-alpha)*xmomc[k] + alpha*xmomv[k,:]
+
+
+###############################################
+#Boundaries - specific to the shallow water wave equation
+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.stage   = domain.quantities['stage'].vertex_values
+        self.xmom    = domain.quantities['xmomentum'].vertex_values
+        self.normals = domain.normals
+
+        from Numeric import zeros, Float
+        self.conserved_quantities = zeros(2, 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.conserved_quantities
+        q[0] = self.stage[vol_id, edge_id]
+        q[1] = self.xmom[vol_id, edge_id]
+
+
+        #r = rotate(q, normal, direction = 1)
+        #r[1] = -r[1]
+        #q = rotate(r, normal, direction = -1)
+        r = q
+        r[1] = -q[1]
+        q = r
+
+        return q
+
+
+#########################
+#Standard forcing terms:
+#
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from Numeric import zeros, Float, array, sum
+    from util import gradient
+
+    xmom = domain.quantities['xmomentum'].explicit_update
+
+    Stage = domain.quantities['stage']
+    Elevation = domain.quantities['elevation']
+    h = Stage.vertex_values - Elevation.vertex_values
+    v = Elevation.vertex_values
+
+    x = domain.get_vertex_coordinates()
+    g = domain.g
+
+    for k in range(domain.number_of_elements):
+        avg_h = sum( h[k,:] )/2.0
+
+        #Compute bed slope
+        x0, x1 = x[k,:]
+        z0, z1 = v[k,:]
+
+        zx = gradient(x0, x1, z0, z1)
+
+        #Update momentumw
+        xmom[k] += -g*zx*avg_h
+
+def manning_friction(domain):
+    """Apply (Manning) friction to water momentum
+    (Python version)
+    """
+
+    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 * sqrt(uh[k]**2)
+            	S /= h[k]**(7.0/3.0)
+
+            	#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)
+        y = ones(2, Float)
+        try:
+            q = f(1.0, x=x, y=y)
+        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 Exception(msg)
+    return f
+
+
+###########################
+###########################
+#Geometries
+
+class Constant_stage:
+    """Set an initial condition with constant stage
+    """
+    def __init__(self, s):
+        self.s = s
+
+    def __call__(self, x, y):
+        return self.s
+
+class Constant_height:
+    """Set an initial condition with constant water height, e.g
+    stage s = z+h
+    """
+
+    def __init__(self, W, h):
+        self.W = W
+        self.h = h
+
+    def __call__(self, x, y):
+        if self.W is None:
+            from Numeric import ones, Float
+            return self.h*ones(len(x), Float)
+        else:
+            return self.W(x,y) + self.h
+
+
+
+"""
+def compute_fluxes_python(domain):
+    Compute all fluxes and the timestep suitable for all volumes
+    in domain.
+
+    Compute total flux for each conserved quantity using "flux_function"
+
+    Fluxes across each edge are scaled by edgelengths and summed up
+    Resulting flux is then scaled by area and stored in
+    explicit_update for each of the three conserved quantities
+    stage, xmomentum and ymomentum
+
+    The maximal allowable speed computed by the flux_function for each volume
+    is converted to a timestep that must not be exceeded. The minimum of
+    those is computed as the next overall timestep.
+
+    Post conditions:
+      domain.explicit_update is reset to computed flux values
+      domain.timestep is set to the largest step satisfying all volumes.
+    
+
+    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']
+
+    #Arrays
+    stage = Stage.edge_values
+    xmom =  Xmom.edge_values
+    bed =   Bed.edge_values
+
+    stage_bdry = Stage.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+
+    flux = zeros((N,2), Float) #Work array for summing up fluxes
+
+    #Loop
+    timestep = float(sys.maxint)
+    for k in range(N):
+
+        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 = [stage_bdry[m], xmom_bdry[m]]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                m = domain.neighbour_edges[k,i]
+                qr = [stage[n, m], xmom[n, m]]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, 2*i:2*i+2]
+
+            #Flux computation using provided function
+            edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+
+            flux[k,:] = edgeflux
+
+    return flux
+"""
+
+
+
+
+
+
+##############################################
+#Initialise module
+
+
+#Optimisation with psyco
+from config import use_psyco
+if use_psyco:
+    try:
+        import psyco
+    except:
+        import os
+        if os.name == 'posix' and os.uname()[4] == 'x86_64':
+            pass
+            #Psyco isn't supported on 64 bit systems, but it doesn't matter
+        else:
+            msg = 'WARNING: psyco (speedup) could not import'+\
+                  ', you may want to consider installing it'
+            print msg
+    else:
+        psyco.bind(Domain.distribute_to_vertices_and_edges)
+        psyco.bind(Domain.compute_fluxes)
+
+if __name__ == "__main__":
+    pass
+
+# Profiling stuff
+import profile
+profiler = profile.Profile()
Index: /anuga_work/development/shallow_water_1d/shallow_water_h.py
===================================================================
--- /anuga_work/development/shallow_water_1d/shallow_water_h.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/shallow_water_h.py	(revision 4959)
@@ -0,0 +1,1305 @@
+"""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 respectively.
+
+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 h, 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 *
+#from domain_order2 import *
+from domain_t2 import *
+Generic_Domain = Domain #Rename
+
+#Shallow water domain
+class Domain(Generic_Domain):
+
+    def __init__(self, coordinates, boundary = None, tagged_elements = None,
+                 geo_reference = None):
+
+        conserved_quantities = ['height', 'xmomentum']
+        other_quantities = ['stage', 'elevation', 'friction']
+        Generic_Domain.__init__(self, coordinates, boundary,
+                                conserved_quantities, other_quantities,
+                                tagged_elements, geo_reference)
+        
+        from config import minimum_allowed_height, g
+        self.minimum_allowed_height = minimum_allowed_height
+        self.g = g
+
+        #forcing terms not included in 1d domain ?WHy?
+        self.forcing_terms.append(gravity)
+        #self.forcing_terms.append(manning_friction)
+        #print "\nI have Removed forcing terms line 64 1dsw"
+
+        #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']
+
+
+    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 = 'First conserved quantity must be "height"'
+        assert self.conserved_quantities[0] == 'height', msg
+
+        msg = 'Second conserved quantity must be "xmomentum"'
+        assert self.conserved_quantities[1] == 'xmomentum', 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(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 update_derived_quantities():
+        Stage = domain.quantities['stage']
+        Height = domain.quantities['height']
+        Bed = domain.quantities['elevation']
+
+        #stage = Stage.centroid_values
+        #height = Height.centroid_values
+        #bed =   Bed.centroid_values
+
+        Stage = Height+Bed
+
+        
+        
+
+    def evolve(self, yieldstep = None, finaltime = None,
+               skip_initial_step = False):
+        """Specialisation of basic evolve method from parent class
+        """
+
+        #Call check integrity here rather than from user scripts
+        #self.check_integrity()
+
+        #msg = 'Parameter beta_h must be in the interval [0, 1)'
+        #assert 0 <= self.beta_h < 1.0, msg
+        #msg = 'Parameter beta_w must be in the interval [0, 1)'
+        #assert 0 <= self.beta_w < 1.0, msg
+
+
+        #Initial update of vertex and edge values before any storage
+        #and or visualisation
+        self.distribute_to_vertices_and_edges()
+        
+        #Initialise real time viz if requested
+        #if self.visualise is True and self.time == 0.0:
+        #    if self.visualiser is None:
+        #        self.initialise_visualiser()
+        #
+        #    self.visualiser.update_timer()
+        #    self.visualiser.setup_all()
+
+        #Store model data, e.g. for visualisation
+        #if self.store is True and self.time == 0.0:
+        #    self.initialise_storage()
+        #    #print 'Storing results in ' + self.writer.filename
+        #else:
+        #    pass
+        #    #print 'Results will not be stored.'
+        #    #print 'To store results set domain.store = True'
+        #    #FIXME: Diagnostic output should be controlled by
+        #    # a 'verbose' flag living in domain (or in a parent class)
+
+        #Call basic machinery from parent class
+        for t in Generic_Domain.evolve(self, yieldstep, finaltime,
+                                       skip_initial_step):
+            #Real time viz
+        #    if self.visualise is True:
+        #        self.visualiser.update_all()
+        #        self.visualiser.update_timer()
+
+
+            #Store model data, e.g. for subsequent visualisation
+        #    if self.store is True:
+        #        self.store_timestep(self.quantities_to_be_stored)
+
+            #FIXME: Could maybe be taken from specified list
+            #of 'store every step' quantities
+
+            #Pass control on to outer loop for more specific actions
+            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
+    from math import sqrt
+    from Numeric import array
+
+    #print 'ql',ql
+
+    #Align momentums with x-axis
+    #q_left  = rotate(ql, normal, direction = 1)
+    #q_right = rotate(qr, normal, direction = 1)
+    q_left = ql
+    q_left[1] = q_left[1]*normal
+    q_right = qr
+    q_right[1] = q_right[1]*normal
+
+    #z = (zl+zr)/2 #Take average of field values
+    z = 0.5*(zl+zr) #Take average of field values
+
+    #w_left  = q_left[0]   #w=h+z
+    #h_left  = w_left-z
+    h_left  = q_left[0]
+    w_left  = z + h_left
+    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
+
+
+    #w_right  = q_right[0]  #w=h+z
+    #h_right  = w_right-z
+    h_right  = q_right[0]
+    w_right  = z + h_right
+    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
+
+    #vh_left  = q_left[2]
+    #vh_right = q_right[2]
+
+    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**2])
+    #flux_right = array([u_right*h_right,
+    #                    u_right*uh_right + 0.5*g*h_right**2])
+    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']
+    Height = domain.quantities['height']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+
+    #stage = Stage.vertex_values
+    height = Height.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+    
+    #stage_bdry = Stage.boundary_values
+    height_bdry = Height.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 = [height[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] = height_bdry[m]
+                qr[1] = xmom_bdry[m]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                m = domain.neighbour_vertices[k,i]
+                qr[0] = height[n, m]
+                qr[1] =  xmom[n, m]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+
+            if domain.split == False:
+                edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            elif domain.split == True:
+                edgeflux, max_speed = flux_function_split(normal, ql, qr, zl, zr)
+
+            try:
+                timestep = min(timestep, domain.cfl*0.5*domain.areas[k]/max_speed)
+            except ZeroDivisionError:
+                pass
+
+    domain.timestep = timestep
+
+
+def compute_fluxes(domain):
+    """Compute all fluxes and the timestep suitable for all volumes
+    in domain.
+
+    Compute total flux for each conserved quantity using "flux_function"
+
+    Fluxes across each edge are scaled by edgelengths and summed up
+    Resulting flux is then scaled by area and stored in
+    explicit_update for each of the three conserved quantities
+    stage, xmomentum and ymomentum
+
+    The maximal allowable speed computed by the flux_function for each volume
+    is converted to a timestep that must not be exceeded. The minimum of
+    those is computed as the next overall timestep.
+
+    Post conditions:
+      domain.explicit_update is reset to computed flux values
+      domain.timestep is set to the largest step satisfying all volumes.
+    """
+
+    import sys
+    from Numeric import zeros, Float
+
+    N = domain.number_of_elements
+
+    #Shortcuts
+    #Stage = domain.quantities['stage']
+    Height = domain.quantities['height']
+    Xmom = domain.quantities['xmomentum']
+#    Ymom = domain.quantities['ymomentum']
+    Bed = domain.quantities['elevation']
+    """ 
+    from util import analytic_cannal
+    hc = domain.quantities['height'].centroid_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    xmomv = domain.quantities['xmomentum'].vertex_values
+    xv = domain.vertices
+
+    #will not show up as correct xmom on plot but is ok
+    for k in range(N):
+        if hc[k] < domain.minimum_allowed_height:
+            xmomc[k] = 0.0
+            xmomv[k,0] = 0.0
+            xmomv[k,1] = 0.0
+        else:
+            #ensure yield step is 1.0 or small enough to be less than min timestep
+            w1,uh1 = analytic_cannal(xv[k,0],domain.time)
+            w2,uh2 = analytic_cannal(xv[k,1],domain.time)
+            xmomv[k,0] = uh1
+            xmomv[k,1] = uh2
+            xmomc[k] = 0.5*(uh1+uh2)
+    """
+    #Arrays
+    #stage = Stage.edge_values
+    #xmom =  Xmom.edge_values
+ #   ymom =  Ymom.edge_values
+    #bed =   Bed.edge_values
+    
+    #stage = Stage.vertex_values
+    height = Height.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+    
+    #print 'stage edge values', stage
+    #print 'xmom edge values', xmom
+    #print 'bed values', bed
+
+    #stage_bdry = Stage.boundary_values
+    height_bdry = Height.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+    #print 'stage_bdry',stage_bdry
+    #print 'xmom_bdry', xmom_bdry
+#    ymom_bdry =  Ymom.boundary_values
+
+#    flux = zeros(3, Float) #Work array for summing up fluxes
+    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(3):
+        for i in range(2):
+            #Quantities inside volume facing neighbour i
+            #ql[0] = stage[k, i]
+            #ql[1] = xmom[k, i]
+            ql = [height[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] = height_bdry[m]
+                qr[1] = xmom_bdry[m]
+                zr = zl #Extend bed elevation to boundary
+            else:
+                #m = domain.neighbour_edges[k,i]
+                m = domain.neighbour_vertices[k,i]
+                #qr = [stage[n, m], xmom[n, m], ymom[n, m]]
+                qr[0] = height[n, m]
+                qr[1] =  xmom[n, m]
+                zr = bed[n, m]
+
+
+            #Outward pointing normal vector
+            normal = domain.normals[k, i]
+        
+            #Flux computation using provided function
+            #edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            #print 'ql',ql
+            #print 'qr',qr
+            
+
+            if domain.split == False:
+                edgeflux, max_speed = flux_function(normal, ql, qr, zl, zr)
+            elif domain.split == True:
+                edgeflux, max_speed = flux_function_split(normal, ql, qr, zl, zr)
+            #print 'edgeflux', edgeflux
+
+            # THIS IS THE LINE TO DEAL WITH LEFT AND RIGHT FLUXES
+            # flux = edgefluxleft - edgefluxright
+            flux -= edgeflux #* domain.edgelengths[k,i]
+            #Update optimal_timestep
+            try:
+                #timestep = min(timestep, 0.5*domain.radii[k]/max_speed)
+                timestep = min(timestep, domain.cfl*0.5*domain.areas[k]/max_speed)
+            except ZeroDivisionError:
+                pass
+
+        #Normalise by area and store for when all conserved
+        #quantities get updated
+        flux /= domain.areas[k]
+
+        Height.explicit_update[k] = flux[0]
+        Xmom.explicit_update[k]   = flux[1]
+        #Ymom.explicit_update[k]  = flux[2]
+
+    #print Height.vertex_values
+    #print Height.centroid_values
+
+    domain.timestep = timestep
+
+####################################
+
+# 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)
+    #classify_wet_dry_cells(domain)
+    #adjust_partially_submerged_cells(domain)
+
+    #Extrapolate all conserved quantities
+    #if optimised_gradient_limiter:
+    #    #MH090605 if second order,
+    #    #perform the extrapolation and limiting on
+    #    #all of the conserved quantities
+
+    #    if (domain.order == 1):
+    #        for name in domain.conserved_quantities:
+    #            Q = domain.quantities[name]
+    #            Q.extrapolate_first_order()
+    #    elif domain.order == 2:
+    #        domain.extrapolate_second_order_sw()
+    #    else:
+    #        raise 'Unknown order'
+    #else:
+        #old code:
+    for name in domain.conserved_quantities:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            #if name != "xmomentum":
+            Q.extrapolate_second_order()
+            #Q.limit()
+        else:
+            raise 'Unknown order'
+
+    #Take bed elevation into account when water heights are small
+    #balance_deep_and_shallow(domain)
+    #protect_dry_beds(domain)
+    protect_against_infinitesimal_and_negative_heights(domain)
+    
+    #Compute edge values by interpolation
+    #for name in domain.conserved_quantities:
+    #    Q = domain.quantities[name]
+    #    Q.interpolate_from_vertices_to_edges()
+
+    #print "dist", domain.quantities['height'].centroid_values
+    #print domain.quantities['height'].vertex_values
+     
+def protect_dry_beds(domain):
+    
+    
+    N = domain.number_of_elements
+    wc = domain.quantities['stage'].centroid_values
+    zc = domain.quantities['elevation'].centroid_values
+    hc = domain.quantities['height'].centroid_values
+    wv = domain.quantities['stage'].vertex_values
+    zv = domain.quantities['elevation'].vertex_values
+    xmomv = domain.quantities['xmomentum'].vertex_values
+    min_centroid_height = 1e-3
+
+    for k in range(N):
+        if hc[k] < min_centroid_height:
+            wc[k] = zc[k]
+            hcv[k,0] = zv[k,0]
+            wv[k,1] = zv[k,1]
+            xmomv[k,:] = 0.0
+
+
+def protect_against_infinitesimal_and_negative_heights(domain):
+    """Protect against infinitesimal heights and associated high velocities
+    """
+
+    #Shortcuts
+    zc = domain.quantities['elevation'].centroid_values
+    hc = domain.quantities['height'].centroid_values
+    hv = domain.quantities['height'].vertex_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    xmomv = domain.quantities['xmomentum'].vertex_values
+#    ymomc = domain.quantities['ymomentum'].centroid_values
+    wc = hc + zc  #stage at centroids
+
+    #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
+                hv[k,0] = 0.0
+                hv[k,1] = 0.0
+                hc[k] = 0.0
+
+            #Control momentum
+            xmomc[k] = 0.0
+        
+            #xmomc[k] = ymomc[k] = 0.0
+        if (hv[k,0] < domain.minimum_allowed_height) | (hv[k,1] < domain.minimum_allowed_height):
+            hv[k,0] = 0.0
+            hv[k,1] = 0.0
+            xmomc[k] = 0.0
+            xmomv[k,0] = 0.0
+            xmomv[k,1] = 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(3):
+        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(3):
+    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(3):
+        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(3):
+        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
+#            ymomc = domain.quantities['ymomentum'].centroid_values
+
+            #Momentums at vertices
+            xmomv = domain.quantities['xmomentum'].vertex_values
+#           ymomv = domain.quantities['ymomentum'].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,:]
+#            ymomv[k,:] = (1-alpha)*ymomc[k] + alpha*ymomv[k,:]
+
+
+###############################################
+#Boundaries - specific to the shallow water wave equation
+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.stage   = domain.quantities['stage'].edge_values
+        #self.xmom    = domain.quantities['xmomentum'].edge_values
+        #self.ymom    = domain.quantities['ymomentum'].edge_values
+        #self.normals = domain.normals
+        #self.stage   = domain.quantities['stage'].vertex_values
+        self.height  = domain.quantities['height'].vertex_values
+        self.xmom    = domain.quantities['xmomentum'].vertex_values
+
+        from Numeric import zeros, Float
+        #self.conserved_quantities = zeros(3, Float)
+        self.conserved_quantities = zeros(2, 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.conserved_quantities
+        #q[0] = self.stage[vol_id, edge_id]
+        q[0] = self.height[vol_id, edge_id]
+        #q[0] = 0.0
+        q[1] = self.xmom[vol_id, edge_id]
+        #q[2] = self.ymom[vol_id, edge_id]
+
+        #normal = self.normals[vol_id, 2*edge_id:2*edge_id+2]
+        #normal = self.normals[vol_id, 2*edge_id:2*edge_id+1]
+
+
+        #r = rotate(q, normal, direction = 1)
+        #r[1] = -r[1]
+        #q = rotate(r, normal, direction = -1)
+        r = q
+        r[1] = -q[1]
+        q = r
+        #For start interval there is no outward momentum so do not need to
+        #reverse direction in this case
+
+        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
+
+
+#########################
+#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']
+    Height = domain.quantities['height']
+    Elevation = domain.quantities['elevation']
+    #h = Stage.edge_values - Elevation.edge_values
+    h = Height.vertex_values
+    b = Elevation.vertex_values
+    w = Elevation.vertex_values + Height.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
+        if domain.split == False:
+            xmom[k] += -g*bx*avg_h
+        elif domain.split == True:
+            xmom[k] += -g*wx*avg_h
+ 
+def manning_friction(domain):
+    """Apply (Manning) friction to water momentum
+    """
+
+    from math import sqrt
+
+    w = domain.quantities['stage'].centroid_values
+    h = domain.quantities['height'].centroid_values
+    z = domain.quantities['elevation'].centroid_values
+    #h = w-z
+
+    uh = domain.quantities['xmomentum'].centroid_values
+    #vh = domain.quantities['ymomentum'].centroid_values
+    eta = domain.quantities['friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+    #ymom_update = domain.quantities['ymomentum'].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 * sqrt((uh[k]**2 + vh[k]**2))
+                S = -g * eta[k]**2 * uh[k]
+            	S /= h[k]**(7.0/3)
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
+            	#ymom_update[k] += S*vh[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 = domain.quantities['height'].centroid_values
+    #h = w-z
+
+    uh = domain.quantities['xmomentum'].centroid_values
+#    vh = domain.quantities['ymomentum'].centroid_values
+    tau = domain.quantities['linear_friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+#    ymom_update = domain.quantities['ymomentum'].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 = 3
+        N = 2
+        #x = ones(3, Float)
+        #y = ones(3, Float)
+        x = ones(2, Float)
+        #y = ones(2, Float)
+        
+        try:
+            #q = f(1.0, x=x, y=y)
+            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,y: vector_function(t,x=x,y=y)[0]
+            #phi = lambda t,x,y: vector_function(t,x=x,y=y)[1]
+            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
+        #ymom_update = domain.quantities['ymomentum'].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[:,0], xc[:,1])
+            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[:,0], xc[:,1])
+            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 * sqrt(u**2 + v**2)
+        S = const * u
+        xmom_update[k] += S*u
+        #ymom_update[k] += S*v
Index: /anuga_work/development/shallow_water_1d/steady_flow.py
===================================================================
--- /anuga_work/development/shallow_water_1d/steady_flow.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/steady_flow.py	(revision 4959)
@@ -0,0 +1,179 @@
+import os
+import Gnuplot
+from math import sqrt, pi
+from shallow_water_1d import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+#h_0 = 0.48
+#u_0 = 0.625
+#h_1 = 0.48
+#u_1 = 0.625
+
+#h_0 = 0.48
+#u_0 = 0.625
+#h_1 = 0.106
+#u_1 = 2.829228
+
+h_0 = 0.5
+u_0 = 0.6
+h_1 = 0.5
+u_1 = 0.6
+g = 9.81
+
+#h_c = (q**2/g)**(1/3)
+#u_c = sqrt(g*h_c)
+
+q = 0.3
+g = 9.81
+
+b = 4.0
+xmax = 25.0
+z_bmax = 0.2
+Fr_0 = u_0/sqrt(g*h_0)
+
+def stage(x):
+    y,u,h = analytical_sol(x)
+    return y
+    
+
+def elevation(x):
+    b = 4.0
+    xmax = 25.0
+    z_bmax = 0.2
+    z_b = zeros(len(x),Float)
+    for i in range(len(x)):
+        if (x[i] >= xmax-b) & (x[i] <= xmax+b):
+            z_b[i] = z_bmax*(1.0-(x[i]-xmax)**2/b**2)
+        else:
+            z_b[i] = 0.0 
+    return z_b
+    #return 0.0
+
+def xmomentum(x):
+    return u_0*h_0
+
+
+def bisection(func,xR,xL,H):
+    while ((xR - xL) > epsilon):
+  
+        #Calculate midpoint of domain
+        xM = xL + (xR - xL) / 2.0
+  
+        #Find f(xM)
+        if ((f(xL,H) * f(xM,H)) > 0):
+            #Throw away left half
+            xL = xM
+        else:
+            #Throw away right half
+            xR = xM
+    return xR
+
+def f(D,H):
+    return D**3+D**2*(H-1.0-Fr_0**2/2.0)+Fr_0**2/2.0
+
+def fprime(D,H):
+    Fr_0 = u_0/sqrt(g*h_0)
+    return 3*D**2+2*D*(H-1-Fr_0**2/2.0)
+
+def analytical_sol(x):
+    y = zeros(len(x),Float)
+    u = zeros(len(x),Float)
+    height = zeros(len(x),Float)
+    for i in range(len(x)):
+        if (x[i] >= xmax-b) & (x[i] <= xmax+b):
+            zb = z_bmax*(1.0-(x[i]-xmax)**2/b**2)
+        else:
+            zb = 0.0 
+
+        H = zb/h_0
+        y1 = bisection(f,1.0,0.2/0.5,H)
+        height[i] = y1*h_0
+        y[i] = height[i]+zb
+        u[i] = q/(height[i])
+        
+
+    return y,u,height
+
+Fr_0 = u_0/sqrt(g*h_0)
+zb=0.2
+H = zb/h_0
+D = bisection(f,1,0.2/0.5,H)
+
+L = 50.0
+N = 50 #800
+cell_len = L/N
+points = zeros(N+1,Float)
+for j in range(N+1):
+    points[j] = j*cell_len
+boundary = { (0,0): 'left',(N-1,1): 'right'}
+domain = Domain(points,boundary)
+D1 = Dirichlet_boundary([h_0,u_0*h_0])
+D2 = Dirichlet_boundary([h_1,u_1*h_1])
+domain.set_boundary({'left':D1,'right':D2})
+domain.set_quantity('elevation',elevation)
+domain.set_quantity('stage',stage)
+domain.set_quantity('xmomentum',xmomentum)
+X = domain.vertices
+C = domain.centroids
+
+Stage = domain.quantities['stage']
+Xmom = domain.quantities['xmomentum']
+
+StageQ = Stage.vertex_values
+StageC = Stage.centroid_values
+XmomQ = Xmom.vertex_values
+XmomC = Xmom.centroid_values
+ElevationQ = domain.quantities['elevation'].vertex_values
+
+stage_bdry = Stage.boundary_values
+xmom_bdry =  Xmom.boundary_values
+
+w,u,h = analytical_sol(X.flat)
+wc, uc, hc = analytical_sol(C)
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot,ylim,xlim, rc
+hold(False)
+rc('text', usetex=True)
+h_error = zeros(1,Float)
+uh_error = zeros(1,Float)
+k = 0
+yieldstep = 25.0
+finaltime = 25.0
+domain.limiter = "vanleer"
+#domain.limiter = "steve_minmod"
+domain.default_order = 2
+domain.default_time_order = 2#check order is not working
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+print 'Test 1'    
+plot1 = subplot(211)
+print 'Test 2'
+plot(X,w,X,StageQ,X,ElevationQ)
+print 'Test 3'
+#xlabel('Position')
+#ylabel('Stage (m)')
+#legend(('Analytical Solution', 'Numerical Solution', 'Channel Bed'),
+#       'upper right', shadow=True)
+plot1.set_ylim([-0.1,1.0])
+print 'Test 4'
+plot2 = subplot(212)
+print 'Test 5'
+plot(X,u*h,X,XmomQ)#/(StageQ-ElevationQ))
+print 'Test 6'
+#xlabel('x (m)')
+#ylabel(r'X-momentum ($m^2/s$)')
+h_error[k] = 1.0/(N)*sum(abs(wc-StageC))
+uh_error[k] = 1.0/(N)*sum(abs(uc*hc-XmomC))
+print "h_error %.10f" %(h_error[k])
+print "uh_error %.10f"% (uh_error[k])
+print "h_max %.10f"%max(wc-StageC)
+print "uh max  %.10f"%max(uc*hc-XmomC)
+filename = "steady_flow_"
+filename += domain.limiter
+filename += str(400)
+filename += ".ps"
+#savefig(filename)
+show()
+
Index: /anuga_work/development/shallow_water_1d/subcritical_single.py
===================================================================
--- /anuga_work/development/shallow_water_1d/subcritical_single.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/subcritical_single.py	(revision 4959)
@@ -0,0 +1,115 @@
+import os
+from math import sqrt, pi
+from shallow_water_1d import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+from analytic_dam import AnalyticDam
+
+
+h0 = 5.0
+h1 = 10.0
+
+analytical_sol = AnalyticDam(h0, h1)
+
+def newLinePlot(title='Simple Plot'):
+    import Gnuplot
+    g = Gnuplot.Gnuplot(persist=1)
+    g.title(title)
+    g('set data style linespoints') 
+    g.xlabel('x')
+    g.ylabel('y')
+    return g
+
+def linePlot(g,x1,y1,x2,y2):
+    import Gnuplot
+    plot1 = Gnuplot.PlotItems.Data(x1.flat,y1.flat,with="linespoints")
+    plot2 = Gnuplot.PlotItems.Data(x2.flat,y2.flat, with="lines 3")
+    g.plot(plot1,plot2)
+    #g.plot(Gnuplot.PlotItems.Data(x1.flat,y1.flat),with="linespoints")
+    #g.plot(Gnuplot.PlotItems.Data(x2.flat,y2.flat), with="lines")
+
+def stage(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        if x[i]<=1000.0:
+            y[i] = h1
+        else:
+            y[i] = h0
+    return y
+
+
+import time
+finaltime = 30.0
+yieldstep = finaltime
+
+L = 2000.0     # Length of channel (m)
+#number_of_cells = [25,50,100,200,400,800,1600,3200,6400,12800,25600]
+number_of_cells = [20]
+h_error = zeros(len(number_of_cells),Float)
+uh_error = zeros(len(number_of_cells),Float)
+k = 0
+for i in range(len(number_of_cells)):
+    N = int(number_of_cells[i])
+    print "Evaluating domain with",N,"cells"
+    cell_len = L/N # Origin = 0.0
+    points = zeros(N+1,Float)
+    for j in range(N+1):
+        points[j] = j*cell_len
+    domain = Domain(points)
+    domain.set_quantity('stage', stage)
+    domain.set_boundary({'exterior': Reflective_boundary(domain)})
+    domain.default_order = 2
+    domain.default_time_order = 2
+    print "time order", domain.default_time_order
+    domain.cfl = 1.0
+    domain.beta = 1.0
+    domain.limiter = "steve_minmod"
+    #domain.limiter = "superbee"
+    init_integral = domain.quantities['stage'].get_integral()
+    t0 = time.time()
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        pass
+    N = float(N)
+    assert(allclose(domain.quantities['stage'].get_integral(),init_integral))
+    StageC = domain.quantities['stage'].centroid_values
+    XmomC = domain.quantities['xmomentum'].centroid_values
+    C = domain.centroids
+    h, uh = analytical_sol(C,domain.time)
+    h_error[k] = 1.0/(N)*sum(abs(h-StageC))
+    uh_error[k] = 1.0/(N)*sum(abs(uh-XmomC))
+    print "h_error %.10f" %(h_error[k])
+    print "uh_error %.10f"% (uh_error[k])
+    k = k+1
+    print 'That took %.2f seconds' %(time.time()-t0)
+    X = domain.vertices
+    StageQ = domain.quantities['stage'].vertex_values
+    XmomQ = domain.quantities['xmomentum'].vertex_values
+    h, uh = analytical_sol(X.flat,domain.time)
+    from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot#,rc
+    #rc('text', usetex=True)
+    hold(False)
+    plot1 = subplot(211)
+    plot(X,h,X,StageQ)
+    plot1.set_ylim([4,11])
+    #title('Free Surface Elevation of a Dry Dam-Break')
+    #ylabel('Stage (m)')
+    #legend(('Analytical Solution', 'Numerical Solution'),
+    #       'upper right', shadow=True)
+    #plot2 = subplot(212)
+    #plot(X,uh,X,XmomQ)
+    #plot2.set_ylim([-1,25])
+    #title('Xmomentum Profile of a Dry Dam-Break')
+    #xlabel('x (m)')
+    #ylabel(r'X-momentum ($m^2/s$)')
+    #legend(('Analytical Solution', 'Numerical Solution'),
+    #       'upper right', shadow=True)
+    #filename = "subcritical_flow_s2_t2_"
+    #filename += domain.limiter
+    #filename += str(number_of_cells[i])
+    #filename += ".eps"
+    #savefig(filename)
+    show()
+
+print "Error in height", h_error
+print "Error in xmom", uh_error
+
Index: /anuga_work/development/shallow_water_1d/util.py
===================================================================
--- /anuga_work/development/shallow_water_1d/util.py	(revision 4959)
+++ /anuga_work/development/shallow_water_1d/util.py	(revision 4959)
@@ -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
