Index: trunk/anuga_work/development/2010-projects/anuga_1d/__init__.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/__init__.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/__init__.py	(revision 7884)
@@ -0,0 +1,9 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="Stephen Roberts"
+__date__ ="$14/06/2010 7:50:20 PM$"
+
+pass
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/__init__.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/__init__.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/__init__.py	(revision 7884)
@@ -0,0 +1,9 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="Stephen Roberts"
+__date__ ="$14/06/2010 7:50:20 PM$"
+
+pass
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/config.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/config.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/config.py	(revision 7884)
@@ -0,0 +1,112 @@
+"""Module where global model parameters are set for anuga_1d
+"""
+
+epsilon = 1.0e-12
+h0 = 1.0e-12
+
+default_boundary_tag = 'exterior'
+
+
+time_format = '%d/%m/%y %H:%M:%S'
+
+min_timestep = 1.0e-6 #Should be computed based on geometry
+max_timestep = 1.0e3
+max_smallsteps = 50  # Max number of degenerate steps allowed b4 trying first order
+#This is how:
+#Define maximal possible speed in open water v_max, e.g. 500m/s (soundspeed?)
+#Then work out minimal internal distance in mesh r_min and set
+#min_timestep = r_min/v_max
+#
+#Max speeds are calculated in the flux function as
+#
+#lambda = v +/- sqrt(gh)
+#
+# so with 500 m/s, h ~ 500^2/g = 2500 m well out of the domain of the
+# shallow water wave equation
+#
+#The actual soundspeed can be as high as 1530m/s
+#(see http://staff.washington.edu/aganse/public.projects/clustering/clustering.html),
+#but that would only happen with h>225000m in this equation. Why ?
+#The maximal speed we specify is really related to the max speed
+#of surface pertubation
+#
+
+
+v_max = 100 #For use in domain_ext.c
+sound_speed = 500
+
+
+max_smallsteps = 50  #Max number of degenerate steps allowed b4 trying first order
+
+manning = 0.0  #Manning's friction coefficient
+g = 9.8       #Gravity
+#g(phi) = 9780313 * (1 + 0.0053024 sin(phi)**2 - 0.000 0059 sin(2*phi)**2) micro m/s**2, where phi is the latitude
+#The 'official' average is 9.80665
+
+
+
+
+eta_w = 3.0e-3 #Wind stress coefficient
+rho_a = 1.2e-3 #Atmospheric density
+rho_w = 1023   #Fluid density [kg/m^3] (rho_w = 1023 for salt water)
+
+
+#Betas [0;1] control the allowed steepness of gradient for second order
+#extrapolations. Values of 1 allow the steepes gradients while
+#lower values are more conservative. Values of 0 correspond to
+#1'st order extrapolations.
+#
+# Large values of beta_h may cause simulations to require more timesteps
+# as surface will 'hug' closer to the bed.
+# Small values of beta_h will make code faster, but one may experience
+# artificial momenta caused by discontinuities in water depths in
+# the presence of steep slopes. One example of this would be
+# stationary water 'lapping' upwards to a higher point on the coast.
+#
+#
+#
+#There are separate betas for the w-limiter and the h-limiter
+#
+#
+#
+#
+#Good values are:
+#beta_w = 0.9
+#beta_h = 0.2
+
+
+
+beta_w = 1.5
+beta_h = 0.2
+timestepping_method = 'euler'
+
+CFL = 1.0  #FIXME (ole): Is this in use yet??
+           #(Steve) yes, change domain.CFL to
+           #make changes
+
+
+pmesh_filename = '.\\pmesh'
+
+
+import os, sys
+
+if sys.platform == 'win32':
+    #default_datadir = 'C:\grohm_output'
+    default_datadir = '.'
+else:
+    #default_datadir = os.path.expanduser('~'+os.sep+'grohm_output')
+    default_datadir = '.'
+
+
+use_extensions = True    #Try to use C-extensions
+#use_extensions = False   #Do not use C-extensions
+
+use_psyco = True  #Use psyco optimisations
+#use_psyco = False  #Do not use psyco optimisations
+
+
+optimised_gradient_limiter = True #Use hardwired gradient limiter
+
+#Specific to shallow water W.E.
+h_min = minimum_allowed_height = 1.0e-6 #1.0e-6 #Water depth below which it is considered to be 0
+maximum_allowed_speed = 1000.0
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_boundary_conditions.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_boundary_conditions.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_boundary_conditions.py	(revision 7884)
@@ -0,0 +1,498 @@
+"""boundary.py - Classes for implementing boundary conditions
+"""
+
+import numpy
+
+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
+
+        self.conserved_quantities=numpy.array(conserved_quantities, numpy.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
+
+        try:
+            q = numpy.array(q, numpy.float)
+        except:
+            msg = 'Return value from time boundary function could '
+            msg += 'not be converted into a numpy array of numpy.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 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 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 = numpy.zeros( (len(domain.boundary), 2), numpy.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 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(numpy.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 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 = numpy.zeros(N, numpy.float)
+        Q = numpy.zeros((N, d), numpy.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] = numpy.float(value)
+
+        msg = 'Time boundary must list time as a monotonuosly '
+        msg += 'increasing sequence'
+
+        assert alltrue( T[1:] - T[:-1] > 0 ), msg
+
+        self.T = T     #Time
+        self.Q = Q     #Boundary values
+        self.index = 0 #Initial index
+
+
+    def __repr__(self):
+        return 'File boundary'
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        """Return linearly interpolated values based on domain.time
+        """
+
+        t = self.domain.time
+
+        msg = 'Time given in File boundary does not match model time'
+        if t < self.T[0]: raise msg
+        if t > self.T[-1]: raise msg
+
+        oldindex = self.index
+
+        #Find slot
+        while t > self.T[self.index]: self.index += 1
+        while t < self.T[self.index]: self.index -= 1
+
+        #if oldindex != self.index:
+        #    print 'Changing from %d to %d' %(oldindex, self.index)
+
+
+        #t is now between index and index+1
+        ratio = (t - self.T[self.index])/\
+                (self.T[self.index+1] - self.T[self.index])
+
+        return self.Q[self.index,:] +\
+               ratio*(self.Q[self.index+1,:] - self.Q[self.index,:])
+
+
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_domain.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_domain.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_domain.py	(revision 7884)
@@ -0,0 +1,1422 @@
+"""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
+"""
+
+import numpy
+from generic_boundary_conditions import *
+
+
+class Generic_domain:
+
+    def __init__(self,
+                 coordinates,
+                 boundary = None,
+                 conserved_quantities = [],
+                 evolved_quantities = [],
+                 other_quantities = [],
+                 tagged_elements = None):
+        """
+        Build 1D elements from x coordinates
+        """
+
+        from config import timestepping_method
+        from config import CFL
+        
+        #Store Points
+        self.coordinates = numpy.array(coordinates, numpy.float)
+
+
+        #Register number of Elements
+        self.number_of_elements = N = len(self.coordinates)-1
+
+        self.set_CFL(CFL)
+        self.set_timestepping_method(timestepping_method)
+
+
+        # work array for special vertices (like wet or dry cells
+        self.special_vertices = numpy.zeros((N,2), numpy.int) # should this be here
+
+        #Allocate space for neighbour and boundary structures
+        self.neighbours = numpy.zeros((N, 2), numpy.int)
+        #self.neighbour_edges = numpy.zeros((N, 2), numpy.int)
+        self.neighbour_vertices   = numpy.zeros((N, 2), numpy.int)
+        self.number_of_boundaries = numpy.zeros(N, numpy.int)
+        self.surrogate_neighbours = numpy.zeros((N, 2), numpy.int)
+        
+        #Allocate space for geometric quantities
+        self.vertices  = numpy.zeros((N, 2), numpy.float)
+        self.centroids = numpy.zeros(N, numpy.float)
+        self.areas     = numpy.zeros(N, numpy.float)
+
+        self.max_speed_array = numpy.zeros(N, numpy.float)
+      
+
+        self.normals = numpy.zeros((N, 2), numpy.float)
+
+
+        xl = self.coordinates[0:-1]
+        xr = self.coordinates[1: ]
+
+        self.vertices[:,0] = xl
+        self.vertices[:,1] = xr
+
+        self.centroids[:] = (xl+xr)/2.0
+
+        msg = 'Coordinates should be ordered, smallest to largest'
+        assert (xr>xl).all(), 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
+
+
+        self.normals[:,0] = -1.0
+        self.normals[:,1] =  1.0
+
+        self.areas[:] = (xr-xl)
+
+        #Initialise Neighbours (-1 means that it is a boundary neighbour)
+
+        self.neighbours[:, :] = -1
+
+        #Initialise edge ids of neighbours
+        self.neighbour_vertices[:, :] = -1
+
+
+#        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, 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
+        #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 evolved_quantities is None:
+            self.evolved_quantities = self.conserved_quantities
+        else:
+            self.evolved_quantities = evolved_quantities
+
+        if other_quantities is None:
+            self.other_quantities = []
+        else:
+            self.other_quantities = other_quantities
+
+
+        #Build dictionary of Quantity instances keyed by quantity names
+        self.quantities = {}
+
+        #print self.conserved_quantities
+        #print self.evolved_quantities
+        
+
+        #FIXME: remove later - maybe OK, though....
+        for name in self.evolved_quantities:
+            self.quantities[name] = Quantity(self)
+        for name in self.other_quantities:
+            self.quantities[name] = Quantity(self)
+
+        #Create an empty list for explicit forcing terms
+        self.forcing_terms = []
+
+        #Defaults
+        from config import max_smallsteps, beta_w, beta_h, epsilon, CFL
+        self.beta_w = beta_w
+        self.beta_h = beta_h
+        self.epsilon = epsilon
+
+        #FIXME: Maybe have separate orders for h-limiter and w-limiter?
+        #Or maybe get rid of order altogether and use beta_w and beta_h
+        self.default_order = 1
+        self.order = self.default_order
+
+        self.default_time_order = 1
+        self.time_order = self.default_time_order
+        
+        self.smallsteps = 0
+        self.max_smallsteps = max_smallsteps
+        self.number_of_steps = 0
+        self.number_of_first_order_steps = 0
+
+        #Model time
+        self.time = 0.0
+        self.finaltime = None
+        self.min_timestep = self.max_timestep = 0.0
+        self.starttime = 0 #Physical starttime if any (0 is 1 Jan 1970 00:00:00)
+        #Checkpointing and storage
+        from config import default_datadir
+        self.set_datadir(default_datadir)
+        self.filename = 'domain'
+        self.checkpoint = False
+
+    def __len__(self):
+        return self.number_of_elements
+
+    def build_vertexlist(self):
+        """Build vertexlist index by vertex ids and for each entry (point id)
+        build a list of (triangles, vertex_id) pairs that use the point
+        as vertex.
+
+        Preconditions:
+          self.coordinates and self.triangles are defined
+
+        Postcondition:
+          self.vertexlist is built
+        """
+
+        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
+        """
+
+        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(numpy.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 set_quantities_to_be_stored(self, q):
+        """Specify which quantities will be stored in the sww file.
+
+        q must be either:
+          - the name of a quantity
+          - a list of quantity names
+          - None
+
+        In the two first cases, the named quantities will be stored at each
+        yieldstep
+        (This is in addition to the quantities elevation and friction)  
+        If q is None, storage will be switched off altogether.
+        """
+
+
+        if q is None:
+            self.quantities_to_be_stored = []            
+            self.store = False
+            return
+
+        if isinstance(q, basestring):
+            q = [q] # Turn argument into a list
+
+        #Check correcness    
+        for quantity_name in q:
+            msg = 'Quantity %s is not a valid conserved quantity' %quantity_name
+            assert quantity_name in self.conserved_quantities, msg 
+        
+        self.quantities_to_be_stored = q
+        
+
+
+
+
+    def get_boundary_tags(self):
+        """Return list of available boundary tags
+        """
+
+        tags = {}
+        for v in self.boundary.values():
+            tags[v] = 1
+
+        return tags.keys()
+        
+    def get_vertex_coordinates(self, obj = False):
+        """Return all vertex coordinates.
+        Return all vertex coordinates for all triangles as an Nx6 array
+        (ordered as x0, y0, x1, y1, x2, y2 for each triangle)
+
+        if obj is True, the x/y pairs are returned in a 3*N x 2 array.
+        FIXME, we might make that the default.
+        FIXME Maybe use keyword: continuous = False for this condition?
+
+        
+        """
+
+        if obj is True:
+        
+            #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 numpy.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
+
+        """
+
+        #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 = numpy.zeros( len(self.conserved_quantities), numpy.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_evolved_quantities(self, vol_id, vertex=None):#, edge=None):
+        """Get evolved quantities at volume vol_id
+
+        If vertex is specified use it as index for vertex values
+        If edge is specified use it as index for edge values
+        If neither are specified use centroid values
+        If both are specified an exeception is raised
+
+        Return value: Vector of length == number_of_evolved quantities
+
+        """
+
+
+
+        #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 = numpy.zeros( len(self.evolved_quantities), numpy.float)
+
+        for i, name in enumerate(self.evolved_quantities):
+            Q = self.quantities[name]
+            if vertex is not None:
+                q[i] = Q.vertex_values[vol_id, vertex]
+            #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=None):
+        """Return area of element id
+        """
+
+        if elem_id is None:
+            return sum(self.areas)
+        else:
+            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 numpyal array of length N, N being the number
+        of elements. Otherwise it must be of dimension Nx3.
+
+        Indices is the set of element ids that the operation applies to.
+
+        The values will be stored in elements following their
+        internal ordering.
+        """
+
+        return self.quantities[name].get_values( location, indices = indices)
+
+    def get_centroid_coordinates(self):
+        """Return all centroid coordinates.
+        Return all centroid coordinates for all triangles as an Nx2 array
+        (ordered as x0, y0 for each triangle)
+        """
+        return self.centroids
+
+
+    def get_timestepping_method(self):
+        return self.timestepping_method
+
+    def set_timestepping_method(self,timestepping_method):
+        
+        if timestepping_method in ['euler', 'rk2', 'rk3']:
+            self.timestepping_method = timestepping_method
+            return
+
+        if timestepping_method in [1, 2, 3]:
+            self.timestepping_method = ['euler', 'rk2', 'rk3'][timestepping_method-1]
+            return
+
+        msg = '%s is an incorrect timestepping type'% timestepping_method
+        raise Exception, msg
+
+
+    def set_quantity(self, name, *args, **kwargs):
+        """Set values for named quantity
+
+
+        One keyword argument is documented here:
+        expression = None, # Arbitrary expression
+
+        expression:
+          Arbitrary expression involving quantity names
+
+        See Quantity.set_values for further documentation.
+        """
+
+        #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 Exception, msg
+
+
+
+    def check_integrity(self):
+        #Mesh.check_integrity(self)
+
+        #print self.quantities
+        #print self.conserved_quantities
+        
+        for quantity in self.conserved_quantities:
+            msg = 'Conserved quantities must be a subset of all quantities'
+            assert quantity in self.quantities, msg
+
+        for quantity in self.evolved_quantities:
+            msg = 'Evolved quantities must be a subset of all quantities'
+            assert quantity in self.quantities, msg            
+
+        # #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
+
+    def set_CFL(self, cfl):
+        if cfl > 1.0:
+            print 'WARNING: Setting CFL condition to %f which is greater than 1' % cfl
+        self.CFL = cfl
+
+    def get_CFL(self):
+        return self.CFL
+    
+    def set_filename(self, name):
+        self.filename = name
+
+    def get_filename(self):
+        return self.filename
+
+
+    def get_spatial_order(self):
+        return self.order
+
+    def set_spatial_order(self, order):
+
+        possible_orders = [1,2]
+
+        if order in possible_orders:
+            self.order = order
+            return
+
+        msg = '%s is an incorrect spatial order.\n'% limiter
+        msg += 'Possible orders are: '+ ", ".join(["%s" % el for el in possible_orders])
+        raise Exception, msg
+    
+
+    def get_beta(self):
+
+        warn('limiter parameter beta associated with quantity not domain')
+
+    def set_beta(self,beta):
+        """Set the same limiter beta parameter to all evolving quantities
+        """
+
+        for name in self.evolved_quantities:
+            Q = self.quantities[name]
+            Q.set_beta(beta)
+
+
+    def get_limiter(self):
+
+        warn('limiter associated with quantity not domain')
+
+    def set_limiter(self,limiter):
+
+        for name in self.evolved_quantities:
+            Q = self.quantities[name]
+            Q.set_limiter(limiter)
+        
+
+        
+    #--------------------------
+    # Main components of evolve
+    #--------------------------    
+
+    def evolve(self, yieldstep = None,
+               finaltime = None,
+               duration = None,
+               skip_initial_step = False):
+        """Evolve model through time starting from self.starttime.
+
+
+        yieldstep: numpy.interval between yields where results are stored,
+                   statistics written and domain inspected or
+                   possibly modified. If omitted the internal predefined
+                   max timestep is used.
+                   numpy.internally, smaller timesteps may be taken.
+
+        duration: Duration of simulation
+
+        finaltime: Time where simulation should end. This is currently
+        relative time.  So it's the same as duration.
+
+        If both duration and finaltime are given an exception is thrown.
+
+
+        skip_initial_step: Boolean flag that decides whether the first
+        yield step is skipped or not. This is useful for example to avoid
+        duplicate steps when multiple evolve processes are dove tailed.
+
+
+        Evolve is implemented as a generator and is to be called as such, e.g.
+
+        for t in domain.evolve(yieldstep, finaltime):
+            <Do something with domain and t>
+
+
+        All times are given in seconds
+
+        """
+
+        from config import min_timestep, max_timestep, epsilon
+
+        # FIXME: Maybe lump into a larger check prior to evolving
+        msg = 'Boundary tags must be bound to boundary objects before '
+        msg += 'evolving system, '
+        msg += 'e.g. using the method set_boundary.\n'
+        msg += 'This system has the boundary tags %s '\
+               %self.get_boundary_tags()
+        assert hasattr(self, 'boundary_objects'), msg
+
+
+        if yieldstep is None:
+            yieldstep = max_timestep
+        else:
+            yieldstep = numpy.float(yieldstep)
+
+        self._order_ = self.default_order
+
+
+        if finaltime is not None and duration is not None:
+            # print 'F', finaltime, duration
+            msg = 'Only one of finaltime and duration may be specified'
+            raise msg
+        else:
+            if finaltime is not None:
+                self.finaltime = numpy.float(finaltime)
+            if duration is not None:
+                self.finaltime = self.starttime + numpy.float(duration)
+
+
+
+        N = len(self) # Number of triangles
+        self.yieldtime = 0.0 # Track time between 'yields'
+
+        # Initialise interval of timestep sizes (for reporting only)
+        self.min_timestep = max_timestep
+        self.max_timestep = min_timestep
+        self.number_of_steps = 0
+        self.number_of_first_order_steps = 0
+
+
+        # Update ghosts
+        self.update_ghosts()
+
+        # Initial update of vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update extrema if necessary (for reporting)
+        self.update_extrema()
+        
+        # Initial update boundary values
+        self.update_boundary()
+
+        # Or maybe restore from latest checkpoint
+        if self.checkpoint is True:
+            self.goto_latest_checkpoint()
+
+        if skip_initial_step is False:
+            yield(self.time)  # Yield initial values
+
+        while True:
+
+            # Evolve One Step, using appropriate timestepping method
+            if self.get_timestepping_method() == 'euler':
+                self.evolve_one_euler_step(yieldstep,finaltime)
+                
+            elif self.get_timestepping_method() == 'rk2':
+                self.evolve_one_rk2_step(yieldstep,finaltime)
+
+            elif self.get_timestepping_method() == 'rk3':
+                self.evolve_one_rk3_step(yieldstep,finaltime)               
+
+            
+            # Update extrema if necessary (for reporting)
+            self.update_extrema()            
+
+
+            
+            self.yieldtime += self.timestep
+            self.number_of_steps += 1
+            if self._order_ == 1:
+                self.number_of_first_order_steps += 1
+
+
+            # Yield results
+            if finaltime is not None and self.time >= finaltime-epsilon:
+
+                if self.time > finaltime:
+                    # FIXME (Ole, 30 April 2006): Do we need this check?
+                    # Probably not (Ole, 18 September 2008). Now changed to
+                    # Exception
+                    msg = 'WARNING (domain.py): time overshot finaltime. '
+                    msg += 'Contact Ole.Nielsen@ga.gov.au'
+                    raise Exception, msg
+                    
+
+                # Yield final time and stop
+                self.time = finaltime
+                yield(self.time)
+                break
+
+            if self.yieldtime >= yieldstep:
+                # Yield (intermediate) time and allow inspection of domain
+
+                if self.checkpoint is True:
+                    self.store_checkpoint()
+                    self.delete_old_checkpoints()
+
+                # Pass control on to outer loop for more specific actions
+
+                yield(self.time)
+
+                # Reinitialise
+                self.yieldtime = 0.0
+                self.min_timestep = max_timestep
+                self.max_timestep = min_timestep
+                self.number_of_steps = 0
+                self.number_of_first_order_steps = 0
+                #self.max_speed_array = 0.0
+
+
+    def evolve_one_euler_step(self, yieldstep, finaltime):
+        """
+        One Euler Time Step
+        Q^{n+1} = E(h) Q^n
+        """
+
+
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Update time
+        self.time += self.timestep
+
+        
+
+
+    def evolve_one_rk2_step(self, yieldstep, finaltime):
+        """
+        One 2nd order RK timestep
+        Q^{n+1} = 0.5 Q^n + 0.5 E(h)^2 Q^n
+        """
+
+        # Save initial conserved quantities values
+        self.backup_conserved_quantities()            
+
+        #--------------------------------------
+        # First euler step
+        #--------------------------------------
+
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Update time
+        self.time += self.timestep
+
+        #------------------------------------
+        # Second Euler step
+        #------------------------------------
+            
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        #------------------------------------
+        # Combine initial and final values
+        # of conserved quantities and cleanup
+        #------------------------------------
+        
+        # Combine steps
+        self.saxpy_conserved_quantities(0.5, 0.5)
+
+        #-----------------------------------
+        # clean up vertex values
+        #-----------------------------------
+ 
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+
+
+    def evolve_one_rk3_step(self, yieldstep, finaltime):
+        """
+        One 3rd order RK timestep
+        Q^(1) = 3/4 Q^n + 1/4 E(h)^2 Q^n  (at time t^n + h/2)
+        Q^{n+1} = 1/3 Q^n + 2/3 E(h) Q^(1) (at time t^{n+1})
+        """
+
+        # Save initial initial conserved quantities values
+        self.backup_conserved_quantities()            
+
+        initial_time = self.time
+        
+        #--------------------------------------
+        # First euler step
+        #--------------------------------------
+
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update timestep to fit yieldstep and finaltime
+        self.update_timestep(yieldstep, finaltime)
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Update time
+        self.time += self.timestep
+
+        #------------------------------------
+        # Second Euler step
+        #------------------------------------
+            
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        #------------------------------------
+        #Combine steps to obtain intermediate
+        #solution at time t^n + 0.5 h
+        #------------------------------------
+
+        # Combine steps
+        self.saxpy_conserved_quantities(0.25, 0.75)
+ 
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Set substep time
+        self.time = initial_time + self.timestep*0.5
+
+        #------------------------------------
+        # Third Euler step
+        #------------------------------------
+            
+        # Compute fluxes across each element edge
+        self.compute_fluxes()
+
+        # Update conserved quantities
+        self.update_conserved_quantities()
+
+        #------------------------------------
+        # Combine final and initial values
+        # and cleanup
+        #------------------------------------
+        
+        # Combine steps
+        self.saxpy_conserved_quantities(2.0/3.0, 1.0/3.0)
+ 
+        # Update ghosts
+        self.update_ghosts()
+
+        # Update vertex and edge values
+        self.distribute_to_vertices_and_edges()
+
+        # Update boundary values
+        self.update_boundary()
+
+        # Set new time
+        self.time = initial_time + self.timestep       
+        
+
+    def backup_conserved_quantities(self):
+        N = len(self) # Number_of_triangles
+
+        # Backup conserved_quantities centroid values
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            Q.backup_centroid_values()        
+
+    def saxpy_conserved_quantities(self,a,b):
+        N = len(self) #number_of_triangles
+
+        # Backup conserved_quantities centroid values
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            Q.saxpy_centroid_values(a,b)        
+
+
+
+        
+    def 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_ghosts(self):
+        pass
+    
+    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)
+            #print 'q ',q
+            for j, name in enumerate(self.evolved_quantities):
+                #print 'name %s j = %f \n'%(name,j)
+                Q = self.quantities[name]
+
+                Q.boundary_values[i] = q[j]
+                #print 'Q=',Q
+    
+    def update_timestep(self, yieldstep, finaltime):
+
+        from config import min_timestep, max_timestep
+
+        # self.timestep is calculated from speed of characteristics
+        # Apply CFL condition here
+        timestep = min(self.CFL*self.flux_timestep, max_timestep)
+
+        #Record maximal and minimal values of timestep for reporting
+        self.max_timestep = max(timestep, self.max_timestep)
+        self.min_timestep = min(timestep, self.min_timestep)
+
+        #Protect against degenerate time steps
+        if timestep < min_timestep:
+
+            #Number of consecutive small steps taken b4 taking action
+            self.smallsteps += 1
+
+            if self.smallsteps > self.max_smallsteps:
+                self.smallsteps = 0 #Reset
+
+                if self.order == 1:
+                    msg = 'WARNING: Too small timestep %.16f reached '\
+                          %timestep
+                    msg += 'even after %d steps of 1 order scheme'\
+                           %self.max_smallsteps
+                    print msg
+                    timestep = min_timestep  #Try enforcing min_step
+
+                    #raise msg
+                else:
+                    #Try to overcome situation by switching to 1 order
+                    print "changing Order 1"
+                    self.order = 1
+
+        else:
+            self.smallsteps = 0
+            if self.order == 1 and self.default_order == 2:
+                self.order = 2
+
+
+        #Ensure that final time is not exceeded
+        if finaltime is not None and self.time + timestep > finaltime:
+            timestep = finaltime-self.time
+
+        #Ensure that model time is aligned with yieldsteps
+        if self.yieldtime + timestep > yieldstep:
+            timestep = yieldstep-self.yieldtime
+
+        self.timestep = timestep
+
+    def update_extrema(self):
+        pass
+
+    def compute_forcing_terms(self):
+        """If there are any forcing functions driving the system
+        they should be defined in Domain subclass and appended to
+        the list self.forcing_terms
+        """
+        #Clears explicit_update needed for second order method
+        if self.time_order == 2:
+            for name in self.conserved_quantities:
+                Q = self.quantities[name]
+                Q.explicit_update[:] = 0.0
+
+        for f in self.forcing_terms:
+            f(self)
+            
+
+    def update_derived_quantites(self):
+        pass
+    
+    #def update_conserved_quantities(self):
+    def update_conserved_quantities(self):
+        """Update vectors of conserved quantities using previously
+        computed fluxes specified forcing functions.
+        """
+
+
+        timestep = self.timestep
+
+        #Compute forcing terms
+        self.compute_forcing_terms()
+
+        #Update conserved_quantities
+        for name in self.conserved_quantities:
+            Q = self.quantities[name]
+            Q.update(timestep)
+
+
+
+if __name__ == "__main__":
+
+    points1 = [0.0, 1.0, 2.0, 3.0]
+    D1 = Domain(points1)
+
+    print D1.get_coordinate(0)
+    print D1.get_coordinate(0,1)
+    print 'Number of Elements = ',D1.number_of_elements
+
+    try:
+        print D1.get_coordinate(3)
+    except:
+        pass
+    else:
+        msg =  'Should have raised an out of bounds exception'
+        raise msg
+
+    #points2 = [0.0, 1.0, 2.0, 3.0, 2.5]
+    #D2 = Domain(points2)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_mesh.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_mesh.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/generic_mesh.py	(revision 7884)
@@ -0,0 +1,23 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="steve"
+__date__ ="$15/06/2010 3:08:41 PM$"
+
+
+import numpy
+
+def uniform_mesh(n, x_0=0.0, x_1=1.0):
+    """Create points, and boundary for a uniform mesh with n sub-interval
+    ranging from x_0 to x_1
+    """
+
+    assert n>0
+
+
+    points  = x_0 + (x_1 - x_0)*numpy.arange(n+1,dtype=numpy.float)/n
+    boundary = {(0, 0): 'left', (n-1, 1): 'right'}
+
+    return points, boundary
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/limiters_python.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/limiters_python.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/limiters_python.py	(revision 7884)
@@ -0,0 +1,90 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="steve"
+__date__ ="$16/06/2010 4:29:59 PM$"
+
+
+
+def  minmod(a,b):
+    from numpy import abs, where
+
+    phi = where((abs(a) < abs(b)) & (a*b > 0.0), a, 0.0)
+    phi = where((abs(b) < abs(a)) & (a*b > 0.0), b, phi)
+
+    return phi
+
+def  minmod_kurganov(a,b,c):
+    from numpy import sign, abs, minimum, where
+
+    return where( (sign(a)*sign(b) > 0.0) & (sign(a)*sign(c)>0.0),
+        sign(a)*minimum(minimum(abs(a),abs(b)),abs(c)), 0.0 )
+
+
+
+def  maxmod(a,b):
+
+    from numpy import abs, where
+
+    phi =  where((abs(a) > abs(b)) & (a*b > 0.0), a, 0.0)
+    phi =  where((abs(b) > abs(a)) & (a*b > 0.0), b, phi)
+
+    return phi
+
+
+def vanleer(a,b):
+
+    from numpy import fabs, where
+
+    return where((fabs(a) + fabs(b) >= 1.0e-12), (a*fabs(b)+fabs(a)*b)/(fabs(a)+fabs(b)), 0.0)
+
+
+def vanalbada(a,b):
+
+    from numpy import abs, where
+
+    return where((a*a + b*b >= 1.0e-16), (a*a*b+a*b*b)/(a*a+b*b), 0.0)
+
+
+
+def  minmod_old(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 vanleer_old(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_old(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  maxmod_old(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  minmod_kurganov_old(a,b,c):
+    from numpy import sign
+    if sign(a)==sign(b)==sign(c):
+        return sign(a)*min(abs(a),abs(b),abs(c))
+    else:
+        return 0.0
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/quantity.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/quantity.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/quantity.py	(revision 7884)
@@ -0,0 +1,1272 @@
+"""
+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
+"""
+
+import numpy
+
+
+
+class Quantity:
+
+    
+    def __init__(self, domain, vertex_values=None):
+        #Initialise Quantity using optional vertex values.
+        
+        from anuga_1d.base.generic_domain import Generic_domain
+
+        msg = 'First argument in Quantity.__init__ '
+        msg += 'must be of class Generic_domain (or a subclass thereof)'
+        assert isinstance(domain, Generic_domain), msg
+
+        if vertex_values is None:
+            N = domain.number_of_elements
+            self.vertex_values = numpy.zeros((N, 2), numpy.float)
+        else:
+            self.vertex_values = numpy.array(vertex_values, numpy.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 = numpy.zeros(N, numpy.float)
+        self.centroid_backup_values = numpy.zeros(N, numpy.float)
+        #self.edge_values = numpy.zeros((N, 2), numpy.float)
+        #edge values are values of the ends of each interval
+      
+        #Intialise centroid values
+        self.interpolate()
+
+
+        
+        #Allocate space for boundary values
+        #L = len(domain.boundary)
+        self.boundary_values = numpy.zeros(2, numpy.float) #assumes no parrellism
+
+        #Allocate space for updates of conserved quantities by
+        #flux calculations and forcing functions
+        
+        self.N = domain.number_of_elements
+        N = self.N
+        self.explicit_update = numpy.zeros(N, numpy.float )
+        self.semi_implicit_update = numpy.zeros(N, numpy.float )
+
+        self.gradients = numpy.zeros(N, numpy.float)
+        self.qmax = numpy.zeros(self.centroid_values.shape, numpy.float)
+        self.qmin = numpy.zeros(self.centroid_values.shape, numpy.float)
+
+        #These are taken from domain but can be set for each quantity
+        # if so desired
+        self.beta = 0.0
+        self.limiter = 'vanleer'
+
+
+        self.beta_p = numpy.zeros(N,numpy.float)
+        self.beta_m = numpy.zeros(N,numpy.float)
+        self.beta_x = numpy.zeros(N,numpy.float)
+
+
+        self.dx  = numpy.zeros((N,2), numpy.float)
+        self.phi = numpy.zeros(N, numpy.float)
+
+
+    def __len__(self):
+        """
+        Returns number of intervals.
+        """
+        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_from_numeric(-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_from_numeric for details
+        """
+
+        Q = Quantity(self.domain)
+        Q.set_values_from_numeric(other)
+
+        result = Quantity(self.domain)
+        result.set_values_from_numeric(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 self.__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_from_numeric for details
+        """
+
+        if isinstance(other, Quantity):
+            Q = other
+        else:
+            Q = Quantity(self.domain)
+            Q.set_values_from_numeric(other)
+
+        result = Quantity(self.domain)
+
+        # The product of vertex_values, edge_values and centroid_values
+        # are calculated and assigned directly without using
+        # set_values_from_numeric (which calls interpolate). Otherwise
+        # centroid values wouldn't be products from q1 and q2
+        result.vertex_values = self.vertex_values * Q.vertex_values
+        result.centroid_values = self.centroid_values * Q.centroid_values
+
+        return result
+
+    def __rmul__(self, other):
+        """Handle cases like 3*Q, where Q is an instance of class Quantity
+        """
+
+        return self * other
+
+    def __div__(self, other):
+        """Divide 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_from_numeric for details
+
+        Zero division is dealt with by adding an epsilon to the divisore
+        FIXME (Ole): Replace this with native INF once we migrate to NumPy
+        """
+
+        if isinstance(other, Quantity):
+            Q = other
+        else:
+            Q = Quantity(self.domain)
+            Q.set_values_from_numeric(other)
+
+        result = Quantity(self.domain)
+
+        # The quotient of vertex_values, edge_values and centroid_values
+        # are calculated and assigned directly without using
+        # set_values_from_numeric (which calls interpolate). Otherwise
+        # centroid values wouldn't be quotient of q1 and q2
+        result.vertex_values = self.vertex_values/(Q.vertex_values + epsilon)
+        result.centroid_values = self.centroid_values/(Q.centroid_values + epsilon)
+
+        return result
+
+    def __rdiv__(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
+        """
+
+        if isinstance(other, Quantity):
+            Q = other
+        else:
+            Q = Quantity(self.domain)
+            Q.set_values_from_numeric(other)
+
+        result = Quantity(self.domain)
+
+        # The power of vertex_values, edge_values and centroid_values
+        # are calculated and assigned directly without using
+        # set_values_from_numeric (which calls interpolate). Otherwise
+        # centroid values wouldn't be correct
+        result.vertex_values = self.vertex_values ** other
+        result.centroid_values = self.centroid_values ** other
+
+        return result
+
+    def set_values_from_numeric(self, numeric):
+        
+        x = numpy.array([1.0,2.0])
+        y = [1.0,2.0]
+
+        if type(numeric) == type(y):
+            self.set_values_from_array(numeric)
+        elif type(numeric) == type(x):
+            self.set_values_from_array(numeric)
+        elif callable(numeric):
+            self.set_values_from_function(numeric)
+        elif isinstance(numeric, Quantity):
+            self.set_values_from_quantity(numeric)
+        else:   # see if it's coercible to a float (float, int or long, etc)
+            try:
+                numeric = float(numeric)
+            except ValueError:
+                msg = ("Illegal type for variable 'numeric': %s" % type(numeric))
+                raise Exception(msg)
+            self.set_values_from_constant(numeric)
+
+    def set_values_from_constant(self,numeric):
+
+        self.vertex_values[:,:]   = numeric
+        self.centroid_values[:,] = numeric
+
+
+    def set_values_from_array(self,numeric):
+
+        self.vertex_values[:,:]   = numeric
+        self.interpolate()
+
+
+    def set_values_from_quantity(self,quantity):
+
+        self.vertex_values[:,:]   = quantity.vertex_values
+        self.centroid_values[:,] = quantity.centroid_values
+
+    def set_values_from_function(self,function):
+
+        self.vertex_values[:,:]   = map(function, self.domain.vertices)
+        self.centroid_values[:,] = map(function, self.domain.centroids)
+
+
+    def interpolate(self):
+        """
+        Compute interpolated values at centroid
+        Pre-condition: vertex_values have been set
+        """
+
+        N = self.vertex_values.shape[0]
+        for i in range(N):
+            v0 = self.vertex_values[i, 0]
+            v1 = self.vertex_values[i, 1]
+
+            self.centroid_values[i] = (v0 + v1)/2.0
+
+
+
+
+    def set_values(self, X, location='vertices'):
+        """Set values for quantity
+
+        X: Compatible list, Numeric array (see below), constant or function
+        location: Where values are to be stored.
+                  Permissible options are: vertices, centroid
+                  Default is "vertices"
+
+        In case of location == 'centroid' the dimension values must
+        be a list of a Numerical array of length N, N being the number
+        of elements in the mesh. Otherwise it must be of dimension Nx2
+
+        The values will be stored in elements following their
+        internal ordering.
+
+        If values are described a function, it will be evaluated at specified points
+
+        If selected location is vertices, values for centroid and edges
+        will be assigned interpolated values.
+        In any other case, only values for the specified locations
+        will be assigned and the others will be left undefined.
+        """
+
+        if location not in ['vertices', 'centroids', 'unique_vertices']:
+            msg = 'Invalid location: %s, (possible choices vertices, centroids, unique_vertices)' %location
+            raise Exception(msg)
+
+        if X is None:
+            msg = 'Given values are None'
+            raise Exception(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]:
+            
+            self.centroid_values[:,] = float(X)
+            self.vertex_values[:,:] = float(X)
+
+        elif isinstance(X, Quantity):
+            self.set_array_values(X.vertex_values, location)
+
+        else:
+            #Use array specific method
+            self.set_array_values(X, location)
+
+        if location == 'vertices' or location == 'unique_vertices':
+            #Intialise centroid
+            self.interpolate()
+
+        if location == 'centroid':
+            self.extrapolate_first_order()
+
+
+
+
+
+    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, unique_vertices
+                  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. If location == 'unique_vertices' the
+        dimension values must be a list or a Numeric array of length N+1.
+        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.
+        """
+
+
+        values = numpy.array(values).astype(numpy.float)
+
+        N = self.centroid_values.shape[0]
+
+
+        if location == 'centroids':
+            msg = 'Number of values must match number of elements'
+            assert values.shape[0] == N, msg
+            assert len(values.shape) == 1, 'Values array must be 1d'
+
+            for i in range(N):
+                self.centroid_values[i] = values[i]
+
+            self.vertex_values[:,0] = values
+            self.vertex_values[:,1] = values
+ 
+        if location == 'vertices':
+            msg = 'Number of values must match number of elements'
+            assert values.shape[0] == N, msg
+            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[:,:]
+
+        if location == 'unique_vertices':
+            msg = 'Number of values must match number of elements +1'
+            assert values.shape[0] == N+1, msg
+            assert len(values.shape) == 1, 'Values array must be 1d'
+
+            self.vertex_values[:,0] = values[0:-1]
+            self.vertex_values[:,1] = values[1:N+1]  
+
+
+            
+
+
+    def get_values(self, location='vertices', indices = None):
+        """get values for quantity
+
+        return X, Compatible list, Numeric array (see below)
+        location: Where values are to be stored.
+                  Permissible options are: vertices, centroid
+                  and unique vertices. Default is 'vertices'
+
+        In case of location == 'centroids' the dimension values must
+        be a list of a Numerical array of length N, N being the number
+        of elements. Otherwise it must be of dimension Nx3
+
+        The returned values with be a list the length of indices
+        (N if indices = None).  Each value will be a list of the three
+        vertex values for this quantity.
+
+        Indices is the set of element ids that the operation applies to.
+
+        """
+
+
+        if location not in ['vertices', 'centroids', 'unique vertices']:
+            msg = 'Invalid location: %s' %location
+            raise Exception(msg)
+
+        import types, numpy
+        assert type(indices) in [types.ListType, types.NoneType,
+                                 numpy.ArrayType],\
+                                 'Indices must be a list or None'
+
+        if location == 'centroids':
+            if (indices ==  None):
+                indices = range(len(self))
+            return take(self.centroid_values,indices)
+        elif location == 'unique vertices':
+            if (indices ==  None):
+                indices=range(self.domain.coordinates.shape[0])
+            vert_values = []
+            #Go through list of unique vertices
+            for unique_vert_id in indices:
+                cells = self.domain.vertexlist[unique_vert_id]
+
+                #In case there are unused points
+                if cells is None:
+                    msg = 'Unique vertex not associated with cells'
+                    raise Exception(msg)
+
+                # Go through all cells, vertex pairs
+                # Average the values
+                sum = 0
+                for cell_id, vertex_id in cells:
+                    sum += self.vertex_values[cell_id, vertex_id]
+                vert_values.append(sum/len(cells))
+            return numpy.array(vert_values)
+        else:
+            if (indices ==  None):
+                indices = range(len(self))
+            return take(self.vertex_values,indices)
+
+
+    def get_vertex_values(self,
+                          x=True,
+                          smooth = None,
+                          precision = None,
+                          reduction = None):
+        """Return vertex values like an OBJ format
+
+        The vertex values are returned as one sequence in the 1D float array A.
+        If requested the coordinates will be returned in 1D arrays X.
+
+        The connectivity is represented as an integer array, V, of dimension
+        M x 2, where M is the number of volumes. Each row has two indices
+        into the X, A arrays defining the element.
+
+        if smooth is True, vertex values corresponding to one common
+        coordinate set will be smoothed according to the given
+        reduction operator. In this case vertex coordinates will be
+        de-duplicated.
+
+        If no smoothings is required, vertex coordinates and values will
+        be aggregated as a concatenation of values at
+        vertices 0, vertices 1
+
+
+        Calling convention
+        if x is True:
+           X,A,V = get_vertex_values
+        else:
+           A,V = get_vertex_values
+
+        """
+
+
+
+
+        if smooth is None:
+            smooth = self.domain.smooth
+
+        if precision is None:
+            precision = numpy.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 = numpy.zeros(N, precision)
+
+            #Smoothing loop
+            for k in range(N):
+                L = self.domain.vertexlist[k]
+                #L = self.domain.vertices[k]
+
+                #Go through all triangle, vertex pairs
+                #contributing to vertex k and register vertex value
+
+                if L is None: continue #In case there are unused points
+
+                contributions = []
+                for volume_id, vertex_id in L:
+                    v = self.vertex_values[volume_id, vertex_id]
+                    contributions.append(v)
+
+                A[k] = reduction(contributions)
+
+            if x is True:
+                 #X = self.domain.coordinates[:,0].astype(precision)
+                 X = self.domain.coordinates[:].astype(precision)
+                 #Y = self.domain.coordinates[:,1].astype(precision)
+
+                 #return X, Y, A, V
+                 return X, A, V
+            
+            #else:
+            return A, V
+        else:
+            #Don't smooth
+            #obj machinery moved to general_mesh
+
+            # Create a V like [[0 1 2], [3 4 5]....[3*m-2 3*m-1 3*m]]
+            # These vert_id's will relate to the verts created below
+            #m = len(self.domain)  #Number of volumes
+            #M = 3*m        #Total number of unique vertices
+            #V = reshape(array(range(M)).astype(Int), (m,3))
+
+            #V = self.domain.get_triangles(obj=True)
+            V = self.domain.get_vertices
+            #FIXME use get_vertices, when ready
+
+            A = self.vertex_values.flat
+
+            #Do vertex coordinates
+            if x is True:
+                X = self.domain.get_vertex_coordinates()
+
+                #X = C[:,0:6:2].copy()
+                #Y = C[:,1:6:2].copy()
+
+                return X.flat, A, V
+            else:
+                return A, V
+
+    def get_integral(self):
+        """Compute the integral of quantity across entire domain
+        """
+        integral = 0
+        for k in range(self.domain.number_of_elements):
+            area = self.domain.areas[k]
+            qc = self.centroid_values[k]
+            integral += qc*area
+
+        return integral
+
+    def get_beta(self,beta):
+        """Get limiting parameter
+        """
+        
+        return self.beta
+
+    def set_beta(self,beta):
+        """Set limiting parameter
+        """
+
+        #Probably should test that it is not too large
+        self.beta = beta
+
+
+    def get_limiter(self):
+        return self.limiter
+
+    def set_limiter(self,limiter):
+
+        possible_limiters = \
+        ['pyvolution', 'minmod_steve', 'minmod', 'minmod_kurganov', 'superbee', 'vanleer', 'vanalbada']
+
+        if limiter in possible_limiters:
+            self.limiter = limiter
+            return
+
+        msg = '%s is an incorrect limiter type.\n'% limiter
+        msg += 'Possible types are: '+ ", ".join(["%s" % el for el in possible_limiters])
+        raise Exception, msg
+
+    def update(self, timestep):
+        """Update centroid values based on values stored in
+        explicit_update and semi_implicit_update as well as given timestep
+        """
+
+
+        #Explicit updates
+        self.centroid_values += timestep*self.explicit_update
+        
+        #Semi implicit updates
+        denominator = 1.0-timestep*self.semi_implicit_update
+
+#        if sum(numpy.equal(denominator, 0.0)) > 0.0:
+#            msg = 'Zero division in semi implicit update. Call Stephen :-)'
+#            raise Exception(msg)
+#        else:
+#            #Update conserved_quantities from semi implicit updates
+#            self.centroid_values /= denominator
+#            
+
+        #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.
+        """
+
+
+        N = self.centroid_values.shape[0]
+
+
+        G = self.gradients
+        Q = self.centroid_values
+        X = self.domain.centroids
+
+    	# first element
+
+        k = 0
+
+        #Get data
+        k0 = k
+        k1 = k+1
+        k2 = k+2
+
+        q0 = Q[k0]
+        q1 = Q[k1]
+        q2 = Q[k2]
+
+        x0 = X[k0] #V0 centroid
+        x1 = X[k1] #V1 centroid
+        x2 = X[k2]
+
+        #Gradient
+        #G[k] = (q1 - q0)/(x1 - x0)
+
+        G[k] = (q1 - q0)*(x2 - x0)*(x2 - x0) - (q2 - q0)*(x1 - x0)*(x1 - x0)
+        G[k] /= (x1 - x0)*(x2 - x0)*(x2 - x1)
+
+        #last element
+        k = N-1
+
+
+        k0 = k
+        k1 = k-1
+        k2 = k-2
+
+        q0 = Q[k0]
+        q1 = Q[k1]
+        q2 = Q[k2]
+
+        x0 = X[k0] #V0 centroid
+        x1 = X[k1] #V1 centroid
+        x2 = X[k2]
+
+        #Gradient
+        #G[k] = (q1 - q0)/(x1 - x0)
+
+        G[k] = (q1 - q0)*(x2 - x0)*(x2 - x0) - (q2 - q0)*(x1 - x0)*(x1 - x0)
+        G[k] /= (x1 - x0)*(x2 - x0)*(x2 - x1)
+
+
+        #Interior Volume (2 neighbours)
+
+
+        q0 = Q[0:-2]
+        q1 = Q[1:-1]
+        q2 = Q[2:]
+
+        x0 = X[0:-2] #V0 centroid
+        x1 = X[1:-1]  #V1 centroid (Self)
+        x2 = X[2:] #V2 centroid
+
+        #Gradient
+        #G[k] = (q2-q0)/(x2-x0)
+        G[1:-1] = ((q0-q1)/(x0-x1)*(x2-x1) - (q2-q1)/(x2-x1)*(x0-x1))/(x2-x0)
+
+
+
+    def compute_minmod_gradients(self):
+        """Compute gradients of piecewise linear function defined by centroids of
+        neighbouring volumes.
+        """
+
+        #print 'compute_minmod_gradients'
+        from numpy import sign
+
+        
+        def xmin(a,b):
+            from numpy import sign, minimum
+            return 0.5*(sign(a)+sign(b))*minimum(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
+
+        #-----------------
+        #first element
+        #-----------------
+        k = 0
+
+        k0 = k
+        k1 = k+1
+        k2 = k+2
+
+        q0 = Q[k0]
+        q1 = Q[k1]
+        q2 = Q[k2]
+
+        x0 = X[k0] #V0 centroid
+        x1 = X[k1] #V1 centroid
+        x2 = X[k2]
+
+        #Gradient
+        #G[k] = (q1 - q0)/(x1 - x0)
+
+        G[k] = (q1 - q0)*(x2 - x0)*(x2 - x0) - (q2 - q0)*(x1 - x0)*(x1 - x0)
+        G[k] /= (x1 - x0)*(x2 - x0)*(x2 - x1)
+
+        #-------------------
+        # Last element
+        #-------------------
+        k = N-1
+
+        k0 = k
+        k1 = k-1
+        k2 = k-2
+
+        q0 = Q[k0]
+        q1 = Q[k1]
+        q2 = Q[k2]
+
+        x0 = X[k0] #V0 centroid
+        x1 = X[k1] #V1 centroid
+        x2 = X[k2]
+
+        #Gradient
+        #G[k] = (q1 - q0)/(x1 - x0)
+
+        G[k] = (q1 - q0)*(x2 - x0)*(x2 - x0) - (q2 - q0)*(x1 - x0)*(x1 - x0)
+        G[k] /= (x1 - x0)*(x2 - x0)*(x2 - x1)
+
+
+
+        #------------------------------
+        #Interior Volume (2 neighbours)
+        #------------------------------
+
+        q0 = Q[0:-2]
+        q1 = Q[1:-1]
+        q2 = Q[2:]
+
+        x0 = X[0:-2] #V0 centroid
+        x1 = X[1:-1]  #V1 centroid (Self)
+        x2 = X[2:] #V2 centroid
+
+        # assuming uniform grid
+        d1 = (q1 - q0)/(x1-x0)
+        d2 = (q2 - q1)/(x2-x1)
+
+        #Gradient
+        G[1:-1] = xmic( self.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.limiter == "pyvolution":
+            self.limit_pyvolution()
+
+        elif self.limiter == "minmod_steve":
+            self.limit_minmod()
+
+        else:
+            self.limit_range()
+        
+
+
+
+
+    def find_qmax_qmin(self):
+        """ Find min and max of this and neighbour's centroid values"""
+
+        from numpy import maximum, minimum
+
+        qmax = self.qmax
+        qmin = self.qmin
+
+        qc = self.centroid_values
+        
+        qmax[:] = qc
+        qmin[:] = qc
+        
+        # check left
+        qmax[1:] = maximum(qmax[1:], qc[0:-1])
+        qmin[1:] = minimum(qmin[1:], qc[0:-1])
+        
+        # check right
+        qmax[0:-1] = maximum(qmax[0:-1], qc[1:])
+        qmin[0:-1] = minimum(qmin[0:-1], qc[1:])
+
+
+
+#        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)
+
+
+
+    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        
+
+        x = self.domain.centroids
+
+        x0 = V[:,0]
+        x1 = V[:,1]
+
+        #Extrapolate
+        qv[:,0] = qc + G*(x0-x)
+        qv[:,1] = qc + G*(x1-x)
+
+#        #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
+        """
+
+
+        N = self.domain.number_of_elements
+        beta = self.domain.beta
+        #beta = 0.8
+
+        self.compute_gradients()
+
+
+        G = self.gradients
+        V = self.domain.vertices
+        C = self.domain.centroids
+        qc = self.centroid_values
+        qv = self.vertex_values
+
+        V0 = V[:,0]
+        V1 = V[:,1]
+
+        # Extrapolate to vertices
+        qv[:,0] = qc + G*(V0-C)
+        qv[:,1] = qc + G*(V1-C)
+
+
+        # Find max and min values
+        self.find_qmax_qmin()
+
+        qmax = self.qmax
+        qmin = self.qmin
+
+        #Diffences between centroids and maxima/minima
+        dqmax = qmax - qc
+        dqmin = qmin - qc
+
+        #Deltas between vertex and centroid values
+        dq = numpy.zeros(qv.shape, numpy.float)
+
+        dq[:,0] = qv[:,0] - qc
+        dq[:,1] = qv[:,1] - qc
+
+        phi = numpy.ones(qc.shape, numpy.float)
+
+        r0 = numpy.where(dq[:,0]>0.0,dqmax/dq[:,0],1.0)
+        r0 = numpy.where(dq[:,0]<0.0,dqmin/dq[:,0],r0)
+
+        r1 = numpy.where(dq[:,1]>0.0,dqmax/dq[:,1],1.0)
+        r1 = numpy.where(dq[:,1]<0.0,dqmin/dq[:,1],r1)
+
+        phi = numpy.min(r0*beta,numpy.min(r1*beta,1.0))
+
+        qv[:,0] = qc + phi*dq[:,0]
+        qv[:,1] = qc + phi*dq[:,1]
+
+#        #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 limiters_python import minmod, minmod_kurganov, minmod_kurganov_old, maxmod, vanleer, vanalbada
+
+        limiter = self.get_limiter()
+        #print limiter
+        
+        #print 'limit_range'
+        N = self.N
+        qc = self.centroid_values
+        qv = self.vertex_values
+        xc = self.domain.centroids
+        x0 = self.domain.vertices[:,0]
+        x1 = self.domain.vertices[:,1]
+
+        beta_p = self.beta_p
+        beta_m = self.beta_m
+        beta_x = self.beta_x
+        phi = self.phi
+        dx  = self.dx
+
+
+        beta_p[1:]  = (qc[1:]-qc[:-1])/(xc[1:]-xc[:-1])
+        beta_m[:-1] = beta_p[1:]
+        beta_x[1:-1] = (qc[2:]-qc[:-2])/(xc[2:]-xc[:-2])
+
+        dx[:,0] = x0 - xc
+        dx[:,1] = x1 - xc
+
+        phi[0] = (qc[1] - qc[0])/(xc[1] - xc[0])
+        phi[N-1] = (qc[N-1] - qc[N-2])/(xc[N-1] - xc[N-2])
+
+
+        if limiter == "minmod":
+            phi[1:-1] = minmod(beta_p[1:-1],beta_m[1:-1])
+
+        elif limiter == "vanleer":
+            phi[1:-1] = vanleer(beta_p[1:-1],beta_m[1:-1])
+            
+        elif limiter == "vanalbada":
+            phi[1:-1] = vanalbada(beta_p[1:-1],beta_m[1:-1])
+
+        elif limiter == "minmod_kurganov":
+            theta = self.beta
+            phi[1:-1] = minmod_kurganov(theta*beta_p[1:-1],theta*beta_m[1:-1], beta_x[1:-1])
+
+        elif limiter == "superbee":
+            slope1 = minmod(beta_m[1:-1],2.0*beta_p[1:-1])
+            slope2 = minmod(2.0*beta_m[1:-1],beta_p[1:-1])
+            phi[1:-1] = maxmod(slope1,slope2)
+
+        else:
+            msg = 'Unknown limiter'
+            raise Exception, msg
+
+
+        
+        qv[:,0] = qc + phi*dx[:,0]
+        qv[:,1] = qc + phi*dx[:,1]
+
+
+
+
+    def limit_steve_slope(self):    
+
+        import sys
+
+        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 = numpy.zeros(N,numpy.float)
+        beta_m = numpy.zeros(N,numpy.float)
+        beta_x = numpy.zeros(N,numpy.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 = numpy.zeros(qv.shape, numpy.float)
+        for i in range(2):
+            dq[:,i] =self.domain.vertices[:,i]-self.domain.centroids
+            
+        #Phi limiter
+        for k in range(N):
+                
+            phi = 0.0
+            if limiter == "flux_minmod":
+                #FLUX MINMOD
+                phi = minmod_kurganov(1.0,beta_m[k],beta_p[k])
+            elif limiter == "flux_superbee":
+                #FLUX SUPERBEE
+                phi = max(0.0,min(1.0,2.0*beta_m[k]),min(2.0,beta_m[k]))+max(0.0,min(1.0,2.0*beta_p[k]),min(2.0,beta_p[k]))-1.0
+            elif limiter == "flux_muscl":
+                #FLUX MUSCL
+                phi = max(0.0,min(2.0,2.0*beta_m[k],2.0*beta_p[k],0.5*(beta_m[k]+beta_p[k])))
+            elif limiter == "flux_vanleer":
+                #FLUX VAN LEER
+                phi = (beta_m[k]+abs(beta_m[k]))/(1.0+abs(beta_m[k]))+(beta_p[k]+abs(beta_p[k]))/(1.0+abs(beta_p[k]))-1.0
+                
+                #Then update using phi limiter
+                n = self.domain.neighbours[k,1]
+                if n>=0:
+                    #qv[k,0] = qc[k] - 0.5*phi*(qc[k+1]-qc[k])
+                    #qv[k,1] = qc[k] + 0.5*phi*(qc[k+1]-qc[k])
+                    qv[k,0] = qc[k] + 0.5*phi*(qv[k,0]-qc[k])
+                    qv[k,1] = qc[k] + 0.5*phi*(qv[k,1]-qc[k])
+                else:
+                    qv[k,i] = qc[k]
+
+    def backup_centroid_values(self):
+        # Call correct module function
+        # (either from this module or C-extension)
+        #backup_centroid_values(self)
+
+        self.centroid_backup_values[:,] = (self.centroid_values).astype('f')
+
+    def saxpy_centroid_values(self,a,b):
+        # Call correct module function
+        # (either from this module or C-extension)
+        self.centroid_values[:,] = (a*self.centroid_values + b*self.centroid_backup_values).astype('f')
+        
+
+
+
+    
+if __name__ == "__main__":
+    #from domain import Domain
+    from generic_domain import Generic_domain as Domain
+
+
+    def newLinePlot(title='Simple Plot'):
+        import pylab as g
+        g.ion()
+        g.hold(False)
+        g.title(title)
+        g.xlabel('x')
+        g.ylabel('y')
+
+
+    def linePlot(x,y):
+        import pylab as g
+        g.plot(x.flat,y.flat)
+
+
+    def closePlots():
+        import pylab as g
+        g.close('all')
+
+        
+    
+    points1 = [0.0, 1.0, 2.0, 3.0]
+    vertex_values = [[1.0,2.0],[4.0,5.0],[-1.0,2.0]]
+
+    D1 = Domain(points1)
+
+    Q1 = Quantity(D1, vertex_values)
+
+    print Q1.vertex_values
+    print Q1.centroid_values
+
+    new_vertex_values = [[2.0,1.0],[3.0,4.0],[-2.0,4.0]]
+
+    Q1.set_values(new_vertex_values)
+
+    print Q1.vertex_values
+    print Q1.centroid_values
+
+    new_centroid_values = [20,30,40]
+    Q1.set_values(new_centroid_values,'centroids')
+
+    print Q1.vertex_values
+    print Q1.centroid_values
+
+    class FunClass:
+        def __init__(self,value):
+            self.value = value
+
+        def __call__(self,x):
+            return self.value*(x**2)
+
+
+    fun = FunClass(1.0)
+    Q1.set_values(fun,'vertices')
+
+    print Q1.vertex_values
+    print Q1.centroid_values
+
+    Xc = Q1.domain.vertices
+    Qc = Q1.vertex_values
+    print Xc
+    print Qc
+
+    Qc[1,0] = 3
+
+    Q1.extrapolate_second_order()
+    #Q1.limit_minmod()
+
+    newLinePlot('plots')
+    linePlot(Xc,Qc)
+    raw_input('press return')
+
+    points2 = numpy.arange(10)
+    D2 = Domain(points2)
+
+    Q2 = Quantity(D2)
+    Q2.set_values(fun,'vertices')
+    Xc = Q2.domain.vertices
+    Qc = Q2.vertex_values
+    linePlot(Xc,Qc)
+    raw_input('press return')
+
+    
+    Q2.extrapolate_second_order()
+    #Q2.limit_minmod()
+    Xc = Q2.domain.vertices
+    Qc = Q2.vertex_values
+    print Q2.centroid_values
+    print Qc
+    linePlot(Xc,Qc)
+    raw_input('press return')
+
+
+    for i in range(10):
+        import pylab as g
+        g.hold(True)
+        fun = FunClass(i/10.0)
+        Q2.set_values(fun,'centroids')
+        Q2.extrapolate_second_order()
+        #Q2.limit_minmod()
+        Qc = Q2.vertex_values
+        linePlot(Xc,Qc)
+        raw_input('press return')
+
+    raw_input('press return to quit')
+
+    closePlots()
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/quantity_ext.c
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/quantity_ext.c	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/quantity_ext.c	(revision 7884)
@@ -0,0 +1,339 @@
+#include "Python.h"
+#include "numpy/arrayobject.h"
+#include "math.h"
+#include <stdio.h>
+const double pi = 3.14159265358979;
+
+
+// Shared code snippets
+#include "util_ext.h"
+
+
+
+
+
+
+
+
+//=========================================================================
+// Python Glue
+//=========================================================================
+
+PyObject *limit_minmod_ext(PyObject *self, PyObject *args) {
+  
+   PyObject
+           *domain,
+           *quantity;
+
+    PyArrayObject 
+	*qco,
+	*qvo,
+	*xco,
+	*xvo;
+
+    double *qc,
+            *qv,
+            *xc,
+            *xv;
+    
+  double a, b;
+  double phi, dx0, dx1;
+  int N, k, k2;
+
+    
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "O", &quantity)) {
+      PyErr_SetString(PyExc_RuntimeError, "quantity_ext.c: limit_minmod_ext could not parse input");
+      return NULL;
+  }
+  
+
+  domain = PyObject_GetAttrString(quantity, "domain");
+
+  //printf("B = %p\n",(void*)domain);
+  if (!domain) {
+    printf("quantity_ext.c: Could not obtain python object");
+    fflush(stdout);
+    PyErr_SetString(PyExc_RuntimeError, "quantity_ext.c: Could not obtain python object domain");
+    return NULL;
+  }
+  
+
+  
+  N  = get_python_integer(quantity,"N");
+ 
+  qco = get_consecutive_array(quantity, "centroid_values");
+  qvo = get_consecutive_array(quantity, "vertex_values");
+  xco = get_consecutive_array(domain, "centroids");
+  xvo = get_consecutive_array(domain, "vertices");
+    
+  qc = (double *) qco -> data;
+  qv = (double *) qvo -> data;
+  xc = (double *) xco -> data;
+  xv = (double *) xvo -> data;
+
+
+  for (k=0; k<N; k++) {
+      k2 = 2*k;
+      if (k == 0) {
+        phi = (qc[1]-qc[0])/(xc[1] - xc[0]);
+      }
+      else if (k==N-1) {
+          phi = (qc[N-1] - qc[N-2])/(xc[N-1] - xc[N-2]);
+      }
+      else {
+          a  = (qc[k]-qc[k-1])/(xc[k]-xc[k-1]);
+          b  = (qc[k+1]-qc[k])/(xc[k+1]-xc[k]);
+          //c  = (qc[K+1]-qc[k-1])/(xc[k+1]-xc[k-1]);
+
+          phi = 0.0;
+          if ((fabs(a) < fabs(b)) & (a*b > 0.0 )) {
+              phi = a;
+          }
+          if ((fabs(b) < fabs(a)) & (a*b > 0.0 )) {
+              phi = b;
+          }
+
+      }
+      
+      dx0 = xv[k2] - xc[k];
+      dx1 = xv[k2+1] - xc[k];
+
+
+      qv[k2]   = qc[k] + phi*dx0;
+      qv[k2+1] = qc[k] + phi*dx1;
+  }
+
+
+  Py_DECREF(qco);
+  Py_DECREF(qvo);
+  Py_DECREF(xco);
+  Py_DECREF(xvo);
+
+  // Return updated flux timestep
+  return Py_BuildValue("");
+}
+
+
+//====================================================================
+PyObject *limit_minmod_kurganov_ext(PyObject *self, PyObject *args) {
+
+   PyObject
+           *domain,
+           *quantity;
+
+    PyArrayObject
+	*qco,
+	*qvo,
+	*xco,
+	*xvo;
+
+    double *qc,
+            *qv,
+            *xc,
+            *xv;
+
+  double a, b, c;
+  double phi, dx0, dx1;
+  double theta;
+  int N, k, k2;
+
+
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "O", &quantity)) {
+      PyErr_SetString(PyExc_RuntimeError, "quantity_ext.c: limit_ minmod_kurganov_ext could not parse input");
+      return NULL;
+  }
+
+
+  domain = PyObject_GetAttrString(quantity, "domain");
+
+  //printf("B = %p\n",(void*)domain);
+  if (!domain) {
+    printf("quantity_ext.c: Could not obtain python object");
+    fflush(stdout);
+    PyErr_SetString(PyExc_RuntimeError, "quantity_ext.c: Could not obtain python object domain");
+    return NULL;
+  }
+
+
+
+  N  = get_python_integer(quantity,"N");
+  theta = get_python_double(quantity,"beta");
+
+
+  //printf("beta = %f",theta);
+  //fflush(stdout);
+
+  qco = get_consecutive_array(quantity, "centroid_values");
+  qvo = get_consecutive_array(quantity, "vertex_values");
+  xco = get_consecutive_array(domain, "centroids");
+  xvo = get_consecutive_array(domain, "vertices");
+
+  qc = (double *) qco -> data;
+  qv = (double *) qvo -> data;
+  xc = (double *) xco -> data;
+  xv = (double *) xvo -> data;
+
+
+  for (k=0; k<N; k++) {
+      k2 = 2*k;
+      if (k == 0) {
+        phi = (qc[1]-qc[0])/(xc[1] - xc[0]);
+      }
+      else if (k==N-1) {
+          phi = (qc[N-1] - qc[N-2])/(xc[N-1] - xc[N-2]);
+      }
+      else {
+          a  = (qc[k]-qc[k-1])/(xc[k]-xc[k-1]);
+          b  = (qc[k+1]-qc[k])/(xc[k+1]-xc[k]);
+          c  = (qc[k+1]-qc[k-1])/(xc[k+1]-xc[k-1]);
+
+          phi = 0.0;
+          if ((sign(a)*sign(b) > 0.0) & (sign(a)*sign(c) > 0.0 )) {
+              phi = sign(a)*min(theta*min(fabs(a),fabs(b)),fabs(c));
+          }
+
+
+      }
+
+      dx0 = xv[k2] - xc[k];
+      dx1 = xv[k2+1] - xc[k];
+
+
+      qv[k2]   = qc[k] + phi*dx0;
+      qv[k2+1] = qc[k] + phi*dx1;
+  }
+
+
+  Py_DECREF(qco);
+  Py_DECREF(qvo);
+  Py_DECREF(xco);
+  Py_DECREF(xvo);
+
+  // Return updated flux timestep
+  return Py_BuildValue("");
+}
+
+ 
+//====================================================================
+PyObject *limit_vanleer_ext(PyObject *self, PyObject *args) {
+
+   PyObject
+           *domain,
+           *quantity;
+
+    PyArrayObject
+	*qco,
+	*qvo,
+	*xco,
+	*xvo;
+
+    double *qc,
+            *qv,
+            *xc,
+            *xv;
+
+  double a, b;
+  double phi, dx0, dx1;
+  double theta;
+  int N, k, k2;
+
+
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "O", &quantity)) {
+      PyErr_SetString(PyExc_RuntimeError, "quantity_ext.c: limit_vanleer_ext could not parse input");
+      return NULL;
+  }
+
+
+  domain = PyObject_GetAttrString(quantity, "domain");
+
+  //printf("B = %p\n",(void*)domain);
+  if (!domain) {
+    printf("quantity_ext.c: Could not obtain python object");
+    fflush(stdout);
+    PyErr_SetString(PyExc_RuntimeError, "quantity_ext.c: Could not obtain python object domain");
+    return NULL;
+  }
+
+
+
+  N  = get_python_integer(quantity,"N");
+  theta = get_python_double(quantity,"beta");
+
+
+  //printf("beta = %f",theta);
+  //fflush(stdout);
+
+  qco = get_consecutive_array(quantity, "centroid_values");
+  qvo = get_consecutive_array(quantity, "vertex_values");
+  xco = get_consecutive_array(domain, "centroids");
+  xvo = get_consecutive_array(domain, "vertices");
+
+  qc = (double *) qco -> data;
+  qv = (double *) qvo -> data;
+  xc = (double *) xco -> data;
+  xv = (double *) xvo -> data;
+
+
+  for (k=0; k<N; k++) {
+      k2 = 2*k;
+      if (k == 0) {
+        phi = (qc[1]-qc[0])/(xc[1] - xc[0]);
+      }
+      else if (k==N-1) {
+          phi = (qc[N-1] - qc[N-2])/(xc[N-1] - xc[N-2]);
+      }
+      else {
+          a  = (qc[k]-qc[k-1])/(xc[k]-xc[k-1]);
+          b  = (qc[k+1]-qc[k])/(xc[k+1]-xc[k]);
+          //c  = (qc[k+1]-qc[k-1])/(xc[k+1]-xc[k-1]);
+
+
+          phi = 0.0;
+          if ((fabs(a)+fabs(b)) > 1.0e-12) {
+              phi = (a*fabs(b)+fabs(a)*b)/(fabs(a)+fabs(b));
+          }
+          //printf("phi = %f",phi);
+          //fflush(stdout);
+
+      }
+
+      dx0 = xv[k2] - xc[k];
+      dx1 = xv[k2+1] - xc[k];
+
+
+      qv[k2]   = qc[k] + phi*dx0;
+      qv[k2+1] = qc[k] + phi*dx1;
+  }
+
+
+  Py_DECREF(qco);
+  Py_DECREF(qvo);
+  Py_DECREF(xco);
+  Py_DECREF(xvo);
+
+  // Return updated flux timestep
+  return Py_BuildValue("");
+}
+
+
+
+
+//-------------------------------
+// Method table for python module
+//-------------------------------
+
+static struct PyMethodDef MethodTable[] = {
+  {"limit_minmod_ext",          limit_minmod_ext, METH_VARARGS, "Print out"},
+  {"limit_minmod_kurganov_ext", limit_minmod_kurganov_ext, METH_VARARGS, "Print out"},
+  {"limit_vanleer_ext",         limit_vanleer_ext, METH_VARARGS, "Print out"},
+  {NULL, NULL}
+};
+
+// Module initialisation
+void initquantity_ext(void){
+  Py_InitModule("quantity_ext", MethodTable);
+  import_array();
+}
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/test_all.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/test_all.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/test_all.py	(revision 7884)
@@ -0,0 +1,83 @@
+"""Regression testing framework
+This module will search for scripts in the same directory named
+test_*.py.  Each such script should be a test suite that tests a
+module through PyUnit. This script will aggregate all
+found test suites into one big test suite and run them all at once.
+"""
+
+# Author: Mark Pilgrim
+# Modified by Ole Nielsen
+
+import unittest
+import os
+
+
+#List files that should be excluded from the testing process.
+#E.g. if they are known to fail and under development
+exclude = [] 
+
+
+def get_test_files(path):
+
+    import sys
+
+    files = os.listdir(path)
+
+    #Check sub directories
+    test_files = []
+    for file in files:
+        if os.path.isdir(file):
+            sys.path.append(file)
+            #print 'Recursing into', file
+            test_files += get_test_files(path + os.sep + file)
+        elif file[:5] == 'test_' and file[-2:] == 'py':
+            #print 'Appending', file
+            test_files.append(file)
+        else:
+            pass
+    return test_files
+
+
+
+def regressionTest():
+    import sys, os, re, unittest
+    path = os.path.split(sys.argv[0])[0] or os.getcwd()
+
+
+    files = get_test_files(path)
+
+
+
+    #test = re.compile('^test_[\w]*.py$', re.IGNORECASE)
+    #files = filter(test.search, files)
+
+
+    try:
+        files.remove(__file__)  #Remove self from list (Ver 2.3. or later)
+    except:
+        files.remove('test_all.py')
+
+    print 'Testing:'
+    for file in files:
+        print '  ' + file
+
+    if globals().has_key('exclude'):
+        for file in exclude:
+            files.remove(file)
+            print 'WARNING: File '+ file + ' excluded from testing'
+
+
+    filenameToModuleName = lambda f: os.path.splitext(f)[0]
+    #print "files",files 
+    moduleNames = map(filenameToModuleName, files)
+    #print "moduleNames",moduleNames
+    modules = map(__import__, moduleNames)
+    load = unittest.defaultTestLoader.loadTestsFromModule
+    return unittest.TestSuite(map(load, modules))
+
+################################################################################
+
+if __name__ == '__main__':   
+    suite = regressionTest()
+    runner = unittest.TextTestRunner() #verbosity=2)
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/test_generic_domain.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/test_generic_domain.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/test_generic_domain.py	(revision 7884)
@@ -0,0 +1,103 @@
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt, pi
+import numpy
+
+from anuga_1d.base.generic_domain import *
+
+
+
+class Test_Generic_Domain(unittest.TestCase):
+    def setUp(self):
+        self.points = [0.0, 1.0, 2.0, 3.0]
+        self.vertex_values = [[1.0,2.0],[4.0,5.0],[-1.0,2.0]]
+        self.points2 = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
+        
+    def tearDown(self):
+        pass
+        #print "  Tearing down"
+
+
+    def test_creation(self):
+        domain = Generic_domain(self.points)
+
+        assert numpy.allclose(domain.neighbours, \
+            [[-1 , 1],[ 0 , 2],[ 1 ,-1]])
+ 
+        assert numpy.allclose(domain.neighbour_vertices, \
+            [[-1 , 0],[ 1 , 0],[ 1 ,-1]])
+
+        assert numpy.allclose(domain.number_of_boundaries, \
+            [1, 0, 1])
+
+        assert numpy.allclose(domain.surrogate_neighbours, \
+            [[0, 1],[0, 2],[1, 2]])
+
+        assert numpy.allclose(domain.vertices, \
+            [[ 0.,  1.],[ 1.,  2.],[ 2.,  3.]])
+
+
+        assert numpy.allclose(domain.centroids, [0.5, 1.5, 2.5])
+
+        assert numpy.allclose(domain.areas, [ 1.,  1.,  1.])
+
+        assert numpy.allclose(domain.normals, \
+            [[-1.,  1.],[-1.,  1.],[-1.,  1.]])
+
+    def test_set_timestepping_method(self):
+
+        domain = Generic_domain(self.points)
+
+        domain.set_timestepping_method('euler')
+        assert domain.timestepping_method == 'euler'
+
+        domain.set_timestepping_method('rk2')
+        assert domain.timestepping_method == 'rk2'
+
+        domain.set_timestepping_method('rk3')
+        assert domain.timestepping_method == 'rk3'
+
+        domain.set_timestepping_method(1)
+        assert domain.timestepping_method == 'euler'
+
+        domain.set_timestepping_method(2)
+        assert domain.timestepping_method == 'rk2'
+
+        domain.set_timestepping_method(3)
+        assert domain.timestepping_method == 'rk3'
+
+        try:
+            domain.set_timestepping_method(4)
+        except:
+            pass
+        else:
+            raise Exception,  'Should have raised "wrong method" error'
+
+    def test_set_spatial_order(self):
+
+        domain = Generic_domain(self.points)
+
+        domain.set_spatial_order(1)
+        assert domain.order == 1
+
+        domain.set_spatial_order(2)
+        assert  domain.order == 2
+
+
+        try:
+            domain.set_spatial_order(3)
+        except:
+            pass
+        else:
+            raise Exception,  'Should have raised "wrong order" error'
+
+
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Generic_Domain, 'test')
+    #suite = unittest.makeSuite(Test_Shallow_Water, 'test_evolve_first_order')
+
+
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/test_quantity_1d.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/test_quantity_1d.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/test_quantity_1d.py	(revision 7884)
@@ -0,0 +1,722 @@
+import quantity
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt, pi
+
+
+from anuga_1d.base.generic_domain import Generic_domain as Domain
+#from shallow_water_domain import flux_function as domain_flux_function
+
+from anuga_1d.base.quantity import *
+
+
+
+from numpy import allclose, array, ones, zeros
+import numpy
+
+
+class Test_Quantity(unittest.TestCase):
+    def setUp(self):
+        self.points3        = [0.0, 1.0, 2.0, 3.0]
+        self.vertex_values3 = [[1.0,2.0],[4.0,5.0],[-1.0,2.0]]
+        self.domain3        = Domain(self.points3)
+
+
+        
+        self.points4          = [0.0, 1.0, 2.5, 3.0, 5.0]
+        self.vertex_values4   = [[1.0,2.0],[4.0,5.0],[-1.0,2.0],[3.0,6.0]]
+        self.centroid_values4 = [1.5, 4.5, 0.5, 4.5]
+        self.boundary4        = {(0, 0): 'left', (3, 1): 'right'}
+        self.domain4          = Domain(self.points4,self.boundary4)
+
+        self.points10 = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
+        self.domain10 = Domain(self.points10)
+
+        self.points6 = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
+        self.domain6 = Domain(self.points6)
+
+    def tearDown(self):
+        pass
+        #print "  Tearing down"
+
+
+    def test_creat_with_boundary(self):
+
+        assert self.domain4.boundary  == {(0, 0): 'left', (3, 1): 'right'}
+
+        
+    def test_creation(self):
+
+        quantity = Quantity(self.domain3)
+        assert allclose(quantity.vertex_values, [[0.0,0.0],[0.0,0.0],[0.0,0.0]])
+
+        
+        try:
+            quantity = Quantity()
+        except:
+            pass
+        else:
+            raise 'Should have raised empty quantity exception'
+
+
+        try:
+            quantity = Quantity([1,2,3])
+        except AssertionError:
+            pass
+        else:
+            raise 'Should have raised "mising domain object" error'
+
+
+    def test_creation_zeros(self):
+
+        quantity = Quantity(self.domain3)
+        assert allclose(quantity.centroid_values, [[0.,0.,0.]])
+
+
+        quantity = Quantity(self.domain4)
+        assert allclose(quantity.vertex_values, [[0.,0.], [0.,0.],
+                                                 [0.,0.], [0.,0.]])
+
+
+    def test_interpolation(self):
+        quantity = Quantity(self.domain4, self.vertex_values4)
+        assert allclose(quantity.centroid_values, self.centroid_values4) #Centroid
+
+
+
+    def test_interpolation2(self):
+        quantity = Quantity(self.domain4, self.vertex_values4)
+        assert allclose(quantity.centroid_values, self.centroid_values4) #Centroid
+
+        quantity.extrapolate_second_order()
+
+        #print quantity.vertex_values
+        assert allclose(quantity.vertex_values,[[ 0.3,  2.7],
+                                                [ 4.5,  4.5],
+                                                [ 0.5,  0.5],
+                                                [ 1.3,  7.7]])
+
+ 
+
+ 
+    def test_boundary_allocation(self):
+        quantity = Quantity(self.domain4,
+                            [[1,2], [5,5], [0,9], [-6, 3]])
+
+
+        assert quantity.boundary_values.shape[0] == len(self.domain4.boundary)
+
+
+    def test_set_values(self):
+        quantity = Quantity(self.domain4)
+
+        # Test vertices
+        quantity.set_values([[1,2], [5,5], [0,9], [-6, 3]], location = 'vertices')
+        assert allclose(quantity.vertex_values,
+                        [[1,2], [5,5], [0,9], [-6, 3]])
+        assert allclose(quantity.centroid_values, [1.5, 5., 4.5, -1.5]) #Centroid
+
+
+
+        # Test unique_vertices
+        quantity.set_values([1,2,4,-5,6], location='unique_vertices')
+        assert allclose(quantity.vertex_values,
+                        [[1,2], [2,4], [4,-5], [-5,6]])
+        assert allclose(quantity.centroid_values, [1.5, 3., -.5, .5]) #Centroid
+
+
+        # Test centroids
+        quantity.set_values([1,2,3,4], location = 'centroids')
+        assert allclose(quantity.centroid_values, [1., 2., 3., 4.]) #Centroid
+
+        # Test exceptions
+        try:
+            quantity.set_values([[1,3], [5,5], [0,9], [-6, 3]],
+                                location = 'bas kamel tuba')
+        except:
+            pass
+
+
+        try:
+            quantity.set_values([[1,3], [0,9]])
+        except AssertionError:
+            pass
+        except:
+            raise 'should have raised Assertionerror'
+
+
+
+    def test_set_values_const(self):
+        quantity = Quantity(self.domain4)
+
+        quantity.set_values(1.0, location = 'vertices')
+
+        assert allclose(quantity.vertex_values, [[1,1], [1,1], [1,1], [1, 1]])
+        assert allclose(quantity.centroid_values, [1, 1, 1, 1]) #Centroid
+
+
+        quantity.set_values(2.0, location = 'centroids')
+
+        assert allclose(quantity.centroid_values, [2, 2, 2, 2])
+
+
+    def test_set_values_func(self):
+        quantity = Quantity(self.domain4)
+
+        def f(x):
+            return x*x
+
+
+
+        quantity.set_values(f, location = 'vertices')
+
+
+        assert allclose(quantity.vertex_values,
+                        [[0,1], [1,6.25], [6.25,9], [9,25]])
+
+        assert allclose(quantity.centroid_values,
+                        [0.5, 3.625, 7.625, 34*0.5])
+
+
+        quantity.set_values(f, location = 'centroids')
+
+        
+        assert allclose(quantity.centroid_values,
+                        [0.25, 3.0625, 7.5625, 16.0])
+
+
+    def test_integral(self):
+        quantity = Quantity(self.domain4)
+
+        #Try constants first
+        const = 5
+        quantity.set_values(const, location = 'vertices')
+        #print 'Q', quantity.get_integral()
+
+        assert allclose(quantity.get_integral(), self.domain4.get_area() * const)
+
+        #Try with a linear function
+        def f(x):
+            return x
+
+        quantity.set_values(f, location = 'vertices')
+
+ 
+        assert allclose (quantity.centroid_values,
+        [ 0.5,   1.75,  2.75,  4.  ])
+
+        assert allclose (quantity.vertex_values, [[ 0.,   1. ],
+                                                  [ 1.,   2.5],
+                                                  [ 2.5,  3. ],
+                                                  [ 3.,   5. ]])
+
+
+        ref_integral = 0.5 + 1.5*1.75 + 0.5*2.75 + 2.0*4.0
+
+        assert allclose (quantity.get_integral(), ref_integral)
+
+
+
+
+
+    def test_set_values_from_quantity(self):
+
+        quantity1 = Quantity(self.domain4)
+        quantity1.set_values([0,1,2,3,4], location='unique_vertices')
+
+        assert allclose(quantity1.vertex_values,
+                        [[0,1], [1,2], [2,3], [3,4]])
+
+
+        quantity2 = Quantity(self.domain4)
+        quantity2.set_values(quantity1)
+        assert allclose(quantity2.vertex_values,
+                        [[0,1], [1,2], [2,3], [3,4]])
+
+        quantity2.set_values(2*quantity1)
+
+        assert allclose(quantity2.vertex_values,
+                        [[0,2], [2,4], [4,6], [6,8]])
+
+        quantity2.set_values(2*quantity1 + 3)
+        assert allclose(quantity2.vertex_values,
+                        [[3,5], [5,7], [7,9], [9,11]])
+
+
+
+    def test_overloading(self):
+
+        quantity1 = Quantity(self.domain4)
+        quantity1.set_values( [[0,1],[1,2],[2,3],[3,4]],
+                            location = 'vertices')
+
+        assert allclose(quantity1.vertex_values,
+                        [[0,1], [1,2], [2,3], [3,4]])
+
+
+        quantity2 = Quantity(self.domain4)
+        quantity2.set_values([[1,2], [5,5], [0,9], [-6, 3]],
+                             location = 'vertices')
+
+
+
+        quantity3 = Quantity(self.domain4)
+        quantity3.set_values([[2,2], [7,8], [7,6], [3, -8]],
+                             location = 'vertices')
+
+
+        # Negation
+        Q = -quantity1
+        assert allclose(Q.vertex_values, -quantity1.vertex_values)
+        assert allclose(Q.centroid_values, -quantity1.centroid_values)
+
+
+        # Addition
+        Q = quantity1 + 7
+        assert allclose(Q.vertex_values, quantity1.vertex_values + 7)
+        assert allclose(Q.centroid_values, quantity1.centroid_values + 7)
+
+        Q = 7 + quantity1
+        assert allclose(Q.vertex_values, quantity1.vertex_values + 7)
+        assert allclose(Q.centroid_values, quantity1.centroid_values + 7)
+
+        Q = quantity1 + quantity2
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values + quantity2.vertex_values)
+        assert allclose(Q.centroid_values,
+                        quantity1.centroid_values + quantity2.centroid_values)
+
+        Q = quantity1 + quantity2 - 3
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values + quantity2.vertex_values - 3)
+
+        Q = quantity1 - quantity2
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values - quantity2.vertex_values)
+
+        #Scaling
+        Q = quantity1*3
+        assert allclose(Q.vertex_values, quantity1.vertex_values*3)
+        assert allclose(Q.centroid_values, quantity1.centroid_values*3)
+
+        Q = 3*quantity1
+        assert allclose(Q.vertex_values, quantity1.vertex_values*3)
+
+        #Multiplication
+        Q = quantity1 * quantity2
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values * quantity2.vertex_values)
+
+        #Linear combinations
+        Q = 4*quantity1 + 2
+        assert allclose(Q.vertex_values,
+                        4*quantity1.vertex_values + 2)
+
+        Q = quantity1*quantity2 + 2
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values * quantity2.vertex_values + 2)
+
+        Q = quantity1*quantity2 + quantity3
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values * quantity2.vertex_values +
+                        quantity3.vertex_values)
+        Q = quantity1*quantity2 + 3*quantity3
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values * quantity2.vertex_values +
+                        3*quantity3.vertex_values)
+        Q = quantity1*quantity2 + 3*quantity3 + 5.0
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values * quantity2.vertex_values +
+                        3*quantity3.vertex_values + 5)
+
+        Q = quantity1*quantity2 - quantity3
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values * quantity2.vertex_values -
+                        quantity3.vertex_values)
+        Q = 1.5*quantity1*quantity2 - 3*quantity3 + 5.0
+        assert allclose(Q.vertex_values,
+                        1.5*quantity1.vertex_values * quantity2.vertex_values -
+                        3*quantity3.vertex_values + 5)
+
+        #Try combining quantities and arrays and scalars
+        Q = 1.5*quantity1*quantity2.vertex_values -\
+            3*quantity3.vertex_values + 5.0
+        assert allclose(Q.vertex_values,
+                        1.5*quantity1.vertex_values * quantity2.vertex_values -
+                        3*quantity3.vertex_values + 5)
+
+
+        #Powers
+        Q = quantity1**2
+        assert allclose(Q.vertex_values, quantity1.vertex_values**2)
+
+        Q = quantity1**2 +quantity2**2
+        assert allclose(Q.vertex_values,
+                        quantity1.vertex_values**2 + \
+                        quantity2.vertex_values**2)
+
+        Q = (quantity1**2 +quantity2**2)**0.5
+        assert allclose(Q.vertex_values,
+                        (quantity1.vertex_values**2 + \
+                        quantity2.vertex_values**2)**0.5)
+
+    def test_compute_gradient(self):
+        quantity = Quantity(self.domain6)
+
+        #Set up for a gradient of (2,0) at mid triangle
+        quantity.set_values([2.0, 4.0, 4.0, 5.0, 10.0, 12.0],
+                            location = 'centroids')
+
+
+        #Gradients
+        quantity.compute_gradients()
+
+        a = quantity.gradients
+
+        assert allclose(a, [ 3., 1., 0.5, 3., 3.5, 0.5])
+
+        quantity.beta = 2.0
+        quantity.limiter = "minmod_kurganov"
+        quantity.extrapolate_second_order()
+
+
+        assert allclose(quantity.vertex_values, [[ 1., 3. ],
+                                                 [ 4., 4. ],
+                                                 [ 4., 4. ],
+                                                 [ 4., 6.],
+                                                 [ 8.25, 11.75],
+                                                 [ 11.,  13. ]])
+
+                                                 
+
+    def test_second_order_extrapolation2(self):
+        quantity = Quantity(self.domain4)
+
+        #Set up for a gradient of (3,1), f(x) = 3x+y
+        quantity.set_values([2.0+2.0/3, 4.0+4.0/3, 8.0+2.0/3, 2.0+8.0/3],
+                            location = 'centroids')
+
+        #Gradients
+        quantity.compute_gradients()
+
+        a = quantity.gradients
+        
+
+        assert allclose(a[1], 2.8)
+
+        #Work out the others
+        quantity.beta = 2.0
+        quantity.limiter = "minmod_kurganov"
+        quantity.extrapolate_second_order()
+        
+
+        assert allclose(quantity.vertex_values[1,0], 3.33333333)
+        assert allclose(quantity.vertex_values[1,1], 7.33333333)
+
+        assert allclose(quantity.centroid_values[1], 0.5*(7.33333333+3.33333333) )
+
+
+
+
+    def test_backup_saxpy_centroid_values(self):
+        quantity = Quantity(self.domain4)
+
+        #Set up for a gradient of (3,1), f(x) = 3x+y
+        c_values = array([2.0+2.0/3, 4.0+4.0/3, 8.0+2.0/3, 2.0+8.0/3])
+        d_values = array([1.0, 2.0, 3.0, 4.0])
+        quantity.set_values(c_values, location = 'centroids')
+
+        #Backup
+        quantity.backup_centroid_values()
+
+        #print quantity.vertex_values
+        assert allclose(quantity.centroid_values, quantity.centroid_backup_values)
+
+
+        quantity.set_values(d_values, location = 'centroids')
+
+        quantity.saxpy_centroid_values(2.0, 3.0)
+
+        assert allclose(quantity.centroid_values, 2.0*d_values + 3.0*c_values)
+
+
+
+    def test_first_order_extrapolator(self):
+        quantity = Quantity(self.domain4)
+
+        centroid_values = array([1.,2.,3.,4.])
+        quantity.set_values(centroid_values, location = 'centroids')
+        assert allclose(quantity.centroid_values, centroid_values) #Centroid
+
+        #Extrapolate
+        quantity.extrapolate_first_order()
+
+        #Check that gradient is zero
+        a = quantity.gradients
+        assert allclose(a, [0,0,0,0])
+       
+
+        #Check vertices but not edge values
+        assert allclose(quantity.vertex_values,
+                        [[1,1], [2,2], [3,3], [4,4]])
+
+
+    def test_second_order_extrapolator(self):
+        quantity = Quantity(self.domain4)
+
+        #Set up for a gradient of (3,0) at mid triangle
+        quantity.set_values([2.0, 4.0, 8.0, 2.0],
+                            location = 'centroids')
+
+
+
+        quantity.extrapolate_second_order()
+
+
+        #Assert that quantities are conserved
+        for k in range(quantity.centroid_values.shape[0]):
+            assert allclose (quantity.centroid_values[k],
+                             numpy.sum(quantity.vertex_values[k,:])/2.0)
+
+
+    def test_limit(self):
+        quantity = Quantity(self.domain4)
+
+        #Create a deliberate overshoot (e.g. from gradient computation)
+        quantity.set_values([[0,0], [2,20], [-20,3], [8,3]])
+
+        #Limit
+        quantity.limit_minmod()
+
+       
+        #cells 1 and 2 are local max and min
+        assert quantity.vertex_values[1][0] == quantity.centroid_values[1]
+        assert quantity.vertex_values[1][1] == quantity.centroid_values[1]
+
+        assert quantity.vertex_values[2][0] == quantity.centroid_values[2]
+        assert quantity.vertex_values[2][1] == quantity.centroid_values[2]
+
+
+
+
+    def test_limit_minmod(self):
+        quantity = Quantity(self.domain4)
+
+        #Create a deliberate overshoot (e.g. from gradient computation)
+        quantity.set_values([[0,0], [2,10], [9,13], [12,14]])
+
+        #Limit
+        quantity.limiter = 'minmod'
+        quantity.limit_range()
+
+
+
+
+        assert allclose(quantity.vertex_values, [[ -2.4,   2.4],
+                                                 [  2.4,   9.6],
+                                                 [ 10.6,  11.4],
+                                                 [ 11.4,  14.6]] )
+
+        from anuga_1d.base.quantity_ext import limit_minmod_ext
+
+        quantity.set_values([[0,0], [2,10], [9,13], [12,14]])
+
+        limit_minmod_ext(quantity)
+
+
+
+
+        assert allclose(quantity.vertex_values, [[ -2.4,   2.4],
+                                                 [  2.4,   9.6],
+                                                 [ 10.6,  11.4],
+                                                 [ 11.4,  14.6]] )
+
+
+
+    def test_limit_minmod_kurganov(self):
+        quantity = Quantity(self.domain4)
+
+        #Create a deliberate overshoot (e.g. from gradient computation)
+        quantity.set_values([[0,0], [2,10], [9,13], [12,14]])
+
+        #Limit
+        quantity.limiter = 'minmod_kurganov'
+        quantity.beta = 0.5
+        quantity.limit_range()
+
+
+        #print quantity.vertex_values
+
+        assert allclose(quantity.vertex_values, [[ -2.4,   2.4],
+                                                 [  4.2,   7.8],
+                                                 [ 10.8,  11.2],
+                                                 [ 11.4,  14.6]])
+
+        from anuga_1d.base.quantity_ext import limit_minmod_kurganov_ext
+
+        quantity.set_values([[0,0], [2,10], [9,13], [12,14]])
+
+        limit_minmod_kurganov_ext(quantity)
+
+
+        #print quantity.vertex_values
+
+
+    def test_limit_vanleer(self):
+        quantity = Quantity(self.domain4)
+
+        #Create a deliberate overshoot (e.g. from gradient computation)
+        quantity.set_values([[0,0], [2,10], [9,13], [12,14]])
+
+        #Limit
+        quantity.set_limiter('vanleer')
+        quantity.limit_range()
+
+
+        #print quantity.vertex_values
+
+        assert allclose(quantity.vertex_values, [[ -2.4,          2.4       ],
+                                                 [  2.32653061,   9.67346939],
+                                                 [ 10.39393939,  11.60606061],
+                                                 [ 11.4,         14.6       ]] )
+
+        from anuga_1d.base.quantity_ext import limit_vanleer_ext
+
+        quantity.set_values([[0,0], [2,10], [9,13], [12,14]])
+
+        limit_vanleer_ext(quantity)
+
+
+        #print quantity.vertex_values
+
+        assert allclose(quantity.vertex_values, [[ -2.4,          2.4       ],
+                                                 [  2.32653061,   9.67346939],
+                                                 [ 10.39393939,  11.60606061],
+                                                 [ 11.4,         14.6       ]] )
+#
+
+    def test_find_qmax_qmin(self):
+        quantity = Quantity(self.domain4)
+
+
+        quantity.set_values([1.0, 4.0, 8.0, 2.0],
+                            location = 'centroids')
+
+
+
+        quantity.find_qmax_qmin()
+
+
+        assert allclose(quantity.qmax, [4.0, 8.0, 8.0, 8.0])
+        assert allclose(quantity.qmin, [1.0, 1.0, 2.0, 2.0])
+
+
+    def test_distribute_first_order(self):
+        quantity = Quantity(self.domain4)
+
+        #Test centroids
+        centroid_values = array([1.,2.,3.,4.])
+        quantity.set_values(centroid_values, location = 'centroids')
+        assert allclose(quantity.centroid_values, centroid_values) #Centroid
+
+
+        #Extrapolate from centroid to vertices and edges
+        quantity.extrapolate_first_order()
+        
+        assert allclose(quantity.vertex_values,[[ 1.,  1.],
+                                                [ 2.,  2.],
+                                                [ 3.,  3.],
+                                                [ 4.,  4.]])
+ 
+
+
+    def test_distribute_second_order(self):
+        quantity = Quantity(self.domain4)
+
+        #Test centroids
+        centroid_values = array([2.,4.,8.,2.])
+        quantity.set_values(centroid_values, location = 'centroids')
+        assert allclose(quantity.centroid_values, centroid_values) #Centroid
+
+
+        #Extrapolate
+        quantity.beta = 2.0
+        quantity.limiter = "minmod_kurganov"
+        quantity.extrapolate_second_order()
+
+        assert allclose(quantity.vertex_values, [[ 1.2,  2.8],
+                                                 [ 2.,  6. ],
+                                                 [ 8.,   8. ],
+                                                 [ 6.8, -2.8]])
+
+
+    def test_update_explicit(self):
+        quantity = Quantity(self.domain4)
+
+        #Test centroids
+        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
+        assert allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
+
+        #Set explicit_update
+        quantity.explicit_update = array( [1.,1.,1.,1.] )
+
+        #Update with given timestep
+        quantity.update(0.1)
+
+        x = array([1, 2, 3, 4]) + array( [.1,.1,.1,.1] )
+        assert allclose( quantity.centroid_values, x)
+
+    def test_update_semi_implicit(self):
+        quantity = Quantity(self.domain4)
+
+        #Test centroids
+        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
+        assert allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
+
+        #Set semi implicit update
+        quantity.semi_implicit_update = array([1.,1.,1.,1.])
+
+        #Update with given timestep
+        timestep = 0.1
+        quantity.update(timestep)
+
+        sem = array([1.,1.,1.,1.])
+        denom = ones(4, numpy.float)-timestep*sem
+
+        x = array([1, 2, 3, 4])/denom
+        assert allclose( quantity.centroid_values, x)
+
+
+    def test_both_updates(self):
+        quantity = Quantity(self.domain4)
+
+        #Test centroids
+        centroid_values = array( [1, 2, 3, 4] )
+        quantity.set_values(centroid_values, location = 'centroids')
+        assert allclose(quantity.centroid_values, centroid_values) #Centroid
+
+        #Set explicit_update
+        explicit_update = array( [4.,3.,2.,1.] )
+        quantity.explicit_update[:,] = explicit_update
+
+        #Set semi implicit update
+        semi_implicit_update = array( [1.,1.,1.,1.] )
+        quantity.semi_implicit_update[:,] = semi_implicit_update
+
+        #Update with given timestep
+        timestep = 0.1
+        quantity.update(0.1)
+
+        denom = 1.0-timestep*semi_implicit_update
+        x = (centroid_values + timestep*explicit_update)/denom
+ 
+        assert allclose( quantity.centroid_values, x)
+
+
+ 
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Quantity, 'test')
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/base/util.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/base/util.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/base/util.py	(revision 7884)
@@ -0,0 +1,21 @@
+"""
+This module contains various auxiliary function used by pyvolution.
+"""
+
+
+import numpy
+
+def mean(x):
+    return numpy.sum(x)/len(x)
+
+
+def gradient(x0, x1, q0, q1):
+
+    if q1-q0 != 0:
+        a = (q1-q0)/(x1-x0)
+    else:
+        a = 0
+        
+    return a
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/__init__.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/__init__.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/__init__.py	(revision 7884)
@@ -0,0 +1,9 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="Stephen Roberts"
+__date__ ="$14/06/2010 7:50:20 PM$"
+
+pass
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_domain.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_domain.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_domain.py	(revision 7884)
@@ -0,0 +1,477 @@
+"""Class Domain -
+1D interval domains for finite-volume computations of
+the shallow water wave equation.
+
+This module contains a specialisation of class Generic_domain from module
+generic_domain.py
+consisting of methods specific to Channel flow using the Shallow Water Wave Equation
+
+This particular modification of the Domain class implements the ability to
+vary the width of the 1D channel that the water flows in. As a result the
+conserved variables are different than previous implementations and so are the
+equations.
+
+U_t + E_x = S
+
+where
+
+U = [A, Q] = [b*h, u*b*h]
+E = [Q, Q^2/A + g*b*h^2/2]
+S represents source terms forcing the system
+(e.g. gravity, boundary_stree, friction, wind stress, ...)
+gravity = -g*b*h*z_x
+boundary_stress = 1/2*g*b_x*h^2
+
+and _t, _x, _y denote the derivative with respect to t, x and y respectiely.
+
+The quantities are
+
+symbol    variable name    explanation
+A         area             Wetted area = b*h
+Q         discharge        flux of water = u*b*h
+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]
+b         width            width of channel
+eta                        mannings friction coefficient [to appear]
+nu                         wind stress coefficient [to appear]
+
+The conserved quantities are A, Q
+--------------------------------------------------------------------------
+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,
+Padarn Wilson, Geoscience Australia, 2008
+"""
+
+
+from anuga_1d.base.generic_domain import *
+import numpy
+
+
+#Shallow water domain
+class Domain(Generic_domain):
+
+    def __init__(self, coordinates, boundary = None, tagged_elements = None):
+
+        conserved_quantities = ['area', 'discharge']
+        evolved_quantities = ['area', 'discharge', 'elevation', 'height', 'velocity','width','stage']
+        other_quantities = ['friction']
+        Generic_domain.__init__(self,
+                                coordinates = coordinates,
+                                boundary = boundary,
+                                conserved_quantities = conserved_quantities,
+                                evolved_quantities = evolved_quantities,
+                                other_quantities = other_quantities,
+                                tagged_elements = tagged_elements)
+        
+        from anuga_1d.config import minimum_allowed_height, g, h0
+        self.minimum_allowed_height = minimum_allowed_height
+        self.g = g
+        self.h0 = h0
+        self.setstageflag = False
+        self.discontinousb = False
+
+
+        # forcing terms gravity and boundary stress are included in the flux calculation
+        #self.forcing_terms.append(gravity)
+        #self.forcing_terms.append(boundary_stress)
+        #self.forcing_terms.append(manning_friction)
+       
+
+        
+        #Stored output
+        self.store = True
+        self.format = 'sww'
+        self.smooth = True
+
+        
+        #Reduction operation for get_vertex_values
+        from anuga_1d.base.util import mean
+        self.reduction = mean
+        #self.reduction = min  #Looks better near steep slopes
+
+        self.set_quantities_to_be_stored(['area','discharge'])
+
+	self.__doc__ = 'channel_domain'
+
+        self.check_integrity()
+
+
+    def check_integrity(self):
+
+        #Check that we are solving the shallow water wave equation
+
+        msg = 'First conserved quantity must be "area"'
+        assert self.conserved_quantities[0] == 'area', msg
+        msg = 'Second conserved quantity must be "discharge"'
+        assert self.conserved_quantities[1] == 'discharge', msg
+
+        msg = 'First evolved quantity must be "area"'
+        assert self.evolved_quantities[0] == 'area', msg
+        msg = 'Second evolved quantity must be "discharge"'
+        assert self.evolved_quantities[1] == 'discharge', msg
+        msg = 'Third evolved quantity must be "elevation"'
+        assert self.evolved_quantities[2] == 'elevation', msg
+        msg = 'Fourth evolved quantity must be "height"'
+        assert self.evolved_quantities[3] == 'height', msg
+        msg = 'Fifth evolved quantity must be "velocity"'
+        assert self.evolved_quantities[4] == 'velocity', msg
+        msg = 'Sixth evolved quantity must be "width"'
+        assert self.evolved_quantities[5] == 'width', msg
+        msg = 'Seventh evolved quantity must be "stage"'
+        assert self.evolved_quantities[6] == 'stage', msg
+
+        Generic_domain.check_integrity(self)
+
+    def compute_fluxes(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        compute_fluxes_channel(self)
+
+    def distribute_to_vertices_and_edges(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        distribute_to_vertices_and_edges_limit_a_d(self)
+        
+
+#=============== End of Channel Domain ===============================
+
+#-----------------------------------
+# Compute flux definition with channel
+#-----------------------------------
+def compute_fluxes_channel(domain):
+    import sys
+    timestep = float(sys.maxint)
+
+    area       = domain.quantities['area']
+    discharge  = domain.quantities['discharge']
+    bed        = domain.quantities['elevation']
+    height     = domain.quantities['height']
+    velocity   = domain.quantities['velocity']
+    width      = domain.quantities['width']
+
+
+    from anuga_1d.channel.channel_domain_ext import compute_fluxes_channel_ext
+    domain.flux_timestep = compute_fluxes_channel_ext(timestep,domain,area,discharge,bed,height,velocity,width)
+
+#-----------------------------------------------------------------------
+# Distribute to verticies with stage reconstructed and then extrapolated
+#-----------------------------------------------------------------------
+def distribute_to_vertices_and_edges_limit_a_d(domain):
+    
+    #Remove very thin layers of water
+    #protect_against_infinitesimal_and_negative_heights(domain)  
+
+
+
+    import sys
+    from anuga_1d.config import epsilon, h0
+
+    
+    N = domain.number_of_elements
+
+    #Shortcuts
+    area      = domain.quantities['area']
+    discharge = domain.quantities['discharge']
+    bed       = domain.quantities['elevation']
+    height    = domain.quantities['height']
+    velocity  = domain.quantities['velocity']
+    width     = domain.quantities['width']
+    stage     = domain.quantities['stage']
+
+    #Arrays   
+    a_C   = area.centroid_values
+    d_C   = discharge.centroid_values
+    z_C   = bed.centroid_values
+    h_C   = height.centroid_values
+    u_C   = velocity.centroid_values
+    b_C   = width.centroid_values
+    w_C   = stage.centroid_values
+
+    if domain.setstageflag:
+        a_C[:,] = (w_C-z_C)*b_C
+        domain.setstageflag = False
+
+    if domain.discontinousb:
+        width.extrapolate_second_order()
+        
+
+    h0 = 1.0e-12
+
+    h_C[:] = numpy.where( (a_C>h0) | (b_C>h0), a_C/(b_C+h0/b_C), 0.0 )
+    u_C[:] = numpy.where( (a_C>h0) | (b_C>h0), d_C/(a_C+h0/a_C), 0.0 )
+
+    a_C[:] = numpy.where( (a_C>h0) | (b_C>h0), a_C, 0.0 )
+    b_C[:] = numpy.where( (a_C>h0) | (b_C>h0), b_C, 0.0 )
+    d_C[:] = numpy.where( (a_C>h0) | (b_C>h0), d_C, 0.0 )
+
+    w_C[:] = h_C + z_C
+    
+		
+
+    bed.extrapolate_second_order()
+    
+    for name in ['velocity','stage']:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            Q.extrapolate_second_order()
+        else:
+            raise 'Unknown order'
+
+
+    a_V  = area.vertex_values
+    w_V  = stage.vertex_values
+    z_V  = bed.vertex_values
+    h_V  = height.vertex_values
+    u_V  = velocity.vertex_values
+    d_V  = discharge.vertex_values
+    b_V  = width.vertex_values
+
+
+    h_V[:] = w_V-z_V
+
+    w_V[:] = numpy.where(h_V > h0, w_V, z_V)
+    h_V[:] = numpy.where(h_V > h0, h_V, 0.0)
+    a_V[:] = b_V*h_V
+    d_V[:] = u_V*a_V
+
+    
+    return
+
+
+#--------------------------------------------------------
+#Boundaries - specific to the channel_domain
+#--------------------------------------------------------
+class Reflective_boundary(Boundary):
+    """Reflective boundary returns same conserved quantities as
+    those present in its neighbour volume but reflected.
+
+    This class is specific to the shallow water equation as it
+    works with the momentum quantities assumed to be the second
+    and third conserved quantities.
+    """
+
+    def __init__(self, domain = None):
+        Boundary.__init__(self)
+
+        if domain is None:
+            msg = 'Domain must be specified for reflective boundary'
+            raise msg
+
+        #Handy shorthands
+        self.normals  = domain.normals
+        self.area     = domain.quantities['area'].vertex_values
+        self.discharge     = domain.quantities['discharge'].vertex_values
+        self.bed      = domain.quantities['elevation'].vertex_values
+        self.height   = domain.quantities['height'].vertex_values
+        self.velocity = domain.quantities['velocity'].vertex_values
+        self.width    = domain.quantities['width'].vertex_values
+        self.stage    = domain.quantities['stage'].vertex_values
+
+        self.evolved_quantities = numpy.zeros(7, numpy.float)
+
+    def __repr__(self):
+        return 'Reflective_boundary'
+
+
+    def evaluate(self, vol_id, edge_id):
+        """Reflective boundaries reverses the outward momentum
+        of the volume they serve.
+        """
+
+        q = self.evolved_quantities
+        q[0] =  self.area[vol_id, edge_id]
+        q[1] = -self.discharge[vol_id, edge_id]
+        q[2] =  self.bed[vol_id, edge_id]
+        q[3] =  self.height[vol_id, edge_id]
+        q[4] = -self.velocity[vol_id, edge_id]
+        q[5] =  self.width[vol_id,edge_id]
+        q[6] =  self.stage[vol_id,edge_id]
+
+        return q
+
+class Dirichlet_boundary(Boundary):
+    """Dirichlet boundary returns constant values for the
+    conserved quantities
+if k>5 and k<15:
+            print discharge_ud[k],-g*zx*avg_h*avg_b
+        discharge_ud[k] +=-g*zx*avg_h*avg_b    """
+
+
+    def __init__(self, evolved_quantities=None):
+        Boundary.__init__(self)
+
+        if evolved_quantities is None:
+            msg = 'Must specify one value for each evolved quantity'
+            raise msg
+
+        assert len(evolved_quantities) == 7
+
+        self.evolved_quantities=numpy.array(evolved_quantities,numpy.float)
+
+    def __repr__(self):
+        return 'Dirichlet boundary (%s)' %self.evolved_quantities
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        return self.evolved_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
+
+
+
+    Area      = domain.quantities['area']
+    Discharge  = domain.quantities['discharge']
+    Elevation = domain.quantities['elevation']
+    Height    = domain.quantities['height']
+    Width     = domain.quantities['width']
+
+    discharge_ud  = Discharge.explicit_update
+
+
+       
+    h = Height.vertex_values
+    b = Width.vertex_values
+    a = Area.vertex_values
+    z = Elevation.vertex_values
+
+    x = domain.get_vertex_coordinates()
+    g = domain.g
+    for k in range(domain.number_of_elements):
+        avg_h = 0.5*(h[k,0] + h[k,1])
+        avg_b = 0.5*(b[k,0] + b[k,1])
+        
+        #Compute bed slope
+        x0, x1 = x[k,:]
+        z0, z1 = z[k,:]
+        zx = gradient(x0, x1, z0, z1)
+       
+        #Update momentum (explicit update is reset to source values)
+        discharge_ud[k]+= -g*zx*avg_h*avg_b
+      
+
+def boundary_stress(domain):
+
+    from util import gradient
+    from Numeric import zeros, Float, array, sum
+
+    Area     = domain.quantities['area']
+    Discharge  = domain.quantities['discharge']
+    Elevation = domain.quantities['elevation']
+    Height    = domain.quantities['height']
+    Width     = domain.quantities['width']
+
+    discharge_ud  = Discharge.explicit_update
+ 
+    h = Height.vertex_values
+    b = Width.vertex_values
+    a = Area.vertex_values
+    z = Elevation.vertex_values
+
+    x = domain.get_vertex_coordinates()
+    g = domain.g
+
+    for k in range(domain.number_of_elements):
+        avg_h = 0.5*(h[k,0] + h[k,1])
+        
+
+        #Compute bed slope
+        x0, x1 = x[k,:]
+        b0, b1 = b[k,:]
+        bx = gradient(x0, x1, b0, b1)
+        
+        #Update momentum (explicit update is reset to source values)
+        discharge_ud[k] += 0.5*g*bx*avg_h*avg_h
+        #stage_ud[k] = 0.0
+ 
+ 
+def manning_friction(domain):
+    """Apply (Manning) friction to water momentum
+    """
+
+    from math import sqrt
+
+    w = domain.quantities['stage'].centroid_values
+    z = domain.quantities['elevation'].centroid_values
+    h = w-z
+
+    uh = domain.quantities['xmomentum'].centroid_values
+    eta = domain.quantities['friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+
+    N = domain.number_of_elements
+    eps = domain.minimum_allowed_height
+    g = domain.g
+
+    for k in range(N):
+        if eta[k] >= eps:
+            if h[k] >= eps:
+            	#S = -g * eta[k]**2 * 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
+    tau = domain.quantities['linear_friction'].centroid_values
+
+    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
+
+    N = domain.number_of_elements
+    eps = domain.minimum_allowed_height
+
+    for k in range(N):
+        if tau[k] >= eps:
+            if h[k] >= eps:
+            	S = -tau[k]/h[k]
+
+            	#Update momentum
+            	xmom_update[k] += S*uh[k]
+
+
+
+
+def linearb(domain):
+
+    bC = domain.quantities['width'].vertex_values
+    
+    for i in range(len(bC)-1):
+        temp= 0.5*(bC[i,1]+bC[i+1,0])
+        bC[i,1]=temp
+        bC[i+1,0]=temp
+
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_domain_ext.c
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_domain_ext.c	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_domain_ext.c	(revision 7884)
@@ -0,0 +1,830 @@
+#include "Python.h"
+#include "numpy/arrayobject.h"
+#include "math.h"
+#include <stdio.h>
+const double pi = 3.14159265358979;
+
+
+// Shared code snippets
+#include "util_ext.h"
+
+
+/* double max(double a, double b) { */
+/* 	double z; */
+/* 	z=(a>b)?a:b; */
+/* 	return z;} */
+
+/* double min(double a, double b) { */
+/* 	double z; */
+/* 	z=(a<b)?a:b; */
+/* 	return z;} */
+
+
+// Function to obtain speed from momentum and depth.
+// This is used by flux functions
+// Input parameters uh and h may be modified by this function.
+double _compute_speed(double *uh,
+		      double *h,
+		      double epsilon,
+		      double h0) {
+
+  double u;
+
+  if (*h < epsilon) {
+    *h = 0.0;  //Could have been negative
+     u = 0.0;
+  } else {
+    u = *uh/(*h + h0/ *h);
+  }
+
+
+  // Adjust momentum to be consistent with speed
+  *uh = u * *h;
+
+  return u;
+}
+
+
+//WELL BALANCED VERSION
+//Innermost flux function (using w=z+h)
+int _flux_function_channel21(double *q_leftm,double *q_leftp, double *q_rightm,
+			   double *q_rightp, double g, double epsilon, double h0,                           double *edgeflux, double *max_speed) {
+
+    int i;
+    double flux_left[2], flux_right[2];
+    double a_leftm,w_leftm, h_leftm, d_leftm, z_leftm, u_leftm, b_leftm, soundspeed_leftm;
+     double a_leftp,w_leftp, h_leftp, d_leftp, z_leftp, u_leftp, b_leftp, soundspeed_leftp;
+ double a_rightm,w_rightm, h_rightm, d_rightm, z_rightm, u_rightm, b_rightm, soundspeed_rightm;
+ double a_rightp,w_rightp, h_rightp, d_rightp, z_rightp, u_rightp, b_rightp, soundspeed_rightp;
+    double s_maxl, s_minl,s_maxr,s_minr, denom;
+    double zphalf,zmhalf,hleftstar,hrightstar;
+    double fluxtemp1,fluxtemp0,speedtemp;
+    double batemp,bphalf,bmhalf;
+
+    zmhalf = max(q_leftm[2],q_leftp[2]);
+    zphalf = max(q_rightm[2],q_rightp[2]);   
+
+    a_leftm  = q_leftm[0];
+    d_leftm = q_leftm[1];
+    z_leftm  = q_leftm[2];
+    h_leftm  = max(0,q_leftm[3]+q_leftm[2]-zmhalf);
+    u_leftm  = q_leftm[4];
+    b_leftm  = q_leftm[5];
+    w_leftm  = h_leftm+z_leftm;
+
+    a_leftp  = q_leftp[0];
+    d_leftp = q_leftp[1];
+    z_leftp  = q_leftp[2];
+    h_leftp  = max(0,q_leftp[3]+q_leftp[2]-zmhalf);
+    u_leftp  = q_leftp[4];
+    b_leftp  = q_leftp[5];
+    w_leftp  = h_leftp+z_leftp;
+
+    a_rightm  = q_rightm[0];
+    d_rightm = q_rightm[1];
+    z_rightm  = q_rightm[2];
+    h_rightm  = max(0,q_rightm[3]+q_rightm[2]-zphalf);
+    u_rightm  = q_rightm[4];
+    b_rightm  = q_rightm[5];
+    w_rightm  = h_rightm+z_rightm;
+
+    a_rightp  = q_rightp[0];
+    d_rightp = q_rightp[1];
+    z_rightp  = q_rightp[2];
+    h_rightp  = max(0,q_rightp[3]+q_rightp[2]-zphalf);
+    u_rightp  = q_rightp[4];
+    b_rightp  = q_rightp[5];
+    w_rightp  = h_rightp+z_rightp;
+
+    hleftstar = q_leftp[3];
+    hrightstar = q_rightm[3];   
+
+     bphalf = 0.5*(b_rightm+b_rightp);
+     bmhalf = 0.5*(b_leftm+b_leftp);
+     //bphalf = min(b_rightm,b_rightp);
+     //bmhalf = min(b_leftm,b_leftp);
+
+
+    soundspeed_leftp = sqrt(g*h_leftp);
+    soundspeed_leftm = sqrt(g*h_leftm);
+    soundspeed_rightp = sqrt(g*h_rightp);
+    soundspeed_rightm = sqrt(g*h_rightm);
+
+    s_maxl = max(u_leftm+soundspeed_leftm, u_leftp+soundspeed_leftp);
+    if (s_maxl < 0.0) s_maxl = 0.0;
+
+    s_minl = min(u_leftm-soundspeed_leftm, u_leftp-soundspeed_leftp);
+    if (s_minl > 0.0) s_minl = 0.0;
+
+    s_maxr = max(u_rightm+soundspeed_rightm, u_rightp+soundspeed_rightp);
+    if (s_maxr < 0.0) s_maxr = 0.0;
+
+    s_minr = min(u_rightm-soundspeed_rightm, u_rightp-soundspeed_rightp);
+    if (s_minr > 0.0) s_minr = 0.0;
+
+    // Flux formulas for left hand side
+    flux_left[0] = d_leftm;
+    flux_left[1] = u_leftm*d_leftm + 0.5*g*h_leftm*h_leftm*bmhalf;
+
+    flux_right[0] = d_leftp;
+    flux_right[1] = u_leftp*d_leftp + 0.5*g*h_leftp*h_leftp*bmhalf;
+
+    
+    // Flux computation for left hand side
+    denom = s_maxl-s_minl;
+    if (denom < epsilon) {
+	for (i=0; i<2; i++) edgeflux[i] = 0.0;
+    } else {
+	edgeflux[0] = s_maxl*flux_left[0] - s_minl*flux_right[0];
+
+        batemp = (q_leftp[3]+q_leftp[2])*bmhalf-(q_leftm[3]+q_leftm[2])*bmhalf;
+       	edgeflux[0] += s_maxl*s_minl*batemp;
+	edgeflux[0] /= denom;
+	edgeflux[1] = s_maxl*flux_left[1] - s_minl*flux_right[1];
+	edgeflux[1] += s_maxl*s_minl*(d_leftp-d_leftm);
+	edgeflux[1] /= denom;
+    
+
+    }
+	fluxtemp0 = edgeflux[0];
+        fluxtemp1 = edgeflux[1];
+    
+
+    // Flux formulas for right hand side
+    flux_left[0] = d_rightm;
+    flux_left[1] = u_rightm*d_rightm + 0.5*g*h_rightm*h_rightm*bphalf;
+
+    flux_right[0] = d_rightp;
+    flux_right[1] = u_rightp*d_rightp + 0.5*g*h_rightp*h_rightp*bphalf;
+    
+   
+   
+    // Flux computation for right hand side
+    denom = s_maxr-s_minr;
+    if (denom < epsilon) {
+	for (i=0; i<2; i++) edgeflux[i] = 0.0;
+    } else {
+	edgeflux[0] = s_maxr*flux_left[0] - s_minr*flux_right[0];
+
+        batemp = (q_rightp[3]+q_rightp[2])*bphalf-(q_rightm[3]+q_rightm[2])*bphalf;
+
+       	edgeflux[0] += s_maxr*s_minr*batemp;
+	edgeflux[0] /= denom;
+	edgeflux[1] = s_maxr*flux_left[1] - s_minr*flux_right[1];
+	edgeflux[1] += s_maxr*s_minr*(d_rightp-d_rightm);
+	edgeflux[1] /= denom;
+    
+
+    }
+    
+   
+    edgeflux[0]=edgeflux[0]-fluxtemp0;
+    edgeflux[1]=edgeflux[1]-fluxtemp1;
+    
+   
+    edgeflux[1]-=0.5*g*h_rightm*h_rightm*bphalf-0.5*g*hrightstar*hrightstar*b_rightm+0.5*g*hleftstar*hleftstar*b_leftp-0.5*g*h_leftp*h_leftp*bmhalf;
+
+    // printf("edgflux:%f expected:%f \n",edgeflux[1],hrightstar*hrightstar*g*0.5*b_rightm-hleftstar*hleftstar*g*0.5*b_leftp);
+
+    edgeflux[1]-=g*(1.0/6.0)*(b_rightm*(hleftstar*hleftstar+hrightstar*(hrightstar+2*z_leftp-2*z_rightm)+hleftstar*(hrightstar+z_leftp-z_rightm))-b_leftp*(hleftstar*hleftstar+hrightstar*(hrightstar-z_leftp+z_rightm)+hleftstar*(hrightstar-2*z_leftp+2*z_rightm)));
+
+   
+    //edgeflux[1]-=0.5*g*h_rightm*h_rightm-0.5*g*hrightstar*hrightstar+0.5*g*hleftstar*hleftstar-0.5*g*h_leftp*h_leftp;
+      
+     //edgeflux[1]-=0.5*g*b_rightm*h_rightm*h_rightm-0.5*g*b_leftp*h_leftp*h_leftp;
+         	// Maximal wavespeed
+	if ( (s_maxl-s_minl)<epsilon && (s_maxr-s_minr)<epsilon ){
+	    *max_speed = 0.0;
+	}else{
+	speedtemp = max(fabs(s_maxl),fabs(s_minl));
+        speedtemp = max(speedtemp,fabs(s_maxr));
+        speedtemp = max(speedtemp,fabs(s_minr));
+	*max_speed = speedtemp;
+	}
+
+//printf("%f\n",h_right);
+    return 0;
+}
+// GOOD BUT NOT WELL BALANCED VERSION
+int _flux_function_channel(double *q_leftm,double *q_leftp, double *q_rightm,
+			   double *q_rightp, double g, double epsilon, double h0,                           double *edgeflux, double *max_speed){
+
+    int i;
+    double flux_left[2], flux_right[2];
+    double a_leftm,w_leftm, h_leftm, d_leftm, z_leftm, u_leftm, b_leftm, soundspeed_leftm;
+     double a_leftp,w_leftp, h_leftp, d_leftp, z_leftp, u_leftp, b_leftp, soundspeed_leftp;
+ double a_rightm,w_rightm, h_rightm, d_rightm, z_rightm, u_rightm, b_rightm, soundspeed_rightm;
+ double a_rightp,w_rightp, h_rightp, d_rightp, z_rightp, u_rightp, b_rightp, soundspeed_rightp;
+    double s_maxl, s_minl,s_maxr,s_minr, denom;
+    double zphalf,zmhalf,hleftstar,hrightstar;
+    double fluxtemp1,fluxtemp0,speedtemp;
+    double batemp,bphalf,bmhalf;
+
+    zmhalf = max(q_leftm[2],q_leftp[2]);
+    zphalf = max(q_rightm[2],q_rightp[2]);   
+
+    a_leftm  = q_leftm[0];
+    d_leftm = q_leftm[1];
+    z_leftm  = q_leftm[2];
+    h_leftm  = q_leftm[3];
+    u_leftm  = q_leftm[4];
+    b_leftm  = q_leftm[5];
+    w_leftm  = h_leftm+z_leftm;
+
+    a_leftp  = q_leftp[0];
+    d_leftp = q_leftp[1];
+    z_leftp  = q_leftp[2];
+    h_leftp  = q_leftp[3];
+    u_leftp  = q_leftp[4];
+    b_leftp  = q_leftp[5];
+    w_leftp  = h_leftp+z_leftp;
+
+    a_rightm  = q_rightm[0];
+    d_rightm = q_rightm[1];
+    z_rightm  = q_rightm[2];
+    h_rightm  = q_rightm[3];
+    u_rightm  = q_rightm[4];
+    b_rightm  = q_rightm[5];
+    w_rightm  = h_rightm+z_rightm;
+
+    a_rightp  = q_rightp[0];
+    d_rightp = q_rightp[1];
+    z_rightp  = q_rightp[2];
+    h_rightp  = q_rightp[3];
+    u_rightp  = q_rightp[4];
+    b_rightp  = q_rightp[5];
+    w_rightp  = h_rightp+z_rightp;
+
+    hleftstar = q_leftp[3];
+    hrightstar = q_rightm[3];   
+
+    bphalf = min(b_rightm,b_rightp);
+    bmhalf = min(b_leftm,b_leftp);
+
+    soundspeed_leftp = sqrt(g*h_leftp);
+    soundspeed_leftm = sqrt(g*h_leftm);
+    soundspeed_rightp = sqrt(g*h_rightp);
+    soundspeed_rightm = sqrt(g*h_rightm);
+
+    s_maxl = max(u_leftm+soundspeed_leftm, u_leftp+soundspeed_leftp);
+    if (s_maxl < 0.0) s_maxl = 0.0;
+
+    s_minl = min(u_leftm-soundspeed_leftm, u_leftp-soundspeed_leftp);
+    if (s_minl > 0.0) s_minl = 0.0;
+
+    s_maxr = max(u_rightm+soundspeed_rightm, u_rightp+soundspeed_rightp);
+    if (s_maxr < 0.0) s_maxr = 0.0;
+
+    s_minr = min(u_rightm-soundspeed_rightm, u_rightp-soundspeed_rightp);
+    if (s_minr > 0.0) s_minr = 0.0;
+
+    // Flux formulas for left hand side
+    flux_left[0] = d_leftm;
+    flux_left[1] = u_leftm*d_leftm + 0.5*g*h_leftm*h_leftm*b_leftm;
+
+    flux_right[0] = d_leftp;
+    flux_right[1] = u_leftp*d_leftp + 0.5*g*h_leftp*h_leftp*b_leftp;
+
+    
+    // Flux computation for left hand side
+    denom = s_maxl-s_minl;
+    if (denom < epsilon) {
+	for (i=0; i<2; i++) edgeflux[i] = 0.0;
+    } else {
+	edgeflux[0] = s_maxl*flux_left[0] - s_minl*flux_right[0];
+
+        batemp = (q_leftp[3]+q_leftp[2])*b_leftp-(q_leftm[3]+q_leftm[2])*b_leftm;
+       	edgeflux[0] += s_maxl*s_minl*batemp;
+	edgeflux[0] /= denom;
+	edgeflux[1] = s_maxl*flux_left[1] - s_minl*flux_right[1];
+	edgeflux[1] += s_maxl*s_minl*(d_leftp-d_leftm);
+	edgeflux[1] /= denom;
+    
+
+    }
+	fluxtemp0 = edgeflux[0];
+        fluxtemp1 = edgeflux[1];
+    
+
+    // Flux formulas for right hand side
+    flux_left[0] = d_rightm;
+    flux_left[1] = u_rightm*d_rightm + 0.5*g*h_rightm*h_rightm*b_rightm;
+
+    flux_right[0] = d_rightp;
+    flux_right[1] = u_rightp*d_rightp + 0.5*g*h_rightp*h_rightp*b_rightp;
+    
+   
+   
+    // Flux computation for right hand side
+    denom = s_maxr-s_minr;
+    if (denom < epsilon) {
+	for (i=0; i<2; i++) edgeflux[i] = 0.0;
+    } else {
+	edgeflux[0] = s_maxr*flux_left[0] - s_minr*flux_right[0];
+
+        batemp = (q_rightp[3]+q_rightp[2])*b_rightp-(q_rightm[3]+q_rightm[2])*b_rightm;
+
+       	edgeflux[0] += s_maxr*s_minr*batemp;
+	edgeflux[0] /= denom;
+	edgeflux[1] = s_maxr*flux_left[1] - s_minr*flux_right[1];
+	edgeflux[1] += s_maxr*s_minr*(d_rightp-d_rightm);
+	edgeflux[1] /= denom;
+    
+
+    }
+    
+   
+    edgeflux[0]=edgeflux[0]-fluxtemp0;
+    edgeflux[1]=edgeflux[1]-fluxtemp1;
+    
+    edgeflux[1]-=-0.5*0.5*g*(h_rightm+h_leftp)*(b_rightm+b_leftp)*(z_rightm-z_leftp)+0.5*(h_rightm+h_leftp)*(h_rightm+h_leftp)*0.5*0.5*(b_rightm-b_leftp)*g; 
+
+    //edgeflux[1]-=0.5*g*h_rightm*h_rightm*bphalf-0.5*g*hrightstar*hrightstar*b_rightm+0.5*g*hleftstar*hleftstar*b_leftp-0.5*g*h_leftp*h_leftp*bmhalf;
+
+    // printf("edgflux:%f expected:%f \n",edgeflux[1],hrightstar*hrightstar*g*0.5*b_rightm-hleftstar*hleftstar*g*0.5*b_leftp);
+
+    //edgeflux[1]-=g*(1.0/6.0)*(b_rightm*(hleftstar*hleftstar+hrightstar*(hrightstar+2*z_leftp-2*z_rightm)+hleftstar*(hrightstar+z_leftp-z_rightm))-b_leftp*(hleftstar*hleftstar+hrightstar*(hrightstar-z_leftp+z_rightm)+hleftstar*(hrightstar-2*z_leftp+2*z_rightm)));
+
+   
+    //edgeflux[1]-=0.5*g*h_rightm*h_rightm-0.5*g*hrightstar*hrightstar+0.5*g*hleftstar*hleftstar-0.5*g*h_leftp*h_leftp;
+      
+     //edgeflux[1]-=0.5*g*b_rightm*h_rightm*h_rightm-0.5*g*b_leftp*h_leftp*h_leftp;
+         	// Maximal wavespeed
+	if ( (s_maxl-s_minl)<epsilon && (s_maxr-s_minr)<epsilon ){
+	    *max_speed = 0.0;
+	}else{
+	speedtemp = max(fabs(s_maxl),fabs(s_minl));
+        speedtemp = max(speedtemp,fabs(s_maxr));
+        speedtemp = max(speedtemp,fabs(s_minr));
+	*max_speed = speedtemp;
+	}
+
+//printf("%f\n",h_right);
+    return 0;
+}
+// NAIEVE VERSION
+int _flux_function_channel2(double *q_leftm,double *q_leftp, double *q_rightm,
+			   double *q_rightp, double g, double epsilon, double h0,                           double *edgeflux, double *max_speed){
+
+    int i;
+    double flux_left[2], flux_right[2];
+    double a_leftm,w_leftm, h_leftm, d_leftm, z_leftm, u_leftm, b_leftm, soundspeed_leftm;
+     double a_leftp,w_leftp, h_leftp, d_leftp, z_leftp, u_leftp, b_leftp, soundspeed_leftp;
+ double a_rightm,w_rightm, h_rightm, d_rightm, z_rightm, u_rightm, b_rightm, soundspeed_rightm;
+ double a_rightp,w_rightp, h_rightp, d_rightp, z_rightp, u_rightp, b_rightp, soundspeed_rightp;
+    double s_maxl, s_minl,s_maxr,s_minr, denom;
+    double zphalf,zmhalf,hleftstar,hrightstar;
+    double fluxtemp1,fluxtemp0,speedtemp;
+    double batemp,bphalf,bmhalf;
+
+    zmhalf = max(q_leftm[2],q_leftp[2]);
+    zphalf = max(q_rightm[2],q_rightp[2]);   
+
+    a_leftm  = q_leftm[0];
+    d_leftm = q_leftm[1];
+    z_leftm  = q_leftm[2];
+    h_leftm  = q_leftm[3];
+    u_leftm  = q_leftm[4];
+    b_leftm  = q_leftm[5];
+    w_leftm  = h_leftm+z_leftm;
+
+    a_leftp  = q_leftp[0];
+    d_leftp = q_leftp[1];
+    z_leftp  = q_leftp[2];
+    h_leftp  = q_leftp[3];
+    u_leftp  = q_leftp[4];
+    b_leftp  = q_leftp[5];
+    w_leftp  = h_leftp+z_leftp;
+
+    a_rightm  = q_rightm[0];
+    d_rightm = q_rightm[1];
+    z_rightm  = q_rightm[2];
+    h_rightm  = q_rightm[3];
+    u_rightm  = q_rightm[4];
+    b_rightm  = q_rightm[5];
+    w_rightm  = h_rightm+z_rightm;
+
+    a_rightp  = q_rightp[0];
+    d_rightp = q_rightp[1];
+    z_rightp  = q_rightp[2];
+    h_rightp  = q_rightp[3];
+    u_rightp  = q_rightp[4];
+    b_rightp  = q_rightp[5];
+    w_rightp  = h_rightp+z_rightp;
+
+    hleftstar = q_leftp[3];
+    hrightstar = q_rightm[3];   
+
+    bphalf = min(b_rightm,b_rightp);
+    bmhalf = min(b_leftm,b_leftp);
+
+    soundspeed_leftp = sqrt(g*h_leftp);
+    soundspeed_leftm = sqrt(g*h_leftm);
+    soundspeed_rightp = sqrt(g*h_rightp);
+    soundspeed_rightm = sqrt(g*h_rightm);
+
+    s_maxl = max(u_leftm+soundspeed_leftm, u_leftp+soundspeed_leftp);
+    if (s_maxl < 0.0) s_maxl = 0.0;
+
+    s_minl = min(u_leftm-soundspeed_leftm, u_leftp-soundspeed_leftp);
+    if (s_minl > 0.0) s_minl = 0.0;
+
+    s_maxr = max(u_rightm+soundspeed_rightm, u_rightp+soundspeed_rightp);
+    if (s_maxr < 0.0) s_maxr = 0.0;
+
+    s_minr = min(u_rightm-soundspeed_rightm, u_rightp-soundspeed_rightp);
+    if (s_minr > 0.0) s_minr = 0.0;
+
+    // Flux formulas for left hand side
+    flux_left[0] = d_leftm;
+    flux_left[1] = u_leftm*d_leftm + 0.5*g*h_leftm*h_leftm*b_leftm;
+
+    flux_right[0] = d_leftp;
+    flux_right[1] = u_leftp*d_leftp + 0.5*g*h_leftp*h_leftp*b_leftp;
+
+    
+    // Flux computation for left hand side
+    denom = s_maxl-s_minl;
+    if (denom < epsilon) {
+	for (i=0; i<2; i++) edgeflux[i] = 0.0;
+    } else {
+	edgeflux[0] = s_maxl*flux_left[0] - s_minl*flux_right[0];
+
+        batemp = (q_leftp[3]+q_leftp[2])*b_leftp-(q_leftm[3]+q_leftm[2])*b_leftm;
+       
+	edgeflux[0] = 0.5*(flux_left[0]+flux_right[0]);
+	edgeflux[1] = 0.5*(flux_left[1]+flux_right[1]);
+
+    
+
+    }
+	fluxtemp0 = edgeflux[0];
+        fluxtemp1 = edgeflux[1];
+    
+
+    // Flux formulas for right hand side
+    flux_left[0] = d_rightm;
+    flux_left[1] = u_rightm*d_rightm + 0.5*g*h_rightm*h_rightm*b_rightm;
+
+    flux_right[0] = d_rightp;
+    flux_right[1] = u_rightp*d_rightp + 0.5*g*h_rightp*h_rightp*b_rightp;
+    
+   
+   
+    // Flux computation for right hand side
+    denom = s_maxr-s_minr;
+    if (denom < epsilon) {
+	for (i=0; i<2; i++) edgeflux[i] = 0.0;
+    } else {
+	edgeflux[0] = s_maxr*flux_left[0] - s_minr*flux_right[0];
+
+        batemp = (q_rightp[3]+q_rightp[2])*b_rightp-(q_rightm[3]+q_rightm[2])*b_rightm;
+
+     
+	edgeflux[0] = 0.5*(flux_right[0]+flux_left[0]);
+
+
+	edgeflux[1] = 0.5*(flux_left[1]+flux_right[1]);
+    
+
+    }
+    
+   
+    edgeflux[0]=edgeflux[0]-fluxtemp0;
+    edgeflux[1]=edgeflux[1]-fluxtemp1;
+    
+    edgeflux[1]-=-0.5*0.5*g*(h_rightm+h_leftp)*(b_rightm+b_leftp)*(z_rightm-z_leftp)+0.5*(h_rightm+h_leftp)*(h_rightm+h_leftp)*0.5*0.5*(b_rightm-b_leftp)*g; 
+
+    //edgeflux[1]-=0.5*g*h_rightm*h_rightm*bphalf-0.5*g*hrightstar*hrightstar*b_rightm+0.5*g*hleftstar*hleftstar*b_leftp-0.5*g*h_leftp*h_leftp*bmhalf;
+
+    // printf("edgflux:%f expected:%f \n",edgeflux[1],hrightstar*hrightstar*g*0.5*b_rightm-hleftstar*hleftstar*g*0.5*b_leftp);
+
+    //edgeflux[1]-=g*(1.0/6.0)*(b_rightm*(hleftstar*hleftstar+hrightstar*(hrightstar+2*z_leftp-2*z_rightm)+hleftstar*(hrightstar+z_leftp-z_rightm))-b_leftp*(hleftstar*hleftstar+hrightstar*(hrightstar-z_leftp+z_rightm)+hleftstar*(hrightstar-2*z_leftp+2*z_rightm)));
+
+   
+    //edgeflux[1]-=0.5*g*h_rightm*h_rightm-0.5*g*hrightstar*hrightstar+0.5*g*hleftstar*hleftstar-0.5*g*h_leftp*h_leftp;
+      
+     //edgeflux[1]-=0.5*g*b_rightm*h_rightm*h_rightm-0.5*g*b_leftp*h_leftp*h_leftp;
+         	// Maximal wavespeed
+	if ( (s_maxl-s_minl)<epsilon && (s_maxr-s_minr)<epsilon ){
+	    *max_speed = 0.0;
+	}else{
+	speedtemp = max(fabs(s_maxl),fabs(s_minl));
+        speedtemp = max(speedtemp,fabs(s_maxr));
+        speedtemp = max(speedtemp,fabs(s_minr));
+	*max_speed = speedtemp;
+	}
+
+//printf("%f\n",h_right);
+    return 0;
+}
+
+
+// Computational function for flux computation
+double _compute_fluxes_channel_ext(double cfl,
+			       double timestep,
+			       double epsilon,
+			       double g,
+			       double h0,
+			       long* neighbours,
+			       long* neighbour_vertices,
+			       double* normals,
+			       double* areas,
+			       double* area_edge_values,
+			       double* discharge_edge_values,
+			       double* bed_edge_values,
+			       double* height_edge_values,
+			       double* velocity_edge_values,
+			       double* width_edge_values,
+			       double* area_boundary_values,
+			       double* discharge_boundary_values,
+			       double* bed_boundary_values,
+			       double* height_boundary_values,
+			       double* velocity_boundary_values,
+			       double* width_boundary_values,
+			       double* area_explicit_update,
+			       double* discharge_explicit_update,
+			       int number_of_elements,
+			       double* max_speed_array) {
+
+    double flux[2], qlm[6],qlp[6], qrm[6],qrp[6], edgeflux[2];
+    double max_speed, normal;
+    int k, i, ki, n, m, nm=0;
+    double zstar;
+    for (k=0; k<number_of_elements; k++) {
+	flux[0] = 0.0;
+	flux[1] = 0.0;
+
+       
+	    ki = k*2;
+           
+
+         n = neighbours[ki];
+	    if (n<0) {
+		m = -n-1;
+
+	    qlm[0] = area_boundary_values[m];
+	    qlm[1] = discharge_boundary_values[m];
+	    qlm[2] = bed_boundary_values[m];
+	    qlm[3] = height_boundary_values[m];
+	    qlm[4] = velocity_boundary_values[m];
+            qlm[5] = width_boundary_values[m];
+
+	    }else{
+	m = neighbour_vertices[ki];
+		nm = n*2+m;
+	    
+
+	    qlm[0] = area_edge_values[nm];
+	    qlm[1] = discharge_edge_values[nm];
+	    qlm[2] = bed_edge_values[nm];
+	    qlm[3] = height_edge_values[nm];
+	    qlm[4] = velocity_edge_values[nm];
+            qlm[5] = width_edge_values[nm];
+    }
+	    qlp[0] = area_edge_values[ki];
+	    qlp[1] = discharge_edge_values[ki];
+	    qlp[2] = bed_edge_values[ki];
+	    qlp[3] = height_edge_values[ki];
+	    qlp[4] = velocity_edge_values[ki];
+            qlp[5] = width_edge_values[ki];
+
+         ki = k*2+1;
+           
+
+         n = neighbours[ki];
+	    if (n<0) {
+		m = -n-1;
+            qrp[0] = area_boundary_values[m];
+	    qrp[1] = discharge_boundary_values[m];
+	    qrp[2] = bed_boundary_values[m];
+	    qrp[3] = height_boundary_values[m];
+	    qrp[4] = velocity_boundary_values[m];
+            qrp[5] = width_boundary_values[m];
+          
+
+
+	    }else{
+	m = neighbour_vertices[ki];
+		nm = n*2+m;
+	    
+           
+            qrp[0] = area_edge_values[nm];
+	    qrp[1] = discharge_edge_values[nm];
+	    qrp[2] = bed_edge_values[nm];
+	    qrp[3] = height_edge_values[nm];
+	    qrp[4] = velocity_edge_values[nm];
+            qrp[5] = width_edge_values[nm];
+            }
+            qrm[0] = area_edge_values[ki];
+	    qrm[1] = discharge_edge_values[ki];
+	    qrm[2] = bed_edge_values[ki];
+	    qrm[3] = height_edge_values[ki];
+	    qrm[4] = velocity_edge_values[ki];
+            qrm[5] = width_edge_values[ki];
+
+             _flux_function_channel(qlm,qlp,qrm,qrp,g,epsilon,h0,edgeflux,&max_speed);
+	    flux[0] -= edgeflux[0];
+	    flux[1] -= edgeflux[1];
+           
+	    // Update timestep based on edge i and possibly neighbour n
+	    if (max_speed > epsilon) {
+		// Original CFL calculation
+
+		timestep = min(timestep, 0.5*cfl*areas[k]/max_speed);
+		if (n>=0) {
+		    timestep = min(timestep, 0.5*cfl*areas[n]/max_speed);
+		}
+	    }
+	 // End edge i (and neighbour n)
+	flux[0] /= areas[k];
+	area_explicit_update[k] = flux[0];
+	flux[1] /= areas[k];
+	discharge_explicit_update[k] = flux[1];
+	//Keep track of maximal speeds
+	max_speed_array[k]=max_speed;
+    }
+    return timestep;
+
+}
+
+
+//-------------------------------------------------------------
+// Old code
+//------------------------------------------------------------
+//Innermost flux function (using w=z+h)
+
+
+
+
+
+// Computational function for flux computation
+
+
+//=========================================================================
+// Python Glue
+//=========================================================================
+
+
+
+//------------------------------------------------
+// New velocity based compute fluxes
+//------------------------------------------------
+
+PyObject *compute_fluxes_channel_ext(PyObject *self, PyObject *args) {
+
+    PyObject
+	*domain,
+	*area,
+	*discharge,
+	*bed,
+	*height,
+	*velocity,
+        *width;
+
+    PyArrayObject
+	*neighbours,
+	*neighbour_vertices,
+	*normals,
+	*areas,
+	*area_vertex_values,
+	*discharge_vertex_values,
+	*bed_vertex_values,
+	*height_vertex_values,
+	*velocity_vertex_values,
+	*width_vertex_values,
+	*area_boundary_values,
+	*discharge_boundary_values,
+	*bed_boundary_values,
+	*height_boundary_values,
+	*velocity_boundary_values,
+	*width_boundary_values,
+	*area_explicit_update,
+	*discharge_explicit_update,
+	*max_speed_array;
+
+  double timestep, epsilon, g, h0, cfl;
+  int number_of_elements;
+
+
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "dOOOOOOO",
+			&timestep,
+			&domain,
+			&area,
+			&discharge,
+			&bed,
+			&height,
+			&velocity,
+                        &width)) {
+      PyErr_SetString(PyExc_RuntimeError, "comp_flux_channel_ext.c: compute_fluxes_channel_ext could not parse input");
+      return NULL;
+  }
+
+
+    epsilon           = get_python_double(domain,"epsilon");
+    g                 = get_python_double(domain,"g");
+    h0                = get_python_double(domain,"h0");
+    cfl               = get_python_double(domain,"CFL");
+
+
+    neighbours        = get_consecutive_array(domain, "neighbours");
+    neighbour_vertices= get_consecutive_array(domain, "neighbour_vertices");
+    normals           = get_consecutive_array(domain, "normals");
+    areas             = get_consecutive_array(domain, "areas");
+    max_speed_array   = get_consecutive_array(domain, "max_speed_array");
+
+    area_vertex_values      = get_consecutive_array(area,    "vertex_values");
+    discharge_vertex_values       = get_consecutive_array(discharge,     "vertex_values");
+    bed_vertex_values        = get_consecutive_array(bed,      "vertex_values");
+    height_vertex_values     = get_consecutive_array(height,   "vertex_values");
+    velocity_vertex_values   = get_consecutive_array(velocity, "vertex_values");
+    width_vertex_values      = get_consecutive_array(width, "vertex_values");
+
+    area_boundary_values     = get_consecutive_array(area,     "boundary_values");
+    discharge_boundary_values      = get_consecutive_array(discharge,      "boundary_values");
+    bed_boundary_values       = get_consecutive_array(bed,       "boundary_values");
+    height_boundary_values    = get_consecutive_array(height,    "boundary_values");
+    velocity_boundary_values  = get_consecutive_array(velocity,  "boundary_values");
+    width_boundary_values       = get_consecutive_array(width,     "boundary_values");
+
+
+    area_explicit_update = get_consecutive_array(area, "explicit_update");
+    discharge_explicit_update  = get_consecutive_array(discharge,  "explicit_update");
+
+    number_of_elements = area_vertex_values -> dimensions[0];
+
+    // Call underlying flux computation routine and update
+    // the explicit update arrays
+    timestep = _compute_fluxes_channel_ext(cfl,
+				       timestep,
+				       epsilon,
+				       g,
+				       h0,
+				       (long*) neighbours -> data,
+				       (long*) neighbour_vertices -> data,
+				       (double*) normals -> data,
+				       (double*) areas -> data,
+				       (double*) area_vertex_values -> data,
+				       (double*) discharge_vertex_values -> data,
+				       (double*) bed_vertex_values -> data,
+				       (double*) height_vertex_values -> data,
+				       (double*) velocity_vertex_values -> data,
+				       (double*) width_vertex_values -> data,
+				       (double*) area_boundary_values -> data,
+				       (double*) discharge_boundary_values -> data,
+				       (double*) bed_boundary_values -> data,
+				       (double*) height_boundary_values -> data,
+				       (double*) velocity_boundary_values -> data,
+				       (double*) width_boundary_values -> data,
+				       (double*) area_explicit_update -> data,
+				       (double*) discharge_explicit_update -> data,
+				       number_of_elements,
+				       (double*) max_speed_array -> data);
+
+
+    Py_DECREF(neighbours);
+    Py_DECREF(neighbour_vertices);
+    Py_DECREF(normals);
+    Py_DECREF(areas);
+    Py_DECREF(area_vertex_values);
+    Py_DECREF(discharge_vertex_values);
+    Py_DECREF(bed_vertex_values);
+    Py_DECREF(height_vertex_values);
+    Py_DECREF(velocity_vertex_values);
+    Py_DECREF(width_vertex_values);
+    Py_DECREF(area_boundary_values);
+    Py_DECREF(discharge_boundary_values);
+    Py_DECREF(bed_boundary_values);
+    Py_DECREF(height_boundary_values);
+    Py_DECREF(velocity_boundary_values);
+    Py_DECREF(width_boundary_values);
+    Py_DECREF(area_explicit_update);
+    Py_DECREF(discharge_explicit_update);
+    Py_DECREF(max_speed_array);
+
+
+    // Return updated flux timestep
+    return Py_BuildValue("d", timestep);
+}
+
+
+//-------------------------------
+// Method table for python module
+//-------------------------------
+
+static struct PyMethodDef MethodTable[] = {
+  {"compute_fluxes_channel_ext", compute_fluxes_channel_ext, METH_VARARGS, "Print out"},
+  {NULL}
+};
+
+/* // Module initialisation */
+/* void initcomp_flux_vel_ext(void){ */
+/*   Py_InitModule("comp_flux_vel_ext", MethodTable); */
+/*   import_array(); */
+/* } */
+
+void initchannel_domain_ext(void){
+  Py_InitModule("channel_domain_ext", MethodTable);
+  import_array();
+}
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_flow_1_padarn.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_flow_1_padarn.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_flow_1_padarn.py	(revision 7884)
@@ -0,0 +1,105 @@
+import os
+from math import sqrt, pow, pi
+
+import numpy
+
+from anuga_1d.channel.channel_domain import *
+from anuga_1d.config import g, epsilon
+from anuga_1d.base.generic_mesh import interval_mesh
+
+
+print "Channel Flow 1 Padarn Test"
+
+# Define functions for initial quantities
+def initial_area(x):
+    return 1.4691*width(x)
+
+def width(x):
+    x1=(x/1000)*(x/1000)
+    x2=x1*(x/1000)
+    x3=x2*(x/1000)
+    return 10-64*(x1-2*x2+x3)
+
+def bed(x):
+    y = numpy.ones(len(x),numpy.float)
+
+    return numpy.where( (x<525) & (x>475),y,0.0)
+    
+
+def initial_discharge(x):
+    return 20
+ 
+import time
+
+# Set final time and yield time for simulation
+finaltime = 50.0
+yieldstep = 10.0
+
+# Length of channel (m)
+L = 1000.0   
+# Define the number of cells
+N = 200
+
+# Create domain with centroid points as defined above        
+domain = Domain(*interval_mesh(N))
+
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('area', initial_area)
+domain.set_quantity('width',width)
+domain.set_quantity('elevation',bed)
+domain.set_quantity('discharge',initial_discharge)
+
+# Set boundry type, order, timestepping method and limiter
+Bd = Dirichlet_boundary([14,20,0,1.4,20/14,9,1.4])
+domain.set_boundary({'left': Bd , 'right' : Bd })
+
+
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+
+exit()
+
+HeightC    = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C          = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X          = domain.vertices
+HeightQ    = domain.quantities['height'].vertex_values
+VelocityQ  = domain.quantities['velocity'].vertex_values
+Z = domain.quantities['elevation'].vertex_values
+Stage      = HeightQ+Z
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+hold(False)
+   
+plot1 = subplot(211)
+
+plot(X.flat,Z.flat,X.flat,Stage.flat)
+ 
+plot1.set_ylim([-1,11])
+xlabel('Position')
+ylabel('Stage')
+legend(('Analytical Solution', 'Numerical Solution'),
+           'upper right', shadow=True)
+
+plot2 = subplot(212)
+plot(X.flat,VelocityQ.flat)
+plot2.set_ylim([-10,10])
+    
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
+    
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_flow_2_padarn.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_flow_2_padarn.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/channel_flow_2_padarn.py	(revision 7884)
@@ -0,0 +1,110 @@
+import os
+from math import sqrt, pow, pi 
+from channel_domain import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+print "Channel Flow 1 Padarn Test"
+
+# Define functions for initial quantities
+def initial_area(x):
+    return 1.4691*width(x)
+
+def width(x):
+    x1=(x/1000)*(x/1000)
+    x2=x1*(x/1000)
+    x3=x2*(x/1000)
+    return 10-64*(x1-2*x2+x3)
+
+def bed(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        if x[i]<525 and x[i]>475:
+            y[i]=0
+        else:
+            y[i]=0
+    return y
+ 
+
+def initial_discharge(x):
+    return 20
+ 
+import time
+
+# Set final time and yield time for simulation
+finaltime = 10.0
+yieldstep = finaltime
+
+# Length of channel (m)
+L = 1000.0   
+# Define the number of cells
+number_of_cells = [200]
+
+# Define cells for finite volume and their size
+N = int(number_of_cells[0])     
+print "Evaluating domain with %d cells" %N
+cell_len = L/N # Origin = 0.0
+points = zeros(N+1,Float)
+
+# Define the centroid points
+for j in range(N+1):
+    points[j] = j*cell_len
+
+# Create domain with centroid points as defined above        
+domain = Domain(points)
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('area', initial_area)
+domain.set_quantity('width',width)
+domain.set_quantity('elevation',bed)
+domain.set_quantity('discharge',initial_discharge)
+
+# Set boundry type, order, timestepping method and limiter
+domain.set_boundary({'exterior': Dirichlet_boundary([14,20,0,1.4,20/14,9])})
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+N = float(N)
+HeightC = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X = domain.vertices
+HeightQ = domain.quantities['height'].vertex_values
+VelocityQ = domain.quantities['velocity'].vertex_values
+x = X.flat
+z = domain.quantities['elevation'].vertex_values.flat
+stage=HeightQ.flat+z
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+hold(False)
+   
+plot1 = subplot(211)
+
+plot(x,z,x,stage)
+ 
+plot1.set_ylim([-1,11])
+xlabel('Position')
+ylabel('Stage')
+legend(('Analytical Solution', 'Numerical Solution'),
+           'upper right', shadow=True)
+plot2 = subplot(212)
+plot(x,VelocityQ.flat)
+plot2.set_ylim([-10,10])
+    
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
+    
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/dam_padarn.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/dam_padarn.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/dam_padarn.py	(revision 7884)
@@ -0,0 +1,177 @@
+import os
+from math import sqrt, pi
+from channel_domain_Ab import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+h1 = 5.0
+h0 = 0.0
+
+def analytical_sol(C,t):
+    if t==0:
+        t=0.0001
+    #t  = 0.0     # time (s)
+    # 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))
+        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 ( x[i] <= -1*L/2.0+2*(-sqrt(g*h1)*t)):
+            u[i] = 0.0
+            h[i] = h0
+        elif ( x[i] <= -1*L/2.0-(-sqrt(g*h1)*t)):
+            u[i] = u3_
+            h[i] = h3_
+
+        elif ( 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, u
+
+#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)
+
+h2=5.0
+k=1
+
+print "TEST 1D-SOLUTION III -- DRY BED"
+
+def stage(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        if x[i]<=L/4.0:
+            y[i] = h0*width([x[i]])
+        elif x[i]<=3*L/4.0:
+            y[i] = h2*width([x[i]])
+        else:
+            y[i] = h0*width([x[i]])
+    return y
+
+def width(x):
+    return k
+
+ 
+import time
+
+finaltime = 10.0
+yieldstep = finaltime
+L = 2000.0     # Length of channel (m)
+number_of_cells = [810]
+k = 0
+widths = [1,2,5]
+heights= []
+velocities = []
+
+for i in range(len(widths)):
+    k=widths[i]
+    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('area', stage)
+        domain.set_quantity('width',width)
+        print "width in cell 1",domain.quantities['width'].vertex_values[1]
+        domain.set_boundary({'exterior': Reflective_boundary(domain)})
+        domain.order = 2
+        domain.set_timestepping_method('rk2')
+        domain.set_CFL(1.0)
+        domain.set_limiter("vanleer")
+        #domain.h0=0.0001
+ 
+        t0 = time.time()
+
+        for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):            
+            domain.write_time()
+
+        N = float(N)
+        HeightC = domain.quantities['height'].centroid_values 
+        DischargeC = domain.quantities['discharge'].centroid_values
+        C = domain.centroids
+        h, uh, u = analytical_sol(C,domain.time)
+        h_error = 1.0/(N)*sum(abs(h-HeightC))
+        u_error = 1.0/(N)*sum(abs(uh-DischargeC))
+        #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
+        heights.append(domain.quantities['height'].vertex_values)
+        velocities.append( domain.quantities['velocity'].vertex_values)
+        #stage = domain.quantities['stage'].vertex_values
+        h, uh, u = analytical_sol(X.flat,domain.time)
+        x = X.flat
+            
+        print "Error in height", h_error
+        print "Error in xmom", u_error
+        #from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+from pylab import *
+import pylab as p
+import matplotlib.axes3d as p3
+print 'test 2'
+#hold(False)
+print 'test 3'
+plot1 = subplot(211)
+print 'test 4'
+plot(x,heights[0].flat,x,h)
+print 'test 5'
+plot1.set_ylim([-1,11])
+xlabel('Position')
+ylabel('Stage')
+legend(('Numerical Solution','Analytic Soltuion'), 'upper right', shadow=True)
+plot2 = subplot(212)
+
+
+plot(x,velocities[0].flat,x,u)
+plot2.set_ylim([-35,35])
+xlabel('Position')
+ylabel('Velocity')
+
+print heights[0].flat-heights[1].flat
+   
+file = "dry_bed_"
+file += str(number_of_cells[i])
+file += ".eps"
+#savefig(file)
+show()
+    
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/parabolic_cannal_padarn.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/parabolic_cannal_padarn.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/parabolic_cannal_padarn.py	(revision 7884)
@@ -0,0 +1,122 @@
+import os
+import random
+from math import sqrt, pow, pi ,sin, cos
+from channel_domain import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+print "Variable Width Only Test"
+
+# Define functions for initial quantities
+def initial_area(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
+
+def width(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=1
+    return y
+
+def bed(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
+
+import time
+
+# Set final time and yield time for simulation
+finaltime = 10.0
+yieldstep = finaltime
+
+# Length of channel (m)
+L = 2500.0   
+# Define the number of cells
+number_of_cells = [200]
+
+# Define cells for finite volume and their size
+N = int(number_of_cells[0])     
+print "Evaluating domain with %d cells" %N
+cell_len = L/N*4 # Origin = 0.0
+points = zeros(N+1,Float)
+
+# Define the centroid points
+points = zeros(N+1,Float)
+for i in range(N+1):
+        points[i] = -2*L +i*cell_len
+
+# Create domain with centroid points as defined above        
+domain = Domain(points)
+
+# Define random array for width
+randomarray=zeros(len(points),Float)
+for j in range(N+1):
+    randomarray[j]=random.normalvariate(5,1)
+
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('area', initial_area)
+domain.set_quantity('width',width)
+domain.set_quantity('elevation',bed)
+
+# Set boundry type, order, timestepping method and limiter
+domain.set_boundary({'exterior':Reflective_boundary(domain)})
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+N = float(N)
+HeightC = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X = domain.vertices
+HeightQ = domain.quantities['height'].vertex_values
+VelocityQ = domain.quantities['velocity'].vertex_values
+x = X.flat
+b = domain.quantities['elevation'].vertex_values.flat
+stage=HeightQ.flat+b
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+hold(False)
+   
+plot1 = subplot(211)
+
+plot(x,b,x,stage)
+ 
+plot1.set_ylim([-1,20])
+xlabel('Position')
+ylabel('Stage')
+legend(('Analytical Solution', 'Numerical Solution'),
+           'upper right', shadow=True)
+plot2 = subplot(212)
+plot(x,VelocityQ.flat)
+plot2.set_ylim([-10,10])
+    
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/profile_channel.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/profile_channel.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/profile_channel.py	(revision 7884)
@@ -0,0 +1,99 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="steve"
+__date__ ="$15/06/2010 5:02:36 PM$"
+
+
+import os
+from math import sqrt, pow, pi
+
+import numpy
+
+from anuga_1d.channel.channel_domain import *
+from anuga_1d.config import g, epsilon
+from anuga_1d.base.generic_mesh import uniform_mesh
+
+
+def run_evolve():
+
+
+    print "Channel Flow 1 Padarn Test"
+
+    # Define functions for initial quantities
+    def initial_area(x):
+        return 1.4691*width(x)
+
+    def width(x):
+        x1=(x/1000)*(x/1000)
+        x2=x1*(x/1000)
+        x3=x2*(x/1000)
+        return 10-64*(x1-2*x2+x3)
+
+    def bed(x):
+        y = numpy.ones(len(x),numpy.float)
+
+        return numpy.where( (x<525) & (x>475),y,0.0)
+
+
+    def initial_discharge(x):
+        return 20
+
+    import time
+
+    # Set final time and yield time for simulation
+    finaltime = 50.0
+    yieldstep = 10.0
+
+    # Length of channel (m)
+    L = 1000.0
+    # Define the number of cells
+    N = 200
+
+    # Create domain with centroid points as defined above
+    domain = Domain(*uniform_mesh(N))
+
+
+    # Set initial values of quantities - default to zero
+    domain.set_quantity('area', initial_area)
+    domain.set_quantity('width',width)
+    domain.set_quantity('elevation',bed)
+    domain.set_quantity('discharge',initial_discharge)
+
+    # Set boundry type, order, timestepping method and limiter
+    Bd = Dirichlet_boundary([14,20,0,1.4,20/14,9,1.4])
+    domain.set_boundary({'left': Bd , 'right' : Bd })
+
+
+    domain.order = 2
+    domain.set_timestepping_method('rk2')
+    domain.set_CFL(1.0)
+    domain.set_limiter("vanleer")
+    #domain.set_limiter("minmod")
+    #domain.h0=0.0001
+
+    # Start timer
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        domain.write_time()
+
+
+
+import cProfile
+cProfile.run('run_evolve()', 'evolve_prof')
+
+
+import pstats
+p = pstats.Stats('evolve_prof')
+
+#p.strip_dirs().sort_stats(-1).print_stats(20)
+
+p.sort_stats('cumulative').print_stats(30)
+
+
+
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/straight_padarn.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/straight_padarn.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/straight_padarn.py	(revision 7884)
@@ -0,0 +1,165 @@
+import os
+from math import sqrt, pi
+from channel_domain import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+h1 = 5.0
+h0 = 0.0
+
+## def analytical_sol(C,t):
+    
+##     #t  = 0.0     # time (s)
+##     # 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))
+##         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 ( x[i] <= -1*L/2.0+2*(-sqrt(g*h1)*t)):
+##             u[i] = 0.0
+##             h[i] = h0
+##         elif ( x[i] <= -1*L/2.0-(-sqrt(g*h1)*t)):
+##             u[i] = u3_
+##             h[i] = h3_
+
+##         elif ( 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, u
+
+#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)
+
+h2=10.0
+
+print "TEST 1D-SOLUTION III -- DRY BED"
+
+def stage(x):
+    return 5
+
+def width(x):
+    return 1
+
+def bot(x):
+    return x/500
+ 
+import time
+
+finaltime = 20.0
+yieldstep = finaltime
+L = 2000.0     # Length of channel (m)
+number_of_cells = [810]#,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('area', stage)
+    domain.set_quantity('width',width)
+    domain.set_quantity('elevation',bot)
+    domain.set_boundary({'exterior': Reflective_boundary(domain)})
+    domain.order = 2
+    domain.set_timestepping_method('rk2')
+    domain.set_CFL(1.0)
+    domain.set_limiter("vanleer")
+    #domain.h0=0.0001
+
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        domain.write_time()
+
+    N = float(N)
+    HeightC = domain.quantities['height'].centroid_values
+    DischargeC = domain.quantities['discharge'].centroid_values
+    C = domain.centroids
+    #h, uh, u = 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
+    HeightQ = domain.quantities['height'].vertex_values
+    VelocityQ = domain.quantities['velocity'].vertex_values
+    #stage = domain.quantities['stage'].vertex_values
+    #h, uh, u = analytical_sol(X.flat,domain.time)
+    x = X.flat
+    z =bot(x)
+    w=HeightQ.flat+z
+    
+    #from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+    from pylab import *
+    import pylab as p
+    import matplotlib.axes3d as p3
+    print 'test 2'
+    hold(False)
+    print 'test 3'
+    plot1 = subplot(211)
+    print 'test 4'
+    plot(x,z,x,w)
+    print 'test 5'
+    plot1.set_ylim([-1,11])
+    xlabel('Position')
+    ylabel('Stage')
+    #legend(( 'Numerical Solution'),
+    #       'upper right', shadow=True)
+    plot2 = subplot(212)
+    plot(x,VelocityQ.flat)
+    plot2.set_ylim([-2,2])
+    
+    xlabel('Position')
+    ylabel('Velocity')
+   
+    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: trunk/anuga_work/development/2010-projects/anuga_1d/channel/test_all.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/test_all.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/test_all.py	(revision 7884)
@@ -0,0 +1,83 @@
+"""Regression testing framework
+This module will search for scripts in the same directory named
+test_*.py.  Each such script should be a test suite that tests a
+module through PyUnit. This script will aggregate all
+found test suites into one big test suite and run them all at once.
+"""
+
+# Author: Mark Pilgrim
+# Modified by Ole Nielsen
+
+import unittest
+import os
+
+
+#List files that should be excluded from the testing process.
+#E.g. if they are known to fail and under development
+exclude = [] 
+
+
+def get_test_files(path):
+
+    import sys
+
+    files = os.listdir(path)
+
+    #Check sub directories
+    test_files = []
+    for file in files:
+        if os.path.isdir(file):
+            sys.path.append(file)
+            #print 'Recursing into', file
+            test_files += get_test_files(path + os.sep + file)
+        elif file[:5] == 'test_' and file[-2:] == 'py':
+            #print 'Appending', file
+            test_files.append(file)
+        else:
+            pass
+    return test_files
+
+
+
+def regressionTest():
+    import sys, os, re, unittest
+    path = os.path.split(sys.argv[0])[0] or os.getcwd()
+
+
+    files = get_test_files(path)
+
+
+
+    #test = re.compile('^test_[\w]*.py$', re.IGNORECASE)
+    #files = filter(test.search, files)
+
+
+    try:
+        files.remove(__file__)  #Remove self from list (Ver 2.3. or later)
+    except:
+        files.remove('test_all.py')
+
+    print 'Testing:'
+    for file in files:
+        print '  ' + file
+
+    if globals().has_key('exclude'):
+        for file in exclude:
+            files.remove(file)
+            print 'WARNING: File '+ file + ' excluded from testing'
+
+
+    filenameToModuleName = lambda f: os.path.splitext(f)[0]
+    #print "files",files 
+    moduleNames = map(filenameToModuleName, files)
+    #print "moduleNames",moduleNames
+    modules = map(__import__, moduleNames)
+    load = unittest.defaultTestLoader.loadTestsFromModule
+    return unittest.TestSuite(map(load, modules))
+
+################################################################################
+
+if __name__ == '__main__':   
+    suite = regressionTest()
+    runner = unittest.TextTestRunner() #verbosity=2)
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/test_padarn.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/test_padarn.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/test_padarn.py	(revision 7884)
@@ -0,0 +1,130 @@
+import os
+import random
+from math import sqrt, pow, pi ,sin, cos
+import numpy
+
+from anuga_1d.channel.channel_domain import *
+
+from anuga_1d.config import g, epsilon
+
+
+
+print "Variable Width Only Test"
+
+# Define functions for initial quantities
+def initial_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 = numpy.zeros(len(x),numpy.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))
+        y[i] = 12.0
+    return y
+
+def bed(x):
+    N = len(x)
+    z_infty = 10.0
+    z = numpy.zeros(N,numpy.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 initial_area(x):
+    y = numpy.zeros(len(x),numpy.float)
+    for i in range(len(x)):
+        y[i]=initial_stage([x[i]])-bed([x[i]])
+
+    return y
+
+def width(x):
+    return 1
+ 
+import time
+
+
+
+# Set final time and yield time for simulation
+finaltime = 10.0
+yieldstep = finaltime
+
+# Length of channel (m)
+L = 2500.0
+# Define the number of cells
+number_of_cells = [50]
+
+# Define cells for finite volume and their size
+N = int(number_of_cells[0])     
+print "Evaluating domain with %d cells" %N
+cell_len = 4*L/N # Origin = 0.0
+points = numpy.zeros(N+1,numpy.float)
+for i in range(N+1):
+        points[i] = -2*L +i*cell_len
+
+
+
+# Create domain with centroid points as defined above        
+domain = Domain(points)
+
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('area', initial_area)
+domain.set_quantity('elevation',bed)
+domain.set_quantity('width',width)
+
+# Set boundry type, order, timestepping method and limiter
+domain.set_boundary({'exterior':Reflective_boundary(domain)})
+domain.order = 2
+domain.set_timestepping_method('euler')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+
+
+
+
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+N = float(N)
+HeightC    = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C          = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X          = domain.vertices
+HeightQ    = domain.quantities['area'].vertex_values
+VelocityQ  = domain.quantities['velocity'].vertex_values
+Z          = domain.quantities['elevation'].vertex_values
+Stage      = HeightQ + Z
+
+
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+hold(False)
+   
+plot1 = subplot(211)
+plot(X.flat,Z.flat, X.flat,Stage.flat)
+ 
+plot1.set_ylim([-1,35])
+xlabel('Position')
+ylabel('Stage')
+legend(('Analytical Solution', 'Numerical Solution'),
+           'upper right', shadow=True)
+plot2 = subplot(212)
+plot(X.flat,VelocityQ.flat)
+plot2.set_ylim([-10,10])
+    
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_depth_only.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_depth_only.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_depth_only.py	(revision 7884)
@@ -0,0 +1,171 @@
+import os
+import random
+from math import sqrt, pow, pi 
+from channel_domain_Ab import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+print "Variable Width Only Test"
+
+# Define functions for initial quantities
+def initial_area(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=(10-randomarray[i])
+
+   
+    return y
+
+def bed(x):
+
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=randomarray[i]
+        randomarray[i]=random.normalvariate(3,1)
+    return y
+
+def stage(x):
+
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=3+x[i]/2000
+    return y
+  
+
+
+def width(x):
+    return 1
+ 
+import time
+
+# Set final time and yield time for simulation
+finaltime = 1
+yieldstep = 0.1
+
+# Length of channel (m)
+L = 1000.0   
+# Define the number of cells
+number_of_cells = [50]
+
+# Define cells for finite volume and their size
+N = int(number_of_cells[0])     
+print "Evaluating domain with %d cells" %N
+cell_len = L/N # Origin = 0.0
+points = zeros(N+1,Float)
+
+# Define the centroid points
+for j in range(N+1):
+    points[j] = j*cell_len
+
+# Create domain with centroid points as defined above        
+domain = Domain(points)
+
+# Define random array for width
+
+randomarray=zeros(len(points),Float)
+for j in range(N+1):
+    randomarray[j]=random.normalvariate(3,1)
+
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('stage',stage)
+#domain.set_quantity('area', initial_area)
+domain.set_quantity('elevation',bed)
+domain.set_quantity('width',width)
+domain.setstageflag = True
+# Set boundry type, order, timestepping method and limiter
+domain.set_boundary({'exterior':Reflective_boundary(domain)})
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+i=1
+
+print domain.quantities['elevation'].vertex_values
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+    N = float(N)
+    HeightC = domain.quantities['height'].centroid_values
+    DischargeC = domain.quantities['discharge'].centroid_values
+    C = domain.centroids
+    print 'That took %.2f seconds' %(time.time()-t0)
+    X = domain.vertices
+    HeightQ = domain.quantities['height'].vertex_values
+    VelocityQ = domain.quantities['velocity'].vertex_values
+    x = X.flat
+    z = domain.quantities['elevation'].vertex_values.flat
+    stage=HeightQ.flat+z
+
+
+
+
+    from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot,savefig
+    import pylab as p
+#hold(False)
+   
+    plot1=subplot(211)
+
+    plot(x,stage,x,z)
+ 
+    plot1.set_ylim([-1,11])
+    xlabel('Position')
+    ylabel('Stage')
+    legend(('Solution', 'Bed Height'),
+                'upper right', shadow=True)
+
+    plot2=subplot(212)
+    plot(x,VelocityQ.flat)
+    plot2.set_ylim([-5,5])
+    xlabel('Position') 
+    ylabel('Velocity')
+
+    savefig(str(i)+'.png')
+    i+=1
+    plot1.clear()
+
+print domain.quantities['elevation'].vertex_values
+
+N = float(N)
+HeightC = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X = domain.vertices
+HeightQ = domain.quantities['height'].vertex_values
+VelocityQ = domain.quantities['velocity'].vertex_values
+x = X.flat
+z = domain.quantities['elevation'].vertex_values.flat
+stage=HeightQ.flat+z
+
+
+
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+#hold(False)
+   
+plot1=subplot(211)
+
+plot(x,stage,x,z)
+ 
+plot1.set_ylim([-1,11])
+xlabel('Position')
+ylabel('Stage')
+legend(('Solution', 'Bed Height'),
+           'upper right', shadow=True)
+
+plot2=subplot(212)
+plot(x,VelocityQ.flat)
+plot2.set_ylim([-5,5])
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_depth_only2.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_depth_only2.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_depth_only2.py	(revision 7884)
@@ -0,0 +1,116 @@
+import os
+import random
+from math import sqrt, pow, pi 
+from channel_domain_Ab import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+print "Variable Width Only Test"
+
+# Define functions for initial quantities
+def initial_area(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        #if x[i]>=500:
+        #    y[i]=0
+        #else:
+       # if x[i]<900:
+        y[i]=(5-bed([x[i]]))*bed([x[i]])
+       # else:
+         #   y[i]=10-bed([x[i]])
+    return y
+
+def bed(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        if x[i]>100:
+            y[i]=2
+        else:
+            y[i]=1
+    return y
+
+def width(x):
+    return 1
+
+
+ 
+import time
+
+# Set final time and yield time for simulation
+finaltime =100.0
+yieldstep = finaltime
+
+# Length of channel (m)
+L = 1000.0   
+# Define the number of cells
+number_of_cells = [10]
+
+# Define cells for finite volume and their size
+N = int(number_of_cells[0])     
+print "Evaluating domain with %d cells" %N
+cell_len = L/N # Origin = 0.0
+points = zeros(N+1,Float)
+
+# Define the centroid points
+for j in range(N+1):
+    points[j] = j*cell_len
+
+# Create domain with centroid points as defined above        
+domain = Domain(points)
+
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('area', initial_area)
+domain.set_quantity('elevation',bed)
+domain.set_quantity('width',bed)
+
+# Set boundry type, order, timestepping method and limiter
+domain.set_boundary({'exterior':Reflective_boundary(domain)})
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+N = float(N)
+HeightC = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X = domain.vertices
+HeightQ = domain.quantities['height'].vertex_values
+VelocityQ = domain.quantities['velocity'].vertex_values
+x = X.flat
+z = domain.quantities['elevation'].vertex_values.flat
+stage=HeightQ.flat+z
+b = domain.quantities['width'].vertex_values.flat
+
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+hold(False)
+   
+plot1 = subplot(211)
+
+plot(x,z,x,stage,x,b)
+ 
+plot1.set_ylim([-1,11])
+xlabel('Position')
+ylabel('Stage')
+## legend(('Analytical Solution', 'Numerical Solution'),
+##            'upper right', shadow=True)
+plot2 = subplot(212)
+plot(x,VelocityQ.flat)
+plot2.set_ylim([-10,10])
+    
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_depth.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_depth.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_depth.py	(revision 7884)
@@ -0,0 +1,143 @@
+import os
+import random
+from math import sqrt, pow, pi 
+from channel_domain_Ab import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+print "Variable Width Only Test"
+
+# Define functions for initial quantities
+def initial_area(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=(10-randomarray[i])
+
+   
+    return y
+
+def width(x):
+
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=randomarray[i]
+        randomarray[i]=random.normalvariate(3,1)
+    return y
+
+def bed(x):
+
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=randomarray2[i]
+        randomarray2[i]=random.normalvariate(3,1)
+    return y
+
+
+
+def stage(x):
+
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        if x[i]<200 and x[i]>150:
+            y[i]=8.0
+        else:
+            y[i]=8.0
+    return y
+  
+
+
+ 
+import time
+
+# Set final time and yield time for simulation
+finaltime = 10.0
+yieldstep = finaltime
+
+# Length of channel (m)
+L = 1000.0   
+# Define the number of cells
+number_of_cells = [100]
+
+# Define cells for finite volume and their size
+N = int(number_of_cells[0])     
+print "Evaluating domain with %d cells" %N
+cell_len = L/N # Origin = 0.0
+points = zeros(N+1,Float)
+
+# Define the centroid points
+for j in range(N+1):
+    points[j] = j*cell_len
+
+# Create domain with centroid points as defined above        
+domain = Domain(points)
+
+# Define random array for width
+randomarray=zeros(len(points),Float)
+for j in range(N+1):
+    randomarray[j]=random.normalvariate(3,1)
+randomarray2=zeros(len(points),Float)
+for j in range(N+1):
+    randomarray2[j]=random.normalvariate(3,1)
+
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('stage',stage,'centroids')
+domain.set_quantity('elevation', bed)
+domain.set_quantity('width',width)
+domain.setstageflag = True
+# Set boundry type, order, timestepping method and limiter
+domain.set_boundary({'exterior':Reflective_boundary(domain)})
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+
+print domain.quantities['elevation'].vertex_values
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+print domain.quantities['elevation'].vertex_values
+
+N = float(N)
+HeightC = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X = domain.vertices
+HeightQ = domain.quantities['height'].vertex_values
+VelocityQ = domain.quantities['velocity'].vertex_values
+x = X.flat
+z = domain.quantities['elevation'].vertex_values.flat
+b = domain.quantities['width'].vertex_values.flat
+stage=HeightQ.flat+z
+
+
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+#hold(False)
+   
+plot1=subplot(211)
+
+plot(x,stage,x,z,x,b)
+ 
+plot1.set_ylim([-5,15])
+xlabel('Position')
+ylabel('Stage')
+legend(('Solution', 'Bed','Width'),
+            'upper right', shadow=True)
+
+plot2=subplot(212)
+plot(x,VelocityQ.flat)
+plot2.set_ylim([-10,10])
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_only.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_only.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_only.py	(revision 7884)
@@ -0,0 +1,127 @@
+import os
+import random
+from math import sqrt, pow, pi 
+from channel_domain_Ab import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+print "Variable Width Only Test"
+
+# Define functions for initial quantities
+def initial_area(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=(10-randomarray[i])
+
+   
+    return y
+
+def width(x):
+
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=randomarray[i]
+        randomarray[i]=random.normalvariate(3,1)
+    return y
+
+def stage(x):
+
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=8.0
+    return y
+  
+
+
+ 
+import time
+
+# Set final time and yield time for simulation
+finaltime = 10.0
+yieldstep = finaltime
+
+# Length of channel (m)
+L = 1000.0   
+# Define the number of cells
+number_of_cells = [50]
+
+# Define cells for finite volume and their size
+N = int(number_of_cells[0])     
+print "Evaluating domain with %d cells" %N
+cell_len = L/N # Origin = 0.0
+points = zeros(N+1,Float)
+
+# Define the centroid points
+for j in range(N+1):
+    points[j] = j*cell_len
+
+# Create domain with centroid points as defined above        
+domain = Domain(points)
+
+# Define random array for width
+
+randomarray=zeros(len(points),Float)
+for j in range(N+1):
+    randomarray[j]=random.normalvariate(3,1)
+
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('stage',stage)
+#domain.set_quantity('area', initial_area)
+domain.set_quantity('width',width)
+domain.setstageflag = True
+# Set boundry type, order, timestepping method and limiter
+domain.set_boundary({'exterior':Reflective_boundary(domain)})
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+
+print domain.quantities['elevation'].vertex_values
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+print domain.quantities['elevation'].vertex_values
+
+N = float(N)
+HeightC = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X = domain.vertices
+HeightQ = domain.quantities['height'].vertex_values
+VelocityQ = domain.quantities['velocity'].vertex_values
+x = X.flat
+z = domain.quantities['width'].vertex_values.flat
+stage=HeightQ.flat+0
+
+
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+#hold(False)
+   
+plot1=subplot(211)
+
+plot(x,stage,x,z)
+ 
+plot1.set_ylim([-1,11])
+xlabel('Position')
+ylabel('Stage')
+legend(('Solution', 'Width'),
+            'upper right', shadow=True)
+
+plot2=subplot(212)
+plot(x,VelocityQ.flat)
+plot2.set_ylim([-5,5])
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_only_random.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_only_random.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/channel/var_width_only_random.py	(revision 7884)
@@ -0,0 +1,114 @@
+import os
+import random
+from math import sqrt, pow, pi 
+from channel_domain_Ab import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+
+print "Variable Width Only Test"
+
+# Define functions for initial quantities
+def initial_area(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=(10*randomarray[i])
+    return y
+
+def width(x):
+    y = zeros(len(x),Float)
+    for i in range(len(x)):
+        y[i]=randomarray[i]
+    return y
+
+
+ 
+import time
+
+# Set final time and yield time for simulation
+finaltime = 20.0
+yieldstep = finaltime
+
+# Length of channel (m)
+L = 1000.0   
+# Define the number of cells
+number_of_cells = [200]
+
+# Define cells for finite volume and their size
+N = int(number_of_cells[0])     
+print "Evaluating domain with %d cells" %N
+cell_len = L/N # Origin = 0.0
+points = zeros(N+1,Float)
+
+# Define the centroid points
+for j in range(N+1):
+    points[j] = j*cell_len
+
+# Create domain with centroid points as defined above        
+domain = Domain(points)
+
+# Define random array for width
+randomarray=zeros(len(points),Float)
+for j in range(N+1):
+    randomarray[j]=random.normalvariate(5,1)
+
+
+
+# Set initial values of quantities - default to zero
+domain.set_quantity('area', initial_area)
+domain.set_quantity('width',width)
+
+
+
+# Set boundry type, order, timestepping method and limiter
+domain.set_boundary({'exterior':Reflective_boundary(domain)})
+domain.order = 2
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("vanleer")
+#domain.h0=0.0001
+
+# Start timer
+t0 = time.time()
+
+
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+
+N = float(N)
+HeightC = domain.quantities['height'].centroid_values
+DischargeC = domain.quantities['discharge'].centroid_values
+C = domain.centroids
+print 'That took %.2f seconds' %(time.time()-t0)
+X = domain.vertices
+HeightQ = domain.quantities['height'].vertex_values
+VelocityQ = domain.quantities['velocity'].vertex_values
+x = X.flat
+z = domain.quantities['width'].vertex_values.flat
+stage=HeightQ.flat+0
+
+
+
+from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+
+hold(False)
+   
+plot1 = subplot(211)
+
+plot(x,z,x,stage)
+ 
+plot1.set_ylim([-1,11])
+xlabel('Position')
+ylabel('Stage')
+#legend(('Analytical Solution', 'Numerical Solution'),
+ #          'upper right', shadow=True)
+plot2 = subplot(212)
+plot(x,VelocityQ.flat)
+plot2.set_ylim([-10,10])
+    
+xlabel('Position')
+ylabel('Velocity')
+   
+show()
Index: trunk/anuga_work/development/2010-projects/anuga_1d/compile_all.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/compile_all.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/compile_all.py	(revision 7884)
@@ -0,0 +1,31 @@
+import os
+
+buildroot = os.getcwd()
+
+#Attempt to compile all extensions
+
+os.chdir('utilities')
+execfile('compile.py')
+
+os.chdir('..')
+os.chdir('base')
+execfile('..' + os.sep + 'utilities' + os.sep + 'compile.py')
+
+os.chdir('..')
+os.chdir('channel')
+execfile('..' + os.sep + 'utilities' + os.sep + 'compile.py')
+
+os.chdir('..')
+os.chdir('pipe')
+execfile('..' + os.sep + 'utilities' + os.sep + 'compile.py')
+
+os.chdir('..')
+os.chdir('sww')
+execfile('..' + os.sep + 'utilities' + os.sep + 'compile.py')
+
+
+os.chdir(buildroot)    
+#execfile('test_all.py')
+    
+if sys.platform == 'win32':
+    raw_input('Press the RETURN key')
Index: trunk/anuga_work/development/2010-projects/anuga_1d/config.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/config.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/config.py	(revision 7884)
@@ -0,0 +1,81 @@
+"""Module where global model parameters are set for anuga_1d
+"""
+
+epsilon = 1.0e-12
+h0 = 1.0e-12
+
+default_boundary_tag = 'exterior'
+
+
+time_format = '%d/%m/%y %H:%M:%S'
+
+min_timestep = 1.0e-6 #Should be computed based on geometry
+max_timestep = 1.0e3
+max_smallsteps = 50  # Max number of degenerate steps allowed b4 trying first order
+#This is how:
+#Define maximal possible speed in open water v_max, e.g. 500m/s (soundspeed?)
+#Then work out minimal internal distance in mesh r_min and set
+#min_timestep = r_min/v_max
+#
+#Max speeds are calculated in the flux function as
+#
+#lambda = v +/- sqrt(gh)
+#
+# so with 500 m/s, h ~ 500^2/g = 2500 m well out of the domain of the
+# shallow water wave equation
+#
+#The actual soundspeed can be as high as 1530m/s
+#(see http://staff.washington.edu/aganse/public.projects/clustering/clustering.html),
+#but that would only happen with h>225000m in this equation. Why ?
+#The maximal speed we specify is really related to the max speed
+#of surface pertubation
+#
+
+
+
+max_smallsteps = 50  #Max number of degenerate steps allowed b4 trying first order
+
+manning = 0.0  #Manning's friction coefficient
+g = 9.8       #Gravity
+#g(phi) = 9780313 * (1 + 0.0053024 sin(phi)**2 - 0.000 0059 sin(2*phi)**2) micro m/s**2, where phi is the latitude
+#The 'official' average is 9.80665
+
+
+
+
+
+
+beta_w = 1.0
+beta_h = 1.0
+timestepping_method = 'rk2'
+
+CFL = 1.0  #FIXME (ole): Is this in use yet??
+           #(Steve) yes, change domain.CFL to
+           #make changes
+
+
+pmesh_filename = '.\\pmesh'
+
+
+import os, sys
+
+if sys.platform == 'win32':
+    #default_datadir = 'C:\grohm_output'
+    default_datadir = '.'
+else:
+    #default_datadir = os.path.expanduser('~'+os.sep+'grohm_output')
+    default_datadir = '.'
+
+
+#use_extensions = True    #Try to use C-extensions
+##use_extensions = False   #Do not use C-extensions
+#
+#use_psyco = True  #Use psyco optimisations
+##use_psyco = False  #Do not use psyco optimisations
+#
+#
+#optimised_gradient_limiter = True #Use hardwired gradient limiter
+
+#Specific to shallow water W.E.
+h_min = minimum_allowed_height = 1.0e-6 #1.0e-6 #Water depth below which it is considered to be 0
+maximum_allowed_speed = 1000.0
Index: trunk/anuga_work/development/2010-projects/anuga_1d/pipe/__init__.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/pipe/__init__.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/pipe/__init__.py	(revision 7884)
@@ -0,0 +1,9 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="Stephen Roberts"
+__date__ ="$14/06/2010 7:50:20 PM$"
+
+pass
Index: trunk/anuga_work/development/2010-projects/anuga_1d/pipe/test_all.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/pipe/test_all.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/pipe/test_all.py	(revision 7884)
@@ -0,0 +1,83 @@
+"""Regression testing framework
+This module will search for scripts in the same directory named
+test_*.py.  Each such script should be a test suite that tests a
+module through PyUnit. This script will aggregate all
+found test suites into one big test suite and run them all at once.
+"""
+
+# Author: Mark Pilgrim
+# Modified by Ole Nielsen
+
+import unittest
+import os
+
+
+#List files that should be excluded from the testing process.
+#E.g. if they are known to fail and under development
+exclude = [] 
+
+
+def get_test_files(path):
+
+    import sys
+
+    files = os.listdir(path)
+
+    #Check sub directories
+    test_files = []
+    for file in files:
+        if os.path.isdir(file):
+            sys.path.append(file)
+            #print 'Recursing into', file
+            test_files += get_test_files(path + os.sep + file)
+        elif file[:5] == 'test_' and file[-2:] == 'py':
+            #print 'Appending', file
+            test_files.append(file)
+        else:
+            pass
+    return test_files
+
+
+
+def regressionTest():
+    import sys, os, re, unittest
+    path = os.path.split(sys.argv[0])[0] or os.getcwd()
+
+
+    files = get_test_files(path)
+
+
+
+    #test = re.compile('^test_[\w]*.py$', re.IGNORECASE)
+    #files = filter(test.search, files)
+
+
+    try:
+        files.remove(__file__)  #Remove self from list (Ver 2.3. or later)
+    except:
+        files.remove('test_all.py')
+
+    print 'Testing:'
+    for file in files:
+        print '  ' + file
+
+    if globals().has_key('exclude'):
+        for file in exclude:
+            files.remove(file)
+            print 'WARNING: File '+ file + ' excluded from testing'
+
+
+    filenameToModuleName = lambda f: os.path.splitext(f)[0]
+    #print "files",files 
+    moduleNames = map(filenameToModuleName, files)
+    #print "moduleNames",moduleNames
+    modules = map(__import__, moduleNames)
+    load = unittest.defaultTestLoader.loadTestsFromModule
+    return unittest.TestSuite(map(load, modules))
+
+################################################################################
+
+if __name__ == '__main__':   
+    suite = regressionTest()
+    runner = unittest.TextTestRunner() #verbosity=2)
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/__init__.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/__init__.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/__init__.py	(revision 7884)
@@ -0,0 +1,9 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="Stephen Roberts"
+__date__ ="$14/06/2010 7:50:20 PM$"
+
+pass
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/profile_dry_dam.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/profile_dry_dam.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/profile_dry_dam.py	(revision 7884)
@@ -0,0 +1,124 @@
+import os
+from math import sqrt, pi
+import numpy
+import time
+#from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+
+
+
+from anuga_1d.sww.sww_domain import *
+from anuga_1d.config import g, epsilon
+from anuga_1d.base.generic_mesh import uniform_mesh
+
+
+def run_evolve():
+
+    h1 = 10.0
+    h0 = 0.01
+
+    def analytical_sol(C,t):
+
+        #t  = 0.0     # time (s)
+        # 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))
+            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 ( x[i] <= -1*L/2.0+2*(-sqrt(g*h1)*t)):
+                u[i] = 0.0
+                h[i] = h0
+            elif ( x[i] <= -1*L/2.0-(-sqrt(g*h1)*t)):
+                u[i] = u3_
+                h[i] = h3_
+
+            elif ( 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, u
+
+
+
+    def stage(x):
+        import numpy
+
+        y = numpy.where( (x>=L/4.0) & (x<=3*L/4.0), h1 , h0)
+
+    #    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
+
+
+
+
+    print "TEST 1D-SOLUTION III -- DRY BED"
+
+
+    finaltime = 4.0
+    yieldstep = 0.1
+    L = 2000.0     # Length of channel (m)
+
+    k = 0
+
+    N = 800
+    print "Evaluating domain with %d cells" %N
+    domain = Domain(*uniform_mesh(N))
+
+    domain.set_quantity('stage', stage)
+
+    Br = Reflective_boundary(domain)
+
+    domain.set_boundary({'left': Br, 'right' : Br})
+    domain.order = 2
+    domain.set_timestepping_method('rk2')
+    domain.set_CFL(1.0)
+    domain.set_limiter("minmod")
+    #domain.h0=0.0001
+
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+        domain.write_time()
+
+    print 'That took %.2f seconds' %(time.time()-t0)
+
+
+import cProfile
+cProfile.run('run_evolve()', 'dry_dam_prof')
+
+
+import pstats
+p = pstats.Stats('dry_dam_prof')
+
+#p.strip_dirs().sort_stats(-1).print_stats(20)
+
+p.sort_stats('cumulative').print_stats(30)
+
+
+
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/run_dry_dam.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/run_dry_dam.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/run_dry_dam.py	(revision 7884)
@@ -0,0 +1,144 @@
+import os
+from math import sqrt, pi
+import numpy
+import time
+#from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+
+
+
+from anuga_1d.sww.sww_domain import *
+from anuga_1d.config import g, epsilon
+from anuga_1d.base.generic_mesh import uniform_mesh
+
+h1 = 10.0
+h0 = 0.1
+
+def analytical_sol(C,t):
+    
+    #t  = 0.0     # time (s)
+    # 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))
+        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 ( x[i] <= -1*L/2.0+2*(-sqrt(g*h1)*t)):
+            u[i] = 0.0
+            h[i] = h0
+        elif ( x[i] <= -1*L/2.0-(-sqrt(g*h1)*t)):
+            u[i] = u3_
+            h[i] = h3_
+
+        elif ( 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, u
+
+
+
+def stage(x):
+    import numpy
+
+    y = numpy.where( (x>=L/4.0) & (x<=3*L/4.0), h1 , h0)
+
+#    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
+
+
+
+print "TEST 1D-SOLUTION III -- DRY BED"
+
+
+finaltime = 4.0
+yieldstep = 0.1
+L = 2000.0     # Length of channel (m)
+
+k = 0
+
+N = 3200
+print "Evaluating domain with %d cells" %N
+domain = Domain(*uniform_mesh(N,x_1=L))
+    
+domain.set_quantity('stage', stage)
+
+Br = Reflective_boundary(domain)
+
+domain.set_boundary({'left': Br, 'right' : Br})
+domain.set_spatial_order(2)
+domain.set_timestepping_method('rk2')
+domain.set_CFL(1.0)
+domain.set_limiter("minmod_kurganov")
+#domain.h0=0.0001
+
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = yieldstep, finaltime = finaltime):
+    domain.write_time()
+
+print 'That took %.2f seconds' %(time.time()-t0)
+
+
+N = float(N)
+HeightC    = domain.quantities['height'].centroid_values
+StageC     = domain.quantities['stage'].centroid_values
+BedC       = domain.quantities['elevation'].centroid_values
+C          = domain.centroids
+
+HeightV    = domain.quantities['height'].vertex_values
+StageV     = domain.quantities['stage'].vertex_values
+BedV       = domain.quantities['elevation'].vertex_values
+VelocityV  = domain.quantities['velocity'].vertex_values
+X          = domain.vertices
+
+
+import pylab
+
+pylab.hold(False)
+
+plot1 = pylab.subplot(211)
+
+pylab.plot(X.flat,BedV.flat,X.flat,StageV.flat)
+
+plot1.set_ylim([-1,11])
+
+pylab.xlabel('Position')
+pylab.ylabel('Stage')
+pylab.legend(('Analytical Solution', 'Numerical Solution'),
+           'upper right', shadow=True)
+
+
+plot2 = pylab.subplot(212)
+
+pylab.plot(X.flat,VelocityV.flat)
+plot2.set_ylim([-15,15])
+
+pylab.xlabel('Position')
+pylab.ylabel('Velocity')
+
+pylab.show()
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/run_parabolic_canal.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/run_parabolic_canal.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/run_parabolic_canal.py	(revision 7884)
@@ -0,0 +1,144 @@
+import os
+from math import sqrt, pi, sin, cos
+from shallow_water_vel_domain import *
+from Numeric import allclose, array, zeros, ones, Float, take, sqrt
+from config import g, epsilon
+
+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)
+        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
+    T = 2.0*pi/omega
+    return u,h,z,z_b, T
+
+
+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
+
+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))
+        #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 = Domain(points)
+domain.order = 2
+domain.set_timestepping_method('euler')
+domain.set_CFL(1.0)
+domain.beta = 1.0
+domain.set_limiter("vanleer")
+
+    
+domain.set_quantity('stage', stage)
+domain.set_quantity('elevation',elevation)
+domain.set_boundary({'exterior': Reflective_boundary(domain)})
+ 
+X = domain.vertices
+u,h,z,z_b,T = analytic_cannal(X.flat,domain.time)
+print 'T = ',T
+
+yieldstep = finaltime = 10.0 #T/2.0
+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):
+    domain.write_time()
+    print "integral", domain.quantities['stage'].get_integral()
+    if t>0.0:
+        
+        x = X.flat
+        print 'domain.time=',domain.time
+        
+        w_V = domain.quantities['stage'].vertex_values.flat
+        uh_V = domain.quantities['xmomentum'].vertex_values.flat
+        u_V = domain.quantities['velocity'].vertex_values.flat
+        h_V = domain.quantities['height'].vertex_values.flat
+        
+        u,h,z,z_b,T = analytic_cannal(x,domain.time)
+        w = z
+        for k in range(len(h)):
+            if h[k] < 0.0:
+                h[k] = 0.0
+                w[k] = z_b[k]
+        
+        from pylab import plot,title,xlabel,ylabel,legend,savefig,show,hold,subplot
+        hold(False)
+
+        #print 'size X',X.shape
+        #print 'size w',w.shape
+        signh = (h_V>0)
+
+        plot1 = subplot(311)
+        #plot(x,w,  x,w_V,  x,z_b)
+        plot(x,signh)
+        plot1.set_xlim([-6000,6000])
+        xlabel('Position')
+        ylabel('Stage')
+        legend(('Analytic Solution', 'Numerical Solution', 'Bed'),
+               'upper center', shadow=True)
+
+        
+        plot2 = subplot(312)
+        plot(x,u*h,x,uh_V)
+        #plot2.set_ylim([-1,25])
+        xlabel('Position')
+        ylabel('Xmomentum')
+
+        print u_V
+        
+        plot3 = subplot(313)
+        plot(x,u, x,u_V)
+        #plot2.set_ylim([-1,25])
+        xlabel('Position')
+        ylabel('Velocity')
+        show()
+raw_input("Press the return key!")
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/swb_comp_flux_ext.c
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/swb_comp_flux_ext.c	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/swb_comp_flux_ext.c	(revision 7884)
@@ -0,0 +1,329 @@
+#include "Python.h"
+#include "numpy/arrayobject.h"
+#include "math.h"
+#include <stdio.h>
+#include "util_ext.h"
+const double pi = 3.14159265358979;
+
+//Innermost flux function (using w=z+h)
+int _flux_function(double *q_left, 
+								double *q_right,
+								double normals, 
+								double g, 
+								double epsilon,
+								double *edgeflux, 
+								double *max_speed) {		
+		int i;
+                double z_left, z_right;
+		double flux_left[2], flux_right[2];
+		double z_star, w_left, h_left, h_left_star, uh_left, soundspeed_left, u_left;
+		double w_right, h_right, h_right_star, uh_right, soundspeed_right, u_right;
+		double s_max, s_min, denom;
+		
+		w_left  = q_left[0];
+		uh_left = q_left[1];
+		uh_left = uh_left*normals;
+                z_left  = q_left[2];
+		h_left  = q_left[3];
+		u_left  = q_left[4];
+	
+		w_right  = q_right[0];
+		uh_right = q_right[1];
+		uh_right = uh_right*normals;
+                z_right  = q_right[2];
+		h_right  = q_right[3];
+		u_right  = q_right[4];
+	  
+		if (z_left-z_right != 0.0 ) printf("z_l - z_r = %f \n",z_left-z_right);
+        
+		z_star = max(z_left, z_right);		              											//equation(7)  
+				   
+		// Compute speeds in x-direction.
+		h_left_star = max(0.0, w_left-z_star);														//equation(8)
+		
+		if (h_left_star < epsilon) {
+			u_left = 0.0; h_left_star = 0.0;
+		}
+		else {
+			u_left = uh_left/h_left_star;
+		}
+	                                                                                                                                                                                           
+		h_right_star = max(0.0, w_right-z_star);													//equation(9)
+
+		if (h_right_star < epsilon) {
+			u_right = 0.0; h_right_star = 0.0; 
+		}
+		else {
+			u_right = uh_right/h_right_star;
+		}
+  
+		//printf("u_left = %g u_right = %g \n",u_left, u_right);
+		soundspeed_left = sqrt(g*h_left_star);
+		soundspeed_right = sqrt(g*h_right_star);
+		
+		s_max = max(u_left+soundspeed_left, u_right+soundspeed_right);
+		if (s_max < 0.0) s_max = 0.0;
+	
+		s_min = min(u_left-soundspeed_left, u_right-soundspeed_right);
+		if (s_min > 0.0) s_min = 0.0;
+		
+		
+		// Flux formulas
+		flux_left[0] = u_left*h_left_star;
+		flux_left[1] = u_left*u_left*h_left_star + 0.5*g*h_left_star*h_left_star;
+
+		flux_right[0] = u_right*h_right_star;
+		flux_right[1] = u_right*u_right*h_right_star + 0.5*g*h_right_star*h_right_star;
+
+		// Flux computation
+		denom = s_max-s_min;
+		if (denom < epsilon && z_right > z_left) {
+			for (i=0; i<2; i++) edgeflux[i] = 0.0;
+			// Maximal wavespeed			
+			edgeflux[1] = edgeflux[1] + (0.5*g*h_left*h_left - 0.5*g*h_left_star*h_left_star );
+			edgeflux[1] *= normals;
+			*max_speed = 0.0;
+		} else if (denom < epsilon){
+			for (i=0; i<2; i++) edgeflux[i] = 0.0;
+			// Maximal wavespeed
+			*max_speed = 0.0;		
+		}else {
+			edgeflux[0] = s_max*flux_left[0] - s_min*flux_right[0];
+			edgeflux[0] += s_max*s_min*(h_right_star-h_left_star);                   //s_max*s_min*(qr[0]-ql[0]);
+			edgeflux[0] /= denom;
+			edgeflux[1] = s_max*flux_left[1] - s_min*flux_right[1];
+			edgeflux[1] += s_max*s_min*(flux_right[0]-flux_left[0]);                 //s_max*s_min*(qr[1]-ql[1]);
+			edgeflux[1] /= denom;
+			edgeflux[1] = edgeflux[1] + (0.5*g*h_left*h_left - 0.5*g*h_left_star*h_left_star );
+			edgeflux[1] *= normals;
+			// Maximal wavespeed
+			*max_speed = max(fabs(s_max), fabs(s_min));
+		}  
+		
+    return 0;		
+	}
+		
+		
+	
+	
+// Computational function for flux computation
+double _compute_fluxes_ext(double timestep,
+		double epsilon,
+		double g,
+		
+		long* neighbours,
+		long* neighbour_vertices,
+		double* normals,
+		double* areas,
+		
+		double* stage_edge_values,
+		double* xmom_edge_values,
+		double* bed_edge_values,
+		double* height_edge_values,
+		double* vel_edge_values,
+		
+		double* stage_boundary_values,
+		double* xmom_boundary_values,
+		double* bed_boundary_values,
+		double* height_boundary_values,
+		double* vel_boundary_values,
+		
+		double* stage_explicit_update,
+		double* xmom_explicit_update,
+		double* bed_explicit_update,
+		double* height_explicit_update,
+		double* vel_explicit_update,
+		
+		int number_of_elements,
+		double* max_speed_array) {
+		
+		double flux[2], ql[5], qr[5], edgeflux[2];
+		double max_speed, normal;
+		int k, i, ki, n, m, nm=0;
+		
+		for (k=0; k<number_of_elements; k++) {
+			flux[0] = 0.0;
+			flux[1] = 0.0;
+			
+			for (i=0; i<2; i++) {
+				ki = k*2+i;
+				
+				ql[0] = stage_edge_values[ki];
+				ql[1] = xmom_edge_values[ki];
+				ql[2] = bed_edge_values[ki];
+                                ql[3] = height_edge_values[ki];
+				ql[4] = vel_edge_values[ki];
+                
+				n = neighbours[ki];
+				printf("neighbours[ki] = %li \n",neighbours[ki]);
+				if (n<0) {
+					m = -n-1;
+					qr[0] = stage_boundary_values[m];
+					qr[1] = xmom_boundary_values[m];
+					qr[2] = ql[2];																			
+					qr[3] = height_edge_values[m]; 														
+					qr[4] = vel_edge_values[m];																
+                    
+				} else {
+					m = neighbour_vertices[ki];
+					nm = n*2+m;
+					qr[0] = stage_edge_values[nm];
+					qr[1] = xmom_edge_values[nm];
+					qr[2] = bed_edge_values[nm];
+					qr[3] = height_edge_values[nm];															
+					qr[4] = vel_edge_values[nm];															
+				}
+				
+				normal = normals[ki];
+				_flux_function(ql, qr, normal, g, epsilon, edgeflux, &max_speed);
+				flux[0] -= edgeflux[0];
+				flux[1] -= edgeflux[1];
+				
+				// Update timestep based on edge i and possibly neighbour n
+				if (max_speed > epsilon) {
+	                // Original CFL calculation
+					timestep = min(timestep, 0.5*areas[k]/max_speed); //Here, CFL=1.0 is assumed.
+					if (n>=0) {
+						timestep = min(timestep, 0.5*areas[n]/max_speed); //Here, CFL=1.0 is assumed. 
+					}
+				}
+            } // End edge i (and neighbour n)
+			flux[0] /= areas[k];
+			stage_explicit_update[k] = flux[0];
+			flux[1] /= areas[k];
+			xmom_explicit_update[k] = flux[1];
+			
+			//Keep track of maximal speeds
+			max_speed_array[k]=max_speed;
+		}
+		
+		return timestep;	
+	}
+	
+	
+	
+
+
+
+//=========================================================================
+// Python Glue
+//=========================================================================
+PyObject *compute_fluxes_ext(PyObject *self, PyObject *args) {
+  
+    PyArrayObject 
+	*neighbours, 
+	*neighbour_vertices,
+	*normals, 
+	*areas,
+	
+	*stage_edge_values,
+	*xmom_edge_values,
+	*bed_edge_values,
+	*height_edge_values,
+	*vel_edge_values,
+	
+	*stage_boundary_values,
+	*xmom_boundary_values,
+	*bed_boundary_values,
+	*height_boundary_values,
+	*vel_boundary_values,
+	
+	*stage_explicit_update,
+	*xmom_explicit_update,
+	*bed_explicit_update,
+	*height_explicit_update,
+	*vel_explicit_update,
+	
+	*max_speed_array;
+    
+  double timestep, epsilon, g;
+  int number_of_elements;
+    
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "dddOOOOOOOOOOOOOOOOOOOiO",
+			&timestep,
+			&epsilon,
+			&g,
+			
+			&neighbours,
+			&neighbour_vertices,
+			&normals,
+			&areas,
+			
+			&stage_edge_values,
+			&xmom_edge_values,
+			&bed_edge_values,
+			&height_edge_values,
+			&vel_edge_values,
+			
+			&stage_boundary_values,
+			&xmom_boundary_values,
+			&bed_boundary_values,
+			&height_boundary_values,
+			&vel_boundary_values,
+			
+			&stage_explicit_update,
+			&xmom_explicit_update,
+			&bed_explicit_update,
+			&height_explicit_update,
+			&vel_explicit_update,
+			
+			&number_of_elements,
+			&max_speed_array)) {
+    PyErr_SetString(PyExc_RuntimeError, "swb_comp_flux_ext.c: compute_fluxes_ext could not parse input");
+    return NULL;
+  }
+
+ 
+  // Call underlying flux computation routine and update 
+  // the explicit update arrays 
+  timestep = _compute_fluxes_ext(timestep,
+				 epsilon,
+				 g,
+				 
+				 (long*) neighbours -> data,
+				 (long*) neighbour_vertices -> data,
+				 (double*) normals -> data,
+				 (double*) areas -> data,
+				 
+				 (double*) stage_edge_values -> data,
+				 (double*) xmom_edge_values -> data,
+				 (double*) bed_edge_values -> data,
+				 (double*) height_edge_values -> data,
+				 (double*) vel_edge_values -> data,
+				 
+				 (double*) stage_boundary_values -> data,
+				 (double*) xmom_boundary_values -> data,
+				 (double*) bed_boundary_values -> data,
+				 (double*) height_boundary_values -> data,
+				 (double*) vel_boundary_values -> data,
+				 
+				 (double*) stage_explicit_update -> data,
+				 (double*) xmom_explicit_update -> data,
+				 (double*) bed_explicit_update -> data,
+				 (double*) height_explicit_update -> data,
+				 (double*) vel_explicit_update -> data,
+				 
+				 number_of_elements,
+				 (double*) max_speed_array -> data);
+
+  // Return updated flux timestep
+  return Py_BuildValue("d", timestep);
+}
+
+
+
+//-------------------------------
+// Method table for python module
+//-------------------------------
+
+static struct PyMethodDef MethodTable[] = {
+  {"compute_fluxes_ext", compute_fluxes_ext, METH_VARARGS, "Print out"},
+  {NULL, NULL}
+};
+
+// Module initialisation
+void initswb_comp_flux_ext(void){
+  Py_InitModule("swb_comp_flux_ext", MethodTable);
+  import_array();
+}
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_boundary_conditions.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_boundary_conditions.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_boundary_conditions.py	(revision 7884)
@@ -0,0 +1,83 @@
+#! /usr/bin/python
+
+"""
+Boundaries - specific to the shallow water wave equation
+"""
+__author__="Stephen Roberts"
+__date__ ="$05/06/2010 5:44:05 PM$"
+
+from anuga_1d.base.generic_domain import *
+
+class Dirichlet_boundary(Boundary):
+    """Dirichlet boundary returns constant values for the
+    conserved quantities
+    """
+
+    def __init__(self, quantities=None):
+        Boundary.__init__(self)
+
+        if quantities is None:
+            msg = 'Must specify one value for each evolved quantity, w,uh,z,h,u'
+            raise msg
+
+        self.quantities=numpy.array(quantities, numpy.float)
+
+    def __repr__(self):
+        return 'Dirichlet boundary (%s)' %self.quantities
+
+    def evaluate(self, vol_id=None, edge_id=None):
+        return self.quantities
+
+
+class Reflective_boundary(Boundary):
+    """Reflective boundary returns same conserved quantities as
+    those present in its neighbour volume but reflected.
+
+    This class is specific to the shallow water equation as it
+    works with the momentum quantities assumed to be the second
+    and third conserved quantities.
+    """
+
+    def __init__(self, domain = None):
+        Boundary.__init__(self)
+
+        if domain is None:
+            msg = 'Domain must be specified for reflective boundary'
+            raise msg
+
+        #Handy shorthands
+        self.normals  = domain.normals
+        self.stage    = domain.quantities['stage'].vertex_values
+        self.xmom     = domain.quantities['xmomentum'].vertex_values
+        self.bed      = domain.quantities['elevation'].vertex_values
+        self.height   = domain.quantities['height'].vertex_values
+        self.velocity = domain.quantities['velocity'].vertex_values
+
+
+        self.quantities = numpy.zeros(5, numpy.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.quantities
+        q[0] =  self.stage[vol_id, edge_id]
+        q[1] = -self.xmom[vol_id, edge_id]
+        q[2] =  self.bed[vol_id, edge_id]
+        q[3] =  self.height[vol_id, edge_id]
+        q[4] = -self.velocity[vol_id, edge_id]
+
+        #normal = self.normals[vol_id,edge_id]
+
+        return q
+
+
+
+
+if __name__ == "__main__":
+    print "Hello World";
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_comp_flux_ext.c
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_comp_flux_ext.c	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_comp_flux_ext.c	(revision 7884)
@@ -0,0 +1,417 @@
+#include "Python.h"
+#include "numpy/arrayobject.h"
+#include "math.h"
+#include <stdio.h>
+const double pi = 3.14159265358979;
+
+
+// Shared code snippets
+#include "util_ext.h"
+
+
+/* double max(double a, double b) { */
+/* 	double z; */
+/* 	z=(a>b)?a:b; */
+/* 	return z;} */
+	
+/* double min(double a, double b) { */
+/* 	double z; */
+/* 	z=(a<b)?a:b; */
+/* 	return z;} */
+
+
+// Function to obtain speed from momentum and depth.
+// This is used by flux functions
+// Input parameters uh and h may be modified by this function.
+double _compute_speed(double *uh, 
+		      double *h, 
+		      double epsilon, 
+		      double h0) {
+  
+  double u;
+  
+  if (*h < epsilon) {
+    *h = 0.0;  //Could have been negative
+     u = 0.0;
+  } else {
+    u = *uh/(*h + h0/ *h);    
+  }
+  
+
+  // Adjust momentum to be consistent with speed
+  *uh = u * *h;
+  
+  return u;
+}
+
+
+
+
+//Innermost flux function (using w=z+h)
+int _flux_function(double *q_left, double *q_right,
+        double z_left, double z_right,
+		   double normals, double g, double epsilon, double h0,
+		double *edgeflux, double *max_speed) {
+		
+		int i;
+		double ql[2], qr[2], flux_left[2], flux_right[2];
+		double z, w_left, h_left, uh_left, soundspeed_left, u_left;
+		double w_right, h_right, uh_right, soundspeed_right, u_right;
+		double s_max, s_min, denom;
+		
+		//printf("h0 = %f \n",h0);
+		ql[0] = q_left[0];
+		ql[1] = q_left[1];
+		ql[1] = ql[1]*normals;
+	
+		qr[0] = q_right[0];
+		qr[1] = q_right[1];
+		qr[1] = qr[1]*normals;
+	  
+		z = (z_left+z_right)/2.0;		   
+				   
+		//w_left = ql[0];
+		//h_left = w_left-z;
+		//uh_left = ql[1];
+		
+
+
+		// Compute speeds in x-direction
+		w_left = ql[0];          
+		h_left = w_left-z;
+		uh_left = ql[1];
+
+		u_left = _compute_speed(&uh_left, &h_left, epsilon, h0);
+
+		w_right = qr[0];
+		h_right = w_right-z;
+		uh_right = qr[1];
+
+		u_right = _compute_speed(&uh_right, &h_right, epsilon, h0);
+  
+		soundspeed_left = sqrt(g*h_left);
+		soundspeed_right = sqrt(g*h_right);
+		
+		s_max = max(u_left+soundspeed_left, u_right+soundspeed_right);
+		if (s_max < 0.0) s_max = 0.0;
+	
+		s_min = min(u_left-soundspeed_left, u_right-soundspeed_right);
+		if (s_min > 0.0) s_min = 0.0;
+		
+		
+		// Flux formulas
+		flux_left[0] = u_left*h_left;
+		flux_left[1] = u_left*uh_left + 0.5*g*h_left*h_left;
+
+		flux_right[0] = u_right*h_right;
+		flux_right[1] = u_right*uh_right + 0.5*g*h_right*h_right;
+
+		// Flux computation
+		denom = s_max-s_min;
+		if (denom < epsilon) {
+			for (i=0; i<2; i++) edgeflux[i] = 0.0;
+			*max_speed = 0.0;
+		} else {
+			edgeflux[0] = s_max*flux_left[0] - s_min*flux_right[0];
+			edgeflux[0] += s_max*s_min*(qr[0]-ql[0]);
+			edgeflux[0] /= denom;
+			edgeflux[1] = s_max*flux_left[1] - s_min*flux_right[1];
+			edgeflux[1] += s_max*s_min*(qr[1]-ql[1]);
+			edgeflux[1] /= denom;
+			edgeflux[1] *= normals;
+    
+		// Maximal wavespeed
+        *max_speed = max(fabs(s_max), fabs(s_min));
+		}  
+    return 0;		
+	}
+		
+		
+	
+	
+// Computational function for flux computation
+double _compute_fluxes_ext(
+			   double cfl,
+			   double timestep,
+			   double epsilon,
+			   double g,
+			   double h0,
+			   long* neighbours,
+			   long* neighbour_vertices,
+			   double* normals,
+			   double* areas,
+			   double* stage_edge_values,
+			   double* xmom_edge_values,
+			   double* bed_edge_values,
+			   double* stage_boundary_values,
+			   double* xmom_boundary_values,
+			   double* stage_explicit_update,
+			   double* xmom_explicit_update,
+			   int number_of_elements,
+			   double* max_speed_array) {
+		
+                double flux[2], ql[2], qr[2], edgeflux[2];
+		double zl, zr, max_speed, normal;
+		int k, i, ki, n, m, nm=0;
+		
+		
+		for (k=0; k<number_of_elements; k++) {
+			flux[0] = 0.0;
+			flux[1] = 0.0;
+			
+			for (i=0; i<2; i++) {
+				ki = k*2+i;
+				
+				ql[0] = stage_edge_values[ki];
+				ql[1] = xmom_edge_values[ki];
+				zl = bed_edge_values[ki];
+				
+				n = neighbours[ki];
+				if (n<0) {
+					m = -n-1;
+					qr[0] = stage_boundary_values[m];
+					qr[1] = xmom_boundary_values[m];
+					zr = zl;
+				} else {
+					m = neighbour_vertices[ki];
+					nm = n*2+m;
+					qr[0] = stage_edge_values[nm];
+					qr[1] = xmom_edge_values[nm];
+					zr = bed_edge_values[nm];				
+				}
+				
+				normal = normals[ki];
+				_flux_function(ql, qr, zl, zr, normal, g, epsilon, h0, edgeflux, &max_speed);
+				flux[0] -= edgeflux[0];
+				flux[1] -= edgeflux[1];
+				
+				// Update timestep based on edge i and possibly neighbour n
+				if (max_speed > epsilon) {
+				    // Original CFL calculation
+				    
+				    timestep = min(timestep, 0.5*cfl*areas[k]/max_speed); 
+				    if (n>=0) {
+					timestep = min(timestep, 0.5*cfl*areas[n]/max_speed); 
+				    }
+				}
+            } // End edge i (and neighbour n)
+			flux[0] /= areas[k];
+			stage_explicit_update[k] = flux[0];
+			flux[1] /= areas[k];
+			xmom_explicit_update[k] = flux[1];
+			
+			//Keep track of maximal speeds
+			max_speed_array[k]=max_speed;
+		}
+		return timestep;	
+	}
+	
+	
+	
+	
+	
+
+
+
+//=========================================================================
+// Python Glue
+//=========================================================================
+PyObject *compute_fluxes_ext(PyObject *self, PyObject *args) {
+  
+    PyArrayObject 
+	*neighbours, 
+	*neighbour_vertices,
+	*normals, 
+	*areas,
+	*stage_edge_values,
+	*xmom_edge_values,
+	*bed_edge_values,
+	*stage_boundary_values,
+	*xmom_boundary_values,
+	*stage_explicit_update,
+	*xmom_explicit_update,
+	*max_speed_array;
+    
+  double timestep, epsilon, g, h0, cfl;
+  int number_of_elements;
+    
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "dddddOOOOOOOOOOOiO",
+			&cfl,
+			&timestep,
+			&epsilon,
+			&g,
+			&h0,
+			&neighbours,
+			&neighbour_vertices,
+			&normals,
+			&areas,
+			&stage_edge_values,
+			&xmom_edge_values,
+			&bed_edge_values,
+			&stage_boundary_values,
+			&xmom_boundary_values,
+			&stage_explicit_update,
+			&xmom_explicit_update,
+			&number_of_elements,
+			&max_speed_array)) {
+    PyErr_SetString(PyExc_RuntimeError, "comp_flux_ext.c: compute_fluxes_ext could not parse input");
+    return NULL;
+  }
+
+ 
+  // Call underlying flux computation routine and update 
+  // the explicit update arrays 
+  timestep = _compute_fluxes_ext(cfl,
+				 timestep,
+				 epsilon,
+				 g,
+				 h0,
+				 (long*) neighbours -> data,
+				 (long*) neighbour_vertices -> data,
+				 (double*) normals -> data,
+				 (double*) areas -> data,
+				 (double*) stage_edge_values -> data,
+				 (double*) xmom_edge_values -> data,
+				 (double*) bed_edge_values -> data,
+				 (double*) stage_boundary_values -> data,
+				 (double*) xmom_boundary_values -> data,
+				 (double*) stage_explicit_update -> data,
+				 (double*) xmom_explicit_update -> data,
+				 number_of_elements,
+				 (double*) max_speed_array -> data);
+
+  // Return updated flux timestep
+  return Py_BuildValue("d", timestep);
+}
+
+
+//-----------------------
+PyObject *compute_fluxes_ext_short(PyObject *self, PyObject *args) {
+  
+   PyObject 
+	*domain,
+	*stage, 
+	*xmom, 
+	*bed;
+
+    PyArrayObject 
+	*neighbours, 
+	*neighbour_vertices,
+	*normals, 
+	*areas,
+	*stage_vertex_values,
+	*xmom_vertex_values,
+	*bed_vertex_values,
+	*stage_boundary_values,
+	*xmom_boundary_values,
+	*stage_explicit_update,
+	*xmom_explicit_update,
+	*max_speed_array;
+    
+  double timestep, epsilon, g, h0, cfl;
+  int number_of_elements;
+
+    
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "dOOOO",
+			&timestep,
+			&domain,
+			&stage,
+			&xmom,
+			&bed)) {
+      PyErr_SetString(PyExc_RuntimeError, "comp_flux_ext.c: compute_fluxes_ext_short could not parse input");
+      return NULL;
+  }
+
+
+    epsilon           = get_python_double(domain,"epsilon");
+    g                 = get_python_double(domain,"g");
+    h0                = get_python_double(domain,"h0");
+    cfl               = get_python_double(domain,"CFL");
+ 
+    
+    neighbours        = get_consecutive_array(domain, "neighbours");
+    neighbour_vertices= get_consecutive_array(domain, "neighbour_vertices"); 
+    normals           = get_consecutive_array(domain, "normals");
+    areas             = get_consecutive_array(domain, "areas");    
+    max_speed_array   = get_consecutive_array(domain, "max_speed_array");
+    
+    stage_vertex_values = get_consecutive_array(stage, "vertex_values");    
+    xmom_vertex_values  = get_consecutive_array(xmom, "vertex_values");    
+    bed_vertex_values   = get_consecutive_array(bed, "vertex_values");    
+
+    stage_boundary_values = get_consecutive_array(stage, "boundary_values");    
+    xmom_boundary_values  = get_consecutive_array(xmom, "boundary_values");    
+
+
+    stage_explicit_update = get_consecutive_array(stage, "explicit_update");    
+    xmom_explicit_update  = get_consecutive_array(xmom, "explicit_update");    
+
+
+
+    number_of_elements = stage_vertex_values -> dimensions[0];
+
+
+ 
+    // Call underlying flux computation routine and update 
+    // the explicit update arrays 
+    timestep = _compute_fluxes_ext(
+	cfl,
+	timestep,
+	epsilon,
+	g,
+	h0,
+	(long*) neighbours -> data,
+	(long*) neighbour_vertices -> data,
+	(double*) normals -> data,
+	(double*) areas -> data,
+	(double*) stage_vertex_values -> data,
+	(double*) xmom_vertex_values -> data,
+	(double*) bed_vertex_values -> data,
+	(double*) stage_boundary_values -> data,
+	(double*) xmom_boundary_values -> data,
+	(double*) stage_explicit_update -> data,
+	(double*) xmom_explicit_update -> data,
+	number_of_elements,
+	(double*) max_speed_array -> data);
+
+
+  Py_DECREF(neighbours);
+  Py_DECREF(neighbour_vertices);
+  Py_DECREF(normals);
+  Py_DECREF(areas);
+  Py_DECREF(stage_vertex_values);
+  Py_DECREF(xmom_vertex_values);
+  Py_DECREF(bed_vertex_values);
+  Py_DECREF(stage_boundary_values);
+  Py_DECREF(xmom_boundary_values);
+  Py_DECREF(stage_explicit_update);
+  Py_DECREF(xmom_explicit_update);
+  Py_DECREF(max_speed_array);
+
+
+
+
+  // Return updated flux timestep
+  return Py_BuildValue("d", timestep);
+}
+
+ 
+
+
+//-------------------------------
+// Method table for python module
+//-------------------------------
+
+static struct PyMethodDef MethodTable[] = {
+  {"compute_fluxes_ext", compute_fluxes_ext, METH_VARARGS, "Print out"},
+  {"compute_fluxes_ext_short", compute_fluxes_ext_short, METH_VARARGS, "Print out"},
+  {NULL, NULL}
+};
+
+// Module initialisation
+void initsww_comp_flux_ext(void){
+  Py_InitModule("sww_comp_flux_ext", MethodTable);
+  import_array();
+}
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_domain.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_domain.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_domain.py	(revision 7884)
@@ -0,0 +1,486 @@
+"""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
+"""
+
+import numpy
+
+from anuga_1d.base.generic_domain import Generic_domain
+from sww_boundary_conditions import *
+from sww_forcing_terms import *
+
+#Shallow water domain
+class Domain(Generic_domain):
+
+    def __init__(self, coordinates, boundary = None, tagged_elements = None):
+
+        conserved_quantities = ['stage', 'xmomentum']
+        evolved_quantities   = ['stage', 'xmomentum', 'elevation', 'height', 'velocity']
+        other_quantities     = ['friction']
+        Generic_domain.__init__(self,
+                                coordinates          = coordinates,
+                                boundary             = boundary,
+                                conserved_quantities = conserved_quantities,
+                                evolved_quantities   = evolved_quantities,
+                                other_quantities     = other_quantities,
+                                tagged_elements      = tagged_elements)
+        
+        from anuga_1d.config import minimum_allowed_height, g, h0
+        self.minimum_allowed_height = minimum_allowed_height
+        self.g = g
+        self.h0 = h0
+
+        #forcing terms
+        self.forcing_terms.append(gravity)
+        #self.forcing_terms.append(manning_friction)
+        
+        
+        #Stored output
+        self.store = True
+        self.format = 'sww'
+        self.smooth = True
+
+        #Evolve parametrs
+        self.cfl = 1.0
+        
+        #Reduction operation for get_vertex_values
+        from anuga_1d.base.util import mean
+        self.reduction = mean
+        #self.reduction = min  #Looks better near steep slopes
+
+        self.quantities_to_be_stored = ['stage','xmomentum']
+
+	self.__doc__ = 'sww_domain'
+
+
+    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 compute_fluxes(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+
+        import sys
+
+
+        timestep = float(sys.maxint)
+
+        stage    = self.quantities['stage']
+        xmom     = self.quantities['xmomentum']
+        bed      = self.quantities['elevation']
+        height   = self.quantities['height']
+        velocity = self.quantities['velocity']
+
+
+        from anuga_1d.sww.sww_comp_flux_ext import compute_fluxes_ext_short
+
+        #self.flux_timestep = compute_fluxes_ext(timestep,self,stage,xmom,bed,height,velocity)
+
+    
+ 	self.flux_timestep = compute_fluxes_ext_short(timestep,self,stage,xmom,bed)
+
+
+
+    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 basic machinery from parent class
+        for t in Generic_domain.evolve(self, yieldstep, finaltime,duration,
+                                       skip_initial_step):
+
+            #Pass control on to outer loop for more specific actions
+            yield(t)
+
+
+
+
+
+#=============== End of Shallow Water Domain ===============================
+
+
+# Module functions for gradient limiting (distribute_to_vertices_and_edges)
+
+def distribute_to_vertices_and_edges(domain):
+    """Distribution from centroids to vertices specific to the
+    shallow water wave
+    equation.
+
+    It will ensure that h (w-z) is always non-negative even in the
+    presence of steep bed-slopes by taking a weighted average between shallow
+    and deep cases.
+
+    In addition, all conserved quantities get distributed as per either a
+    constant (order==1) or a piecewise linear function (order==2).
+
+    FIXME: more explanation about removal of artificial variability etc
+
+    Precondition:
+      All quantities defined at centroids and bed elevation defined at
+      vertices.
+
+    Postcondition
+      Conserved quantities defined at vertices
+
+    """
+
+    #from config import optimised_gradient_limiter
+
+    #Remove very thin layers of water
+    #protect_against_infinitesimal_and_negative_heights(domain)  
+
+    import sys
+    from anuga_1d.config import epsilon, h0
+	
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage      = domain.quantities['stage']
+    Xmom       = domain.quantities['xmomentum']
+    Bed        = domain.quantities['elevation']
+    Height     = domain.quantities['height']
+    Velocity   = domain.quantities['velocity']
+
+    #Arrays   
+    w_C   = Stage.centroid_values    
+    uh_C  = Xmom.centroid_values    
+    z_C   = Bed.centroid_values
+    h_C   = Height.centroid_values
+    u_C   = Velocity.centroid_values
+	
+    #Calculate height (and fix negatives)better be non-negative!
+    h_C[:] = w_C - z_C
+    u_C[:]  = uh_C/(h_C + h0/h_C)
+	
+    for name in [ 'velocity', 'stage' ]:
+        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'
+
+
+    stage_V = domain.quantities['stage'].vertex_values			
+    bed_V   = domain.quantities['elevation'].vertex_values	
+    h_V     = domain.quantities['height'].vertex_values
+    u_V     = domain.quantities['velocity'].vertex_values
+    xmom_V  = domain.quantities['xmomentum'].vertex_values
+
+    h_V[:,:]    = stage_V - bed_V
+
+#    # protect from edge values going negative
+#    h_V[:,1] = numpy.where(h_V[:,0] < 0.0 , h_V[:,1]-h_V[:,0], h_V[:,1])
+#    h_V[:,0] = numpy.where(h_V[:,0] < 0.0 , 0.0, h_V[:,0])
+#
+#    h_V[:,0] = numpy.where(h_V[:,1] < 0.0 , h_V[:,0]-h_V[:,1], h_V[:,0])
+#    h_V[:,1] = numpy.where(h_V[:,1] < 0.0 , 0.0, h_V[:,1])
+#
+#
+#    stage_V[:,:] = bed_V + h_V
+    xmom_V[:,:] = u_V * h_V
+    
+    return
+#
+
+
+
+
+
+
+
+#
+def protect_against_infinitesimal_and_negative_heights(domain):
+    """Protect against infinitesimal heights and associated high velocities
+    """
+
+    #Shortcuts
+    wc    = domain.quantities['stage'].centroid_values
+    zc    = domain.quantities['elevation'].centroid_values
+    xmomc = domain.quantities['xmomentum'].centroid_values
+    hc = wc - zc  #Water depths at centroids
+
+    zv = domain.quantities['elevation'].vertex_values
+    wv = domain.quantities['stage'].vertex_values
+    hv = wv-zv
+    xmomv = domain.quantities['xmomentum'].vertex_values
+    #remove the above two lines and corresponding code below
+
+    #Update
+    #FIXME replace with numpy.where
+    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
+    """
+
+    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, numpy.float) #h-limited values
+
+    #Find min and max of this and neighbour's centroid values
+    hmax = zeros(hc.shape, numpy.float)
+    hmin = zeros(hc.shape, numpy.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, numpy.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 numpyal 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,:]
+
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_forcing_terms.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_forcing_terms.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_forcing_terms.py	(revision 7884)
@@ -0,0 +1,187 @@
+#! /usr/bin/python
+
+
+"""
+Forcing terms for the shallow water equations, gravity, friction etc
+"""
+
+__author__="Stephen Roberts"
+__date__ ="$05/06/2010 5:49:35 PM$"
+
+
+def gravity_for_loops(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    from anuga_1d.base.util import gradient
+
+    xmom  = domain.quantities['xmomentum'].explicit_update
+
+    Stage = domain.quantities['stage']
+    Elevation = domain.quantities['elevation']
+
+    h = Stage.vertex_values - Elevation.vertex_values
+    b = Elevation.vertex_values
+    w = Stage.vertex_values
+
+    x = domain.get_vertex_coordinates()
+    g = domain.g
+
+    for k in range(domain.number_of_elements):
+        avg_h = sum( h[k,:] )/2
+
+        #Compute bed slope
+        #x0, y0, x1, y1, x2, y2 = x[k,:]
+        x0, x1 = x[k,:]
+        #z0, z1, z2 = v[k,:]
+        b0, b1 = b[k,:]
+
+
+        #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)
+        xmom[k] += -g*bx*avg_h
+        #xmom[k] = -g*bx*avg_h
+        #stage[k] = 0.0
+
+
+def gravity(domain):
+    """Apply gravitational pull in the presence of bed slope
+    """
+
+    xmom  = domain.quantities['xmomentum'].explicit_update
+
+    Elevation = domain.quantities['elevation']
+    Height    = domain.quantities['height']
+
+    hc = Height.centroid_values
+    b  = Elevation.vertex_values
+
+    x = domain.vertices
+    g = domain.g
+
+    x0 = x[:,0]
+    x1 = x[:,1]
+
+    b0 = b[:,0]
+    b1 = b[:,1]
+
+    bx = (b1-b0)/(x1-x0)
+
+    xmom[:] = xmom - g*bx*hc
+
+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
+    """
+
+
+    if callable(f):
+        #N = 3
+        N = 2
+        #x = ones(3, numpy.float)
+        #y = ones(3, numpy.float)
+        x = ones(2, numpy.float)
+        #y = ones(2, numpy.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 = numpy.array(q, numpy.float)
+        except:
+            msg = 'Return value from vector function %s could ' %f
+            msg += 'not be converted into a numpy array of numpy.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
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_python.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_python.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_python.py	(revision 7884)
@@ -0,0 +1,221 @@
+#! /usr/bin/python
+
+
+
+__author__="Stephen Roberts"
+__date__ ="$05/06/2010 4:54:58 PM$"
+
+
+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
+    import numpy
+
+    N = domain.number_of_elements
+
+    tmp0 = numpy.zeros(N,numpy.float)
+    tmp1 = numpy.zeros(N,numpy.float)
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+
+    #Arrays
+    stage = Stage.vertex_values
+    xmom =  Xmom.vertex_values
+    bed =   Bed.vertex_values
+
+
+    stage_bdry = Stage.boundary_values
+    xmom_bdry =  Xmom.boundary_values
+
+    flux = numpy.zeros(2, numpy.float) #Work numpy.array for summing up fluxes
+    ql = numpy.zeros(2, numpy.float)
+    qr = numpy.zeros(2, numpy.float)
+
+    #Loop
+    timestep = float(sys.maxint)
+
+    for k in range(N):
+
+        flux[:,] = 0.  #Reset work numpy.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]
+                #print i, ' ' , m
+                #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 'edgeflux', edgeflux
+
+            # THIS IS THE LINE TO DEAL WITH LEFT AND RIGHT FLUXES
+            # flux = edgefluxleft - edgefluxright
+            flux -= edgeflux
+            #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]
+        tmp0[k] = flux[0]
+        tmp1[k] = flux[1]
+
+
+    return tmp0, tmp1
+
+
+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 anuga_1d.config import g, epsilon, h0
+    from math import sqrt
+    import numpy
+
+    #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 +  h0/h_left)
+
+
+    uh_left = u_left*h_left
+
+    w_right  = q_right[0]  #w=h+z
+    h_right  = w_right-z
+    uh_right = q_right[1]
+
+
+    if h_right < epsilon:
+        u_right = 0.0  #Could have been negative
+        h_right = 0.0
+    else:
+        u_right  = uh_right/(h_right + h0/h_right)
+
+    uh_right = u_right*h_right
+
+    #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  = numpy.array([u_left*h_left,
+    #                    u_left*uh_left + 0.5*g*h_left**2])
+    #flux_right = numpy.array([u_right*h_right,
+    #                    u_right*uh_right + 0.5*g*h_right**2])
+    flux_left  = numpy.array([u_left*h_left,
+                        u_left*uh_left + 0.5*g*h_left*h_left])
+    flux_right = numpy.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 = numpy.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
+
+
+if __name__ == "__main__":
+    print "Hello World";
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_vel_comp_flux_ext.c
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_vel_comp_flux_ext.c	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_vel_comp_flux_ext.c	(revision 7884)
@@ -0,0 +1,638 @@
+#include "Python.h"
+#include "numpy/arrayobject.h"
+#include "math.h"
+#include <stdio.h>
+const double pi = 3.14159265358979;
+
+
+// Shared code snippets
+#include "util_ext.h"
+
+
+/* double max(double a, double b) { */
+/* 	double z; */
+/* 	z=(a>b)?a:b; */
+/* 	return z;} */
+	
+/* double min(double a, double b) { */
+/* 	double z; */
+/* 	z=(a<b)?a:b; */
+/* 	return z;} */
+
+
+// Function to obtain speed from momentum and depth.
+// This is used by flux functions
+// Input parameters uh and h may be modified by this function.
+double _compute_speed(double *uh, 
+		      double *h, 
+		      double epsilon, 
+		      double h0) {
+  
+  double u;
+  
+  if (*h < epsilon) {
+    *h = 0.0;  //Could have been negative
+     u = 0.0;
+  } else {
+    u = *uh/(*h + h0/ *h);    
+  }
+  
+
+  // Adjust momentum to be consistent with speed
+  *uh = u * *h;
+  
+  return u;
+}
+
+//-------------------------------------------------------------
+// New vel based code
+//-------------------------------------------------------------
+//Innermost flux function (using w=z+h)
+int _flux_function_vel(double *q_left, double *q_right,
+		       double normals, double g, double epsilon, double h0,
+		       double *edgeflux, double *max_speed) {
+    
+    int i;
+    double flux_left[2], flux_right[2];
+    double w_left, h_left, uh_left, z_left, u_left, soundspeed_left;
+    double w_right, h_right, uh_right, z_right, u_right, soundspeed_right;
+    double z, s_max, s_min, denom;
+    
+
+    w_left  = q_left[0];
+    uh_left = q_left[1]*normals;
+    z_left  = q_left[2];
+    h_left  = q_left[3];
+    u_left  = q_left[4]*normals;
+
+/*     printf("w_left  = %f \n",w_left); */
+/*     printf("uh_left = %f \n",uh_left); */
+/*     printf("z_left  = %f \n",z_left); */
+/*     printf("h_left  = %f \n",h_left); */
+/*     printf("u_left  = %f \n",u_left); */
+    
+    w_right  = q_right[0];
+    uh_right = q_right[1]*normals;
+    z_right  = q_right[2];
+    h_right  = q_right[3];
+    u_right  = q_right[4]*normals;		
+    
+    z = (z_left+z_right)/2.0;		   
+    
+    soundspeed_left = sqrt(g*h_left);
+    soundspeed_right = sqrt(g*h_right);
+    
+    s_max = max(u_left+soundspeed_left, u_right+soundspeed_right);
+    if (s_max < 0.0) s_max = 0.0;
+    
+    s_min = min(u_left-soundspeed_left, u_right-soundspeed_right);
+    if (s_min > 0.0) s_min = 0.0;
+    
+    
+    // Flux formulas
+    flux_left[0] = u_left*h_left;
+    flux_left[1] = u_left*u_left*h_left + 0.5*g*h_left*h_left;
+    
+    flux_right[0] = u_right*h_right;
+    flux_right[1] = u_right*u_right*h_right + 0.5*g*h_right*h_right;
+    
+    // Flux computation
+    denom = s_max-s_min;
+    if (denom < epsilon) {
+	for (i=0; i<2; i++) edgeflux[i] = 0.0;
+	*max_speed = 0.0;
+    } else {
+	edgeflux[0] = s_max*flux_left[0] - s_min*flux_right[0];
+	edgeflux[0] += s_max*s_min*(w_right-w_left);
+	edgeflux[0] /= denom;
+	edgeflux[1] = s_max*flux_left[1] - s_min*flux_right[1];
+	edgeflux[1] += s_max*s_min*(uh_right-uh_left);
+	edgeflux[1] /= denom;
+	edgeflux[1] *= normals;
+	
+	// Maximal wavespeed
+	*max_speed = max(fabs(s_max), fabs(s_min));
+    }  
+    return 0;		
+}
+
+// Computational function for flux computation
+double _compute_fluxes_vel_ext(double cfl,
+			       double timestep,
+			       double epsilon,
+			       double g,
+			       double h0,
+			       long* neighbours,
+			       long* neighbour_vertices,
+			       double* normals,
+			       double* areas,
+			       double* stage_edge_values,
+			       double* xmom_edge_values,
+			       double* bed_edge_values,
+			       double* height_edge_values,
+			       double* velocity_edge_values,
+			       double* stage_boundary_values,
+			       double* xmom_boundary_values,
+			       double* bed_boundary_values,
+			       double* height_boundary_values,
+			       double* velocity_boundary_values,
+			       double* stage_explicit_update,
+			       double* xmom_explicit_update,
+			       int number_of_elements,
+			       double* max_speed_array) {
+		
+    double flux[2], ql[5], qr[5], edgeflux[2];
+    double max_speed, normal;
+    int k, i, ki, n, m, nm=0;
+
+    //printf("Inside _comp\n");    
+    
+    for (k=0; k<number_of_elements; k++) {
+	flux[0] = 0.0;
+	flux[1] = 0.0;
+	//printf("k = %d\n",k);
+
+	for (i=0; i<2; i++) {
+	    ki = k*2+i;
+	    
+	    ql[0] = stage_edge_values[ki];
+	    ql[1] = xmom_edge_values[ki];
+	    ql[2] = bed_edge_values[ki];
+	    ql[3] = height_edge_values[ki];
+	    ql[4] = velocity_edge_values[ki];
+	    
+	    n = neighbours[ki];
+	    if (n<0) {
+		m = -n-1;
+		qr[0] = stage_boundary_values[m];
+		qr[1] = xmom_boundary_values[m];
+		qr[2] = bed_boundary_values[m];
+		qr[3] = height_boundary_values[m];
+		qr[4] = velocity_boundary_values[m];
+	    } else {
+		m = neighbour_vertices[ki];
+		nm = n*2+m;
+		qr[0] = stage_edge_values[nm];
+		qr[1] = xmom_edge_values[nm];
+		qr[2] = bed_edge_values[nm];
+		qr[3] = height_edge_values[nm];
+		qr[4] = velocity_edge_values[nm];
+	    }
+	    
+	    normal = normals[ki];
+	    _flux_function_vel(ql, qr, normal, g, epsilon, h0, edgeflux, &max_speed);
+	    flux[0] -= edgeflux[0];
+	    flux[1] -= edgeflux[1];
+	    
+	    // Update timestep based on edge i and possibly neighbour n
+	    if (max_speed > epsilon) {
+		// Original CFL calculation
+		
+		timestep = min(timestep, 0.5*cfl*areas[k]/max_speed); 
+		if (n>=0) {
+		    timestep = min(timestep, 0.5*cfl*areas[n]/max_speed); 
+		}
+	    }
+	} // End edge i (and neighbour n)
+	flux[0] /= areas[k];
+	stage_explicit_update[k] = flux[0];
+	flux[1] /= areas[k];
+	xmom_explicit_update[k] = flux[1];
+	
+	//Keep track of maximal speeds
+	max_speed_array[k]=max_speed;
+    }
+    return timestep;	
+}
+
+//-------------------------------------------------------------
+// Old code
+//------------------------------------------------------------
+//Innermost flux function (using w=z+h)
+int _flux_function(double *q_left, double *q_right,
+        double z_left, double z_right,
+		   double normals, double g, double epsilon, double h0,
+		double *edgeflux, double *max_speed) {
+		
+		int i;
+		double ql[2], qr[2], flux_left[2], flux_right[2];
+		double z, w_left, h_left, uh_left, soundspeed_left, u_left;
+		double w_right, h_right, uh_right, soundspeed_right, u_right;
+		double s_max, s_min, denom;
+		
+		//printf("h0 = %f \n",h0);
+		ql[0] = q_left[0];
+		ql[1] = q_left[1];
+		ql[1] = ql[1]*normals;
+	
+		qr[0] = q_right[0];
+		qr[1] = q_right[1];
+		qr[1] = qr[1]*normals;
+	  
+		z = (z_left+z_right)/2.0;		   
+				   
+		//w_left = ql[0];
+		//h_left = w_left-z;
+		//uh_left = ql[1];
+		
+
+
+		// Compute speeds in x-direction
+		w_left = ql[0];          
+		h_left = w_left-z;
+		uh_left = ql[1];
+
+		u_left = _compute_speed(&uh_left, &h_left, epsilon, h0);
+
+		w_right = qr[0];
+		h_right = w_right-z;
+		uh_right = qr[1];
+
+		u_right = _compute_speed(&uh_right, &h_right, epsilon, h0);
+  
+		soundspeed_left = sqrt(g*h_left);
+		soundspeed_right = sqrt(g*h_right);
+		
+		s_max = max(u_left+soundspeed_left, u_right+soundspeed_right);
+		if (s_max < 0.0) s_max = 0.0;
+	
+		s_min = min(u_left-soundspeed_left, u_right-soundspeed_right);
+		if (s_min > 0.0) s_min = 0.0;
+		
+		
+		// Flux formulas
+		flux_left[0] = u_left*h_left;
+		flux_left[1] = u_left*uh_left + 0.5*g*h_left*h_left;
+
+		flux_right[0] = u_right*h_right;
+		flux_right[1] = u_right*uh_right + 0.5*g*h_right*h_right;
+
+		// Flux computation
+		denom = s_max-s_min;
+		if (denom < epsilon) {
+			for (i=0; i<2; i++) edgeflux[i] = 0.0;
+			*max_speed = 0.0;
+		} else {
+			edgeflux[0] = s_max*flux_left[0] - s_min*flux_right[0];
+			edgeflux[0] += s_max*s_min*(qr[0]-ql[0]);
+			edgeflux[0] /= denom;
+			edgeflux[1] = s_max*flux_left[1] - s_min*flux_right[1];
+			edgeflux[1] += s_max*s_min*(qr[1]-ql[1]);
+			edgeflux[1] /= denom;
+			edgeflux[1] *= normals;
+    
+		// Maximal wavespeed
+        *max_speed = max(fabs(s_max), fabs(s_min));
+		}  
+    return 0;		
+	}
+		
+		
+	
+	
+// Computational function for flux computation
+double _compute_fluxes_ext(
+			   double cfl,
+			   double timestep,
+			   double epsilon,
+			   double g,
+			   double h0,
+			   long* neighbours,
+			   long* neighbour_vertices,
+			   double* normals,
+			   double* areas,
+			   double* stage_edge_values,
+			   double* xmom_edge_values,
+			   double* bed_edge_values,
+			   double* stage_boundary_values,
+			   double* xmom_boundary_values,
+			   double* stage_explicit_update,
+			   double* xmom_explicit_update,
+			   int number_of_elements,
+			   double* max_speed_array) {
+		
+                double flux[2], ql[2], qr[2], edgeflux[2];
+		double zl, zr, max_speed, normal;
+		int k, i, ki, n, m, nm=0;
+		
+		
+		for (k=0; k<number_of_elements; k++) {
+			flux[0] = 0.0;
+			flux[1] = 0.0;
+			
+			for (i=0; i<2; i++) {
+				ki = k*2+i;
+				
+				ql[0] = stage_edge_values[ki];
+				ql[1] = xmom_edge_values[ki];
+				zl = bed_edge_values[ki];
+				
+				n = neighbours[ki];
+				if (n<0) {
+					m = -n-1;
+					qr[0] = stage_boundary_values[m];
+					qr[1] = xmom_boundary_values[m];
+					zr = zl;
+				} else {
+					m = neighbour_vertices[ki];
+					nm = n*2+m;
+					qr[0] = stage_edge_values[nm];
+					qr[1] = xmom_edge_values[nm];
+					zr = bed_edge_values[nm];				
+				}
+				
+				normal = normals[ki];
+				_flux_function(ql, qr, zl, zr, normal, g, epsilon, h0, edgeflux, &max_speed);
+				flux[0] -= edgeflux[0];
+				flux[1] -= edgeflux[1];
+				
+				// Update timestep based on edge i and possibly neighbour n
+				if (max_speed > epsilon) {
+				    // Original CFL calculation
+				    
+				    timestep = min(timestep, 0.5*cfl*areas[k]/max_speed); 
+				    if (n>=0) {
+					timestep = min(timestep, 0.5*cfl*areas[n]/max_speed); 
+				    }
+				}
+            } // End edge i (and neighbour n)
+			flux[0] /= areas[k];
+			stage_explicit_update[k] = flux[0];
+			flux[1] /= areas[k];
+			xmom_explicit_update[k] = flux[1];
+			
+			//Keep track of maximal speeds
+			max_speed_array[k]=max_speed;
+		}
+		return timestep;	
+	}
+
+//=========================================================================
+// Python Glue
+//=========================================================================
+PyObject *compute_fluxes_ext(PyObject *self, PyObject *args) {
+  
+   PyObject 
+	*domain,
+	*stage, 
+	*xmom, 
+	*bed;
+
+    PyArrayObject 
+	*neighbours, 
+	*neighbour_vertices,
+	*normals, 
+	*areas,
+	*stage_vertex_values,
+	*xmom_vertex_values,
+	*bed_vertex_values,
+	*stage_boundary_values,
+	*xmom_boundary_values,
+	*stage_explicit_update,
+	*xmom_explicit_update,
+	*max_speed_array;
+    
+  double timestep, epsilon, g, h0, cfl;
+  int number_of_elements;
+
+    
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "dOOOO",
+			&timestep,
+			&domain,
+			&stage,
+			&xmom,
+			&bed)) {
+      PyErr_SetString(PyExc_RuntimeError, "comp_flux_vel_ext.c: compute_fluxes_ext could not parse input");
+      return NULL;
+  }
+
+
+    epsilon           = get_python_double(domain,"epsilon");
+    g                 = get_python_double(domain,"g");
+    h0                = get_python_double(domain,"h0");
+    cfl               = get_python_double(domain,"CFL");
+ 
+    
+    neighbours        = get_consecutive_array(domain, "neighbours");
+    neighbour_vertices= get_consecutive_array(domain, "neighbour_vertices"); 
+    normals           = get_consecutive_array(domain, "normals");
+    areas             = get_consecutive_array(domain, "areas");    
+    max_speed_array   = get_consecutive_array(domain, "max_speed_array");
+    
+    stage_vertex_values = get_consecutive_array(stage, "vertex_values");    
+    xmom_vertex_values  = get_consecutive_array(xmom, "vertex_values");    
+    bed_vertex_values   = get_consecutive_array(bed, "vertex_values");    
+
+    stage_boundary_values = get_consecutive_array(stage, "boundary_values");    
+    xmom_boundary_values  = get_consecutive_array(xmom, "boundary_values");    
+
+
+    stage_explicit_update = get_consecutive_array(stage, "explicit_update");    
+    xmom_explicit_update  = get_consecutive_array(xmom, "explicit_update");    
+
+
+
+    number_of_elements = stage_vertex_values -> dimensions[0];
+
+
+ 
+    // Call underlying flux computation routine and update 
+    // the explicit update arrays 
+    timestep = _compute_fluxes_ext(
+	cfl,
+	timestep,
+	epsilon,
+	g,
+	h0,
+	(long*) neighbours -> data,
+	(long*) neighbour_vertices -> data,
+	(double*) normals -> data,
+	(double*) areas -> data,
+	(double*) stage_vertex_values -> data,
+	(double*) xmom_vertex_values -> data,
+	(double*) bed_vertex_values -> data,
+	(double*) stage_boundary_values -> data,
+	(double*) xmom_boundary_values -> data,
+	(double*) stage_explicit_update -> data,
+	(double*) xmom_explicit_update -> data,
+	number_of_elements,
+	(double*) max_speed_array -> data);
+
+
+  Py_DECREF(neighbours);
+  Py_DECREF(neighbour_vertices);
+  Py_DECREF(normals);
+  Py_DECREF(areas);
+  Py_DECREF(stage_vertex_values);
+  Py_DECREF(xmom_vertex_values);
+  Py_DECREF(bed_vertex_values);
+  Py_DECREF(stage_boundary_values);
+  Py_DECREF(xmom_boundary_values);
+  Py_DECREF(stage_explicit_update);
+  Py_DECREF(xmom_explicit_update);
+  Py_DECREF(max_speed_array);
+
+
+
+
+  // Return updated flux timestep
+  return Py_BuildValue("d", timestep);
+}
+
+
+//------------------------------------------------
+// New velocity based compute fluxes
+//------------------------------------------------
+PyObject *compute_fluxes_vel_ext(PyObject *self, PyObject *args) {
+  
+    PyObject 
+	*domain,
+	*stage, 
+	*xmom, 
+	*bed,
+	*height,
+	*velocity;
+
+    PyArrayObject 
+	*neighbours, 
+	*neighbour_vertices,
+	*normals, 
+	*areas,
+	*stage_vertex_values,
+	*xmom_vertex_values,
+	*bed_vertex_values,
+	*height_vertex_values,
+	*velocity_vertex_values,
+	*stage_boundary_values,
+	*xmom_boundary_values,
+	*bed_boundary_values,
+	*height_boundary_values,
+	*velocity_boundary_values,
+	*stage_explicit_update,
+	*xmom_explicit_update,
+	*max_speed_array;
+    
+  double timestep, epsilon, g, h0, cfl;
+  int number_of_elements;
+
+    
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "dOOOOOO",
+			&timestep,
+			&domain,
+			&stage,
+			&xmom,
+			&bed,
+			&height,
+			&velocity)) {
+      PyErr_SetString(PyExc_RuntimeError, "comp_flux_vel_ext.c: compute_fluxes_vel_ext could not parse input");
+      printf("comp_flux_vel_ext.c: compute_fluxes_vel_ext could not parse input");
+      return NULL;
+  }
+
+
+    epsilon           = get_python_double(domain,"epsilon");
+    g                 = get_python_double(domain,"g");
+    h0                = get_python_double(domain,"h0");
+    cfl               = get_python_double(domain,"CFL");
+ 
+    
+    neighbours        = get_consecutive_array(domain, "neighbours");
+    neighbour_vertices= get_consecutive_array(domain, "neighbour_vertices"); 
+    normals           = get_consecutive_array(domain, "normals");
+    areas             = get_consecutive_array(domain, "areas");    
+    max_speed_array   = get_consecutive_array(domain, "max_speed_array");
+    
+    stage_vertex_values      = get_consecutive_array(stage,    "vertex_values");    
+    xmom_vertex_values       = get_consecutive_array(xmom,     "vertex_values");    
+    bed_vertex_values        = get_consecutive_array(bed,      "vertex_values");    
+    height_vertex_values     = get_consecutive_array(height,   "vertex_values");    
+    velocity_vertex_values   = get_consecutive_array(velocity, "vertex_values");    
+
+    stage_boundary_values     = get_consecutive_array(stage,     "boundary_values");    
+    xmom_boundary_values      = get_consecutive_array(xmom,      "boundary_values");    
+    bed_boundary_values       = get_consecutive_array(bed,       "boundary_values");    
+    height_boundary_values    = get_consecutive_array(height,    "boundary_values");    
+    velocity_boundary_values  = get_consecutive_array(velocity,  "boundary_values");    
+
+
+    stage_explicit_update = get_consecutive_array(stage, "explicit_update");    
+    xmom_explicit_update  = get_consecutive_array(xmom,  "explicit_update");    
+
+    number_of_elements = stage_vertex_values -> dimensions[0];
+ 
+
+    //printf("comp_flux_vel 1 N = %d %15.5e %15.5e %15.5e %15.5e %15.5e \n",number_of_elements,cfl,timestep,epsilon,g,h0);
+
+
+
+    // Call underlying flux computation routine and update 
+    // the explicit update arrays 
+    timestep = _compute_fluxes_vel_ext(cfl,
+				       timestep,
+				       epsilon,
+				       g,
+				       h0,
+				       (long*) neighbours -> data,
+				       (long*) neighbour_vertices -> data,
+				       (double*) normals -> data,
+				       (double*) areas -> data,
+				       (double*) stage_vertex_values -> data,
+				       (double*) xmom_vertex_values -> data,
+				       (double*) bed_vertex_values -> data,
+				       (double*) height_vertex_values -> data,
+				       (double*) velocity_vertex_values -> data,
+				       (double*) stage_boundary_values -> data,
+				       (double*) xmom_boundary_values -> data,
+				       (double*) bed_boundary_values -> data,
+				       (double*) height_boundary_values -> data,
+				       (double*) velocity_boundary_values -> data,
+				       (double*) stage_explicit_update -> data,
+				       (double*) xmom_explicit_update -> data,
+				       number_of_elements,
+				       (double*) max_speed_array -> data);
+
+    //printf("comp_flux_vel 2 \n");    
+    
+    Py_DECREF(neighbours);
+    Py_DECREF(neighbour_vertices);
+    Py_DECREF(normals);
+    Py_DECREF(areas);
+    Py_DECREF(stage_vertex_values);
+    Py_DECREF(xmom_vertex_values);
+    Py_DECREF(bed_vertex_values);
+    Py_DECREF(height_vertex_values);
+    Py_DECREF(velocity_vertex_values);
+    Py_DECREF(stage_boundary_values);
+    Py_DECREF(xmom_boundary_values);
+    Py_DECREF(bed_boundary_values);
+    Py_DECREF(height_boundary_values);
+    Py_DECREF(velocity_boundary_values);
+    Py_DECREF(stage_explicit_update);
+    Py_DECREF(xmom_explicit_update);
+    Py_DECREF(max_speed_array);
+    
+    //printf("comp_flux_vel 3 \n");
+
+    // Return updated flux timestep
+    return Py_BuildValue("d", timestep);
+}
+
+
+
+//-------------------------------
+// Method table for python module
+//-------------------------------
+
+static struct PyMethodDef MethodTable[] = {
+  {"compute_fluxes_ext", compute_fluxes_ext, METH_VARARGS, "Print out"},
+  {"compute_fluxes_vel_ext", compute_fluxes_vel_ext, METH_VARARGS, "Print out"},
+  {NULL, NULL}
+};
+
+// Module initialisation
+void initsww_vel_comp_flux_ext(void){
+  Py_InitModule("sww_vel_comp_flux_ext", MethodTable);
+  import_array();
+}
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_vel_domain.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_vel_domain.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_vel_domain.py	(revision 7884)
@@ -0,0 +1,363 @@
+"""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 anuga_1d.base.generic_domain import *
+from sww_boundary_conditions import *
+from sww_forcing_terms import *
+
+#Shallow water domain
+class Domain(Generic_domain):
+
+    def __init__(self, coordinates, boundary = None, tagged_elements = None):
+
+        conserved_quantities = ['stage', 'xmomentum']
+        evolved_quantities = ['stage', 'xmomentum', 'elevation', 'height', 'velocity']
+        other_quantities = ['friction']
+        Generic_domain.__init__(self,
+                                coordinates = coordinates,
+                                boundary = boundary,
+                                conserved_quantities = conserved_quantities,
+                                evolved_quantities = evolved_quantities,
+                                other_quantities = other_quantities,
+                                tagged_elements = tagged_elements)
+        
+        from anuga_1d.config import minimum_allowed_height, g, h0
+        self.minimum_allowed_height = minimum_allowed_height
+        self.g = g
+        self.h0 = h0
+
+        #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"
+
+        
+        #Stored output
+        self.store = True
+        self.format = 'sww'
+        self.smooth = True
+
+        
+        #Reduction operation for get_vertex_values
+        from anuga_1d.base.util import mean
+        self.reduction = mean
+        #self.reduction = min  #Looks better near steep slopes
+
+        self.set_quantities_to_be_stored(['stage','xmomentum'])
+
+	self.__doc__ = 'sww_vel_domain'
+
+        self.check_integrity()
+
+
+
+    def check_integrity(self):
+
+        #Check that we are solving the shallow water wave equation
+
+        msg = 'First conserved quantity must be "stage"'
+        assert self.conserved_quantities[0] == 'stage', msg
+        msg = 'Second conserved quantity must be "xmomentum"'
+        assert self.conserved_quantities[1] == 'xmomentum', msg
+
+        msg = 'First evolved quantity must be "stage"'
+        assert self.evolved_quantities[0] == 'stage', msg
+        msg = 'Second evolved quantity must be "xmomentum"'
+        assert self.evolved_quantities[1] == 'xmomentum', msg
+        msg = 'Third evolved quantity must be "elevation"'
+        assert self.evolved_quantities[2] == 'elevation', msg
+        msg = 'Fourth evolved quantity must be "height"'
+        assert self.evolved_quantities[3] == 'height', msg
+        msg = 'Fifth evolved quantity must be "velocity"'
+        assert self.evolved_quantities[4] == 'velocity', msg
+
+        Generic_domain.check_integrity(self)
+
+    def compute_fluxes(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        compute_fluxes_vel(self)
+
+    def distribute_to_vertices_and_edges(self):
+        #Call correct module function
+        #(either from this module or C-extension)
+        distribute_to_vertices_and_edges_limit_w_u(self)
+        
+
+#=============== End of Shallow Water Domain ===============================
+#-----------------------------------
+# Compute fluxes interface
+#-----------------------------------
+def compute_fluxes(domain):
+    """
+    Python version of compute fluxes (local_compute_fluxes)
+    is available in test_shallow_water_vel_domain.py
+    """
+ 
+
+    from numpy import zeros 
+    import sys
+
+	
+    timestep = float(sys.maxint)
+
+    stage = domain.quantities['stage']
+    xmom = domain.quantities['xmomentum']
+    bed = domain.quantities['elevation']
+
+
+    from anuga_1d.sww_flow.sww_vel_comp_flux_ext import compute_fluxes_ext
+
+    domain.flux_timestep = compute_fluxes_ext(timestep,domain,stage,xmom,bed)
+
+
+#-----------------------------------
+# Compute flux definition with vel
+#-----------------------------------
+def compute_fluxes_vel(domain):
+    from Numeric import zeros, Float
+    import sys
+
+	
+    timestep = float(sys.maxint)
+
+    stage    = domain.quantities['stage']
+    xmom     = domain.quantities['xmomentum']
+    bed      = domain.quantities['elevation']
+    height   = domain.quantities['height']
+    velocity = domain.quantities['velocity']
+
+
+    from anuga_1d.sww.sww_vel_comp_flux_ext import compute_fluxes_vel_ext
+
+    domain.flux_timestep = compute_fluxes_vel_ext(timestep,domain,stage,xmom,bed,height,velocity)
+
+
+
+#--------------------------------------------------------------------------
+def distribute_to_vertices_and_edges_limit_w_u(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)  
+
+    import sys
+    from numpy import zeros
+    from anuga_1d.config import epsilon, h0
+	
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+    #Arrays   
+    w_C   = Stage.centroid_values    
+    uh_C  = Xmom.centroid_values    
+    z_C   = Bed.centroid_values
+    h_C   = Height.centroid_values
+    u_C   = Velocity.centroid_values
+	
+    #print id(h_C)
+##     for i in range(N):
+## 	h_C[i] = w_C[i] - z_C[i]						
+##         if h_C[i] <= 1.0e-12:
+## 	    #print 'h_C[%d]= %15.5e\n' % (i,h_C[i])
+## 	    h_C[i] = 0.0
+## 	    w_C[i] = z_C[i]
+## 	    #uh_C[i] = 0.0
+            
+##  #           u_C[i] = 0.0
+##  #       else:
+##  #           u_C[i] = uh_C[i]/h_C[i]
+		
+    h0 = 1.0e-12    
+    for i in range(N):
+        h_C[i] = w_C[i] - z_C[i]						
+	if h_C[i] < 1.0e-12:
+	    u_C[i] = 0.0  #Could have been negative
+	    h_C[i] = 0.0
+            w_C[i] = z_C[i]
+	else:
+            u_C[i]  = uh_C[i]/(h_C[i] + h0/h_C[i])
+            #u_C[i]  = uh_C[i]/h_C[i]
+	
+    for name in [ 'velocity', 'stage' ]:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            Q.extrapolate_second_order()
+        else:
+            raise 'Unknown order'
+
+    w_V  = domain.quantities['stage'].vertex_values			
+    z_V  = domain.quantities['elevation'].vertex_values	
+    h_V  = domain.quantities['height'].vertex_values
+    u_V  = domain.quantities['velocity'].vertex_values		
+    uh_V = domain.quantities['xmomentum'].vertex_values	
+
+    #print w_V
+    #print z_V
+    
+    h_V[:,:]    = w_V - z_V
+    for i in range(len(h_C)):
+        for j in range(2):
+            if h_V[i,j] < 0.0 :
+                #print 'h_V[%d,%d] = %f \n' % (i,j,h_V[i,j])                 
+                dh = h_V[i,j]
+                h_V[i,j] = 0.0
+                w_V[i,j] = z_V[i,j]
+                h_V[i,(j+1)%2] = h_V[i,(j+1)%2] + dh
+                w_V[i,(j+1)%2] = w_V[i,(j+1)%2] + dh
+                
+    uh_V[:,:] = u_V * h_V
+
+    
+    return
+
+#---------------------------------------------------------------------------
+def distribute_to_vertices_and_edges_limit_w_uh(domain):
+    """Distribution from centroids to vertices specific to the
+    shallow water wave equation.
+
+    In addition, all conserved quantities get distributed as per either a
+    constant (order==1) or a piecewise linear function (order==2).
+
+    Precondition:
+      All quantities defined at centroids and bed elevation defined at
+      vertices.
+
+    Postcondition
+      Conserved quantities defined at vertices
+
+    """
+
+    import sys
+    from numpy import zeros
+    from anuga_1d.config import epsilon, h0
+	
+    N = domain.number_of_elements
+
+    #Shortcuts
+    Stage = domain.quantities['stage']
+    Xmom = domain.quantities['xmomentum']
+    Bed = domain.quantities['elevation']
+    Height = domain.quantities['height']
+    Velocity = domain.quantities['velocity']
+
+    #Arrays   
+    w_C   = Stage.centroid_values    
+    uh_C  = Xmom.centroid_values    
+    z_C   = Bed.centroid_values
+    h_C   = Height.centroid_values
+    u_C   = Velocity.centroid_values
+	
+
+    for i in range(N):
+	h_C[i] = w_C[i] - z_C[i]						
+        if h_C[i] <= 1.0e-6:
+	    #print 'h_C[%d]= %15.5e\n' % (i,h_C[i])
+	    h_C[i] = 0.0
+	    w_C[i] = z_C[i]
+	    uh_C[i] = 0.0
+            
+    for name in [ 'stage', 'xmomentum']:
+        Q = domain.quantities[name]
+        if domain.order == 1:
+            Q.extrapolate_first_order()
+        elif domain.order == 2:
+            Q.extrapolate_second_order()
+        else:
+            raise 'Unknown order'
+
+    w_V  = domain.quantities['stage'].vertex_values			
+    z_V  = domain.quantities['elevation'].vertex_values	
+    h_V  = domain.quantities['height'].vertex_values
+    u_V  = domain.quantities['velocity'].vertex_values		
+    uh_V = domain.quantities['xmomentum'].vertex_values	
+
+    h_V[:,:]    = w_V - z_V
+
+    for i in range(len(h_C)):
+        for j in range(2):
+            if h_V[i,j] < 0.0 :
+                #print 'h_V[%d,%d] = %f \n' % (i,j,h_V[i,j])                 
+                dh = h_V[i,j]
+                h_V[i,j] = 0.0
+                w_V[i,j] = z_V[i,j]
+                h_V[i,(j+1)%2] = h_V[i,(j+1)%2] + dh
+                w_V[i,(j+1)%2] = w_V[i,(j+1)%2] + dh
+                u_V[i,j] = 0.0
+            if h_V[i,j] < h0:
+                u_V[i,j]
+            else:
+                u_V[i,j] = uh_V[i,j]/(h_V[i,j] + h0/h_V[i,j])
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_wet_dry.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_wet_dry.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/sww_wet_dry.py	(revision 7884)
@@ -0,0 +1,126 @@
+"""
+This module contains various auxiliary function used
+to ascertain wet dry areas.
+"""
+
+
+import numpy
+
+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 numpy 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):
+
+    import math
+    #N = len(C)
+    #u = zeros(N,numpy.float)    ## water velocity
+    #h = zeros(N,numpy.float)    ## water depth
+    x = C
+    g = 9.81
+
+
+    ## Define Basin Bathymetry
+    #z_b = zeros(N,numpy.float) ## elevation of basin
+    #z = zeros(N,numpy.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 = math.sqrt(2*g*z_infty)/L_x ## angular frequency of osccilation
+
+    x1 = A0*cos(omega*t)-L_x # left shoreline
+    x2 = A0*cos(omega*t)+L_x # right shoreline
+    if (x >=x1) & (x <= x2):
+        z_b = z_infty*(x**2/L_x**2) ## or A0*cos(omega*t)\pmL_x
+        u = -A0*omega*sin(omega*t)
+        z = z_infty+2*A0*z_infty/L_x*cos(omega*t)*(x/L_x-0.5*A0/(L_x)*cos(omega*t))
+    else:
+       z_b = z_infty*(x**2/L_x**2)
+       u=0.0
+       z = z_b
+    h = z-z_b
+    return z,u*h
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_all.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_all.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_all.py	(revision 7884)
@@ -0,0 +1,83 @@
+"""Regression testing framework
+This module will search for scripts in the same directory named
+test_*.py.  Each such script should be a test suite that tests a
+module through PyUnit. This script will aggregate all
+found test suites into one big test suite and run them all at once.
+"""
+
+# Author: Mark Pilgrim
+# Modified by Ole Nielsen
+
+import unittest
+import os
+
+
+#List files that should be excluded from the testing process.
+#E.g. if they are known to fail and under development
+exclude = [] 
+
+
+def get_test_files(path):
+
+    import sys
+
+    files = os.listdir(path)
+
+    #Check sub directories
+    test_files = []
+    for file in files:
+        if os.path.isdir(file):
+            sys.path.append(file)
+            #print 'Recursing into', file
+            test_files += get_test_files(path + os.sep + file)
+        elif file[:5] == 'test_' and file[-2:] == 'py':
+            #print 'Appending', file
+            test_files.append(file)
+        else:
+            pass
+    return test_files
+
+
+
+def regressionTest():
+    import sys, os, re, unittest
+    path = os.path.split(sys.argv[0])[0] or os.getcwd()
+
+
+    files = get_test_files(path)
+
+
+
+    #test = re.compile('^test_[\w]*.py$', re.IGNORECASE)
+    #files = filter(test.search, files)
+
+
+    try:
+        files.remove(__file__)  #Remove self from list (Ver 2.3. or later)
+    except:
+        files.remove('test_all.py')
+
+    print 'Testing:'
+    for file in files:
+        print '  ' + file
+
+    if globals().has_key('exclude'):
+        for file in exclude:
+            files.remove(file)
+            print 'WARNING: File '+ file + ' excluded from testing'
+
+
+    filenameToModuleName = lambda f: os.path.splitext(f)[0]
+    #print "files",files 
+    moduleNames = map(filenameToModuleName, files)
+    #print "moduleNames",moduleNames
+    modules = map(__import__, moduleNames)
+    load = unittest.defaultTestLoader.loadTestsFromModule
+    return unittest.TestSuite(map(load, modules))
+
+################################################################################
+
+if __name__ == '__main__':   
+    suite = regressionTest()
+    runner = unittest.TextTestRunner() #verbosity=2)
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_sww_domain.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_sww_domain.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_sww_domain.py	(revision 7884)
@@ -0,0 +1,208 @@
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt, pi
+
+
+from sww_domain import *
+import sww_python
+
+
+import numpy
+
+
+class Test_Shallow_Water(unittest.TestCase):
+    def setUp(self):
+        self.points = [0.0, 1.0, 2.0, 3.0]
+        self.vertex_values = [[1.0,2.0],[4.0,5.0],[-1.0,2.0]]
+        self.points2 = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
+        
+    def tearDown(self):
+        pass
+        #print "  Tearing down"
+
+
+    def test_creation(self):
+        domain = Domain(self.points)
+        assert numpy.allclose(domain.centroids, [0.5, 1.5, 2.5])
+
+    def test_compute_fluxes(self):
+        """
+        Compare shallow_water_domain flux calculation against a previous
+        Python implementation (defined in this file)
+        """
+        domain = Domain(self.points)
+        domain.set_quantity('stage',2.0)
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+        stage_ud, xmom_ud = sww_python.compute_fluxes(domain)
+
+        domain.distribute_to_vertices_and_edges()
+        domain.compute_fluxes()
+
+        assert numpy.allclose( domain.quantities['stage'].explicit_update, stage_ud )
+        assert numpy.allclose( domain.quantities['xmomentum'].explicit_update, xmom_ud )
+
+
+    def test_sww_python_flux_function(self):
+        normal = 1.0
+        ql = numpy.array([1.0, 2.0],numpy.float)
+        qr = numpy.array([1.0, 2.0],numpy.float)
+        zl = 0.0
+        zr = 0.0
+
+        #This assumes h0 = 1.0e-3!!
+        edgeflux, maxspeed = sww_python.flux_function(normal, ql,qr,zl,zr)
+        #print maxspeed
+        #print edgeflux
+        
+        assert numpy.allclose([2.0, 8.9], edgeflux, rtol=1.0e-005)
+        assert numpy.allclose(5.1305, maxspeed, rtol=1.0e-005)
+
+        normal = -1.0
+        ql = numpy.array([1.0, 2.0],numpy.float)
+        qr = numpy.array([1.0, 2.0],numpy.float)
+        zl = 0.0
+        zr = 0.0
+
+        edgeflux, maxspeed = sww_python.flux_function(normal, ql,qr,zl,zr)
+
+
+        #print maxspeed
+        #print edgeflux        
+        
+        assert numpy.allclose([-2.0, -8.9], edgeflux, rtol=1.0e-005)
+        assert numpy.allclose(5.1305, maxspeed, rtol=1.0e-005)
+
+
+
+    def test_gravity_for_loops(self):
+        """
+        Compare shallow_water_domain gravity calculation
+        """
+
+        def slope_one(x):
+            return x
+
+        domain = Domain(self.points)
+        domain.set_quantity('stage',4.0)
+        domain.set_quantity('elevation',slope_one)
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+        domain.set_spatial_order(1)
+        domain.distribute_to_vertices_and_edges()
+
+        gravity_for_loops(domain)     
+
+        assert numpy.allclose( [-34.3, -24.5, -14.7], domain.quantities['xmomentum'].explicit_update )
+
+
+    def test_gravity(self):
+        """
+        Compare shallow_water_domain gravity calculation
+        """
+
+        def slope_one(x):
+            return x
+
+        domain = Domain(self.points)
+        domain.set_quantity('stage',4.0)
+        domain.set_quantity('elevation',slope_one)
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+
+        domain.set_spatial_order(1)
+        domain.distribute_to_vertices_and_edges()
+
+        gravity(domain)
+
+        assert numpy.allclose( [-34.3, -24.5, -14.7], domain.quantities['xmomentum'].explicit_update )
+
+
+    def test_evolve_first_order(self):
+        """
+        Compare still lake solution for various versions of shallow_water_domain
+        """
+        
+        def slope_square(x):
+            return numpy.maximum(4.0-(x-5.0)*(x-5.0), 0.0)
+
+        domain = Domain(self.points2)
+        domain.set_quantity('stage',10.0)
+        domain.set_quantity('elevation',slope_square)
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+        domain.default_order = 1
+        domain.set_timestepping_method('euler')
+        
+        yieldstep=1.0
+        finaltime=1.0
+
+        for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+            pass
+        
+
+        assert numpy.allclose( 10.0*numpy.ones(10), domain.quantities['stage'].centroid_values )
+        assert numpy.allclose( numpy.zeros(10), domain.quantities['xmomentum'].centroid_values )
+
+
+    def test_evolve_euler_second_order_space(self):
+        """
+        Compare still lake solution for various versions of shallow_water_domain
+        """
+
+        def slope_square(x):
+            return numpy.maximum(4.0-(x-5.0)*(x-5.0), 0.0)
+
+        domain = Domain(self.points2)
+        domain.set_quantity('stage',10.0)
+        domain.set_quantity('elevation',slope_square)
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+        domain.default_order = 2
+        domain.set_timestepping_method('rk2')
+        yieldstep=1.0
+        finaltime=1.0
+
+        for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+            pass
+        
+        assert numpy.allclose( 10.0*numpy.ones(10), domain.quantities['stage'].centroid_values )
+        assert numpy.allclose( numpy.zeros(10), domain.quantities['xmomentum'].centroid_values )
+
+    def test_evolve_second_order_space_time(self):
+        """
+        Compare still lake solution for various versions of shallow_water_domain
+        """
+
+        def slope_square(x):
+            return numpy.maximum(4.0-(x-5.0)*(x-5.0), 0.0)
+
+        domain = Domain(self.points2)
+        domain.set_quantity('stage',10.0)
+        domain.set_quantity('elevation',slope_square)
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+        domain.default_order = 2
+        domain.set_timestepping_method('rk3')
+
+        yieldstep=1.0
+        finaltime=1.0
+
+        for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+            pass
+        
+        assert numpy.allclose( 10.0*numpy.ones(10), domain.quantities['stage'].centroid_values )
+        assert numpy.allclose( numpy.zeros(10), domain.quantities['xmomentum'].centroid_values )
+
+
+
+#==============================================================================
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Shallow_Water, 'test_gravity')
+    #suite = unittest.makeSuite(Test_Shallow_Water, 'test_evolve_first_order')
+
+
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_sww_vel_domain.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_sww_vel_domain.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/sww/test_sww_vel_domain.py	(revision 7884)
@@ -0,0 +1,516 @@
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt, pi
+
+
+from sww_vel_domain import *
+
+
+from numpy import allclose, array, ones, maximum, zeros
+import numpy
+
+
+class Test_Shallow_Water(unittest.TestCase):
+    def setUp(self):
+        self.points = [0.0, 1.0, 2.0, 3.0]
+        self.vertex_values = [[1.0,2.0],[4.0,5.0],[-1.0,2.0]]
+        self.points2 = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
+        
+    def tearDown(self):
+        pass
+        #print "  Tearing down"
+
+
+    def test_creation(self):
+        domain = Domain(self.points)
+        assert allclose(domain.centroids, [0.5, 1.5, 2.5])
+
+    def test_reflective_boundary(self):
+        """
+        Test setting reflective boundary
+        """
+        
+        domain = Domain(self.points)
+        domain.set_quantity('stage',2.0)
+        domain.set_quantity('xmomentum',6.0)
+        
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+
+        domain.distribute_to_vertices_and_edges()
+        domain.update_boundary()
+
+##         print 'In test reflective'
+##         print domain.quantities['stage'].vertex_values
+##         print domain.quantities['xmomentum'].vertex_values
+##         print domain.quantities['elevation'].vertex_values
+##         print domain.quantities['height'].vertex_values
+##         print domain.quantities['velocity'].vertex_values
+        
+##         print domain.quantities['stage'].boundary_values
+##         print domain.quantities['xmomentum'].boundary_values
+##         print domain.quantities['elevation'].boundary_values
+##         print domain.quantities['height'].boundary_values
+##         print domain.quantities['velocity'].boundary_values
+
+        assert allclose( domain.quantities['stage'    ].boundary_values, [2.0, 2.0])
+        assert allclose( domain.quantities['xmomentum'].boundary_values, [-6.0, -6.0])
+        assert allclose( domain.quantities['elevation'].boundary_values, [0.0, 0.0])
+        assert allclose( domain.quantities['height'   ].boundary_values, [2.0, 2.0])
+        assert allclose( domain.quantities['velocity' ].boundary_values, [-3.0, -3.0])
+
+        
+
+    def test_dirichlet_boundary(self):
+        """
+        Test setting dirichlet boundary
+        """
+        
+        domain = Domain(self.points)
+        domain.set_quantity('stage',2.0)
+        domain.set_quantity('xmomentum',6.0)
+        
+        domain.set_boundary({'exterior' : Dirichlet_boundary([3.0, 8.0, 1.0, 2.0, 4.0])})
+
+
+        domain.distribute_to_vertices_and_edges()
+        domain.update_boundary()
+
+##         print 'In test dirichlet'
+##         print domain.quantities['stage'].vertex_values
+##         print domain.quantities['xmomentum'].vertex_values
+##         print domain.quantities['elevation'].vertex_values
+##         print domain.quantities['height'].vertex_values
+##         print domain.quantities['velocity'].vertex_values
+        
+##         print domain.quantities['stage'].boundary_values
+##         print domain.quantities['xmomentum'].boundary_values
+##         print domain.quantities['elevation'].boundary_values
+##         print domain.quantities['height'].boundary_values
+##         print domain.quantities['velocity'].boundary_values
+
+        assert allclose( domain.quantities['stage'    ].boundary_values, [3.0, 3.0])
+        assert allclose( domain.quantities['xmomentum'].boundary_values, [8.0, 8.0])
+        assert allclose( domain.quantities['elevation'].boundary_values, [1.0, 1.0])
+        assert allclose( domain.quantities['height'   ].boundary_values, [2.0, 2.0])
+        assert allclose( domain.quantities['velocity' ].boundary_values, [4.0, 4.0])
+
+
+    def test_compute_fluxes(self):
+        """
+        Compare shallow_water_domain flux calculation against a previous
+        Python implementation (defined in this file)
+        """
+        domain = Domain(self.points)
+        domain.set_quantity('stage',2.0)
+        domain.set_boundary({'exterior' : Dirichlet_boundary([0.0, 0.0, 0.0, 0.0, 0.0])})
+
+
+        domain.distribute_to_vertices_and_edges()
+        domain.update_boundary()
+
+	import sww_python
+        stage_ud, xmom_ud = sww_python.compute_fluxes(domain)
+
+        domain.compute_fluxes()
+        
+#        print domain.quantities['stage'].vertex_values
+#        print domain.quantities['xmomentum'].vertex_values
+#        print domain.quantities['elevation'].vertex_values
+#        print domain.quantities['height'].vertex_values
+#        print domain.quantities['velocity'].vertex_values
+#
+#        print domain.quantities['stage'].boundary_values
+#        print domain.quantities['xmomentum'].boundary_values
+#        print domain.quantities['elevation'].boundary_values
+#        print domain.quantities['height'].boundary_values
+#        print domain.quantities['velocity'].boundary_values
+        
+
+        assert allclose( domain.quantities['stage'].explicit_update, stage_ud )
+        assert allclose( domain.quantities['xmomentum'].explicit_update, xmom_ud )
+
+
+    def test_local_flux_function(self):
+        normal = 1.0
+        ql = array([1.0, 2.0],numpy.float)
+        qr = array([1.0, 2.0],numpy.float)
+        zl = 0.0
+        zr = 0.0
+
+        #This assumes h0 = 1.0e-3!!
+	import sww_python
+        edgeflux, maxspeed = sww_python.flux_function(normal, ql,qr,zl,zr)
+        #print maxspeed
+        #print edgeflux
+        
+        assert allclose([2.0, 8.9], edgeflux, rtol=1.0e-005)
+        assert allclose(5.1305, maxspeed, rtol=1.0e-005)
+
+        normal = -1.0
+        ql = array([1.0, 2.0],numpy.float)
+        qr = array([1.0, 2.0],numpy.float)
+        zl = 0.0
+        zr = 0.0
+
+        edgeflux, maxspeed = sww_python.flux_function(normal, ql,qr,zl,zr)
+
+
+        #print maxspeed
+        #print edgeflux        
+        
+        assert allclose([-2.0, -8.9], edgeflux, rtol=1.0e-005)
+        assert allclose(5.1305, maxspeed, rtol=1.0e-005)
+
+
+    def test_gravity(self):
+        """
+        Compare shallow_water_domain gravity calculation
+        """
+
+        def slope_one(x):
+            return x
+
+        domain = Domain(self.points)
+        domain.set_quantity('stage',4.0)
+        domain.set_quantity('elevation',slope_one)
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+        domain.distribute_to_vertices_and_edges()
+        domain.update_boundary()
+
+        gravity(domain)
+        
+        #print domain.quantities['stage'].vertex_values 
+        #print domain.quantities['elevation'].vertex_values 
+        #print domain.quantities['xmomentum'].explicit_update       
+
+        assert allclose( [-34.3, -24.5, -14.7], domain.quantities['xmomentum'].explicit_update )
+
+
+    def test_evolve_first_order(self):
+        """
+        Compare still lake solution for various versions of shallow_water_domain
+        """
+        
+        def slope_square(x):
+            return maximum(4.0-(x-5.0)*(x-5.0), 0.0)
+
+        domain = Domain(self.points2)
+        domain.set_quantity('stage',10.0)
+        domain.set_quantity('elevation',slope_square)
+        domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+        domain.default_order = 1
+        domain.set_timestepping_method('euler')
+        
+        yieldstep=0.25
+        finaltime=1.0
+
+        for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+            pass
+        
+        ##	print domain.quantities['stage'].vertex_values 
+        ##	print domain.quantities['elevation'].vertex_values 
+        ##        print domain.quantities['xmomentum'].vertex_values
+        ##  
+        ##
+        ##        print domain.quantities['stage'].centroid_values  
+        ##	print domain.quantities['elevation'].centroid_values    
+        ##        print domain.quantities['xmomentum'].centroid_values    
+
+        #assert allclose( 10.0*ones(10), domain.quantities['stage'].centroid_values )
+        #assert allclose( zeros(10), domain.quantities['xmomentum'].centroid_values )
+
+
+##     def test_evolve_euler_second_order_space(self):
+##         """
+##         Compare still lake solution for various versions of shallow_water_domain
+##         """
+
+##         def slope_square(x):
+##             return maximum(4.0-(x-5.0)*(x-5.0), 0.0)
+
+##         domain = Domain(self.points2)
+##         domain.set_quantity('stage',10.0)
+##         domain.set_quantity('elevation',slope_square)
+##         domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+##         domain.default_order = 2
+##         domain.set_timestepping_method('rk2')
+##         yieldstep=1.0
+##         finaltime=1.0
+
+##         for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+##             pass
+        
+##         assert allclose( 10.0*ones(10), domain.quantities['stage'].centroid_values )
+##         assert allclose( zeros(10), domain.quantities['xmomentum'].centroid_values )
+
+##     def test_evolve_second_order_space_time(self):
+##         """
+##         Compare still lake solution for various versions of shallow_water_domain
+##         """
+
+##         def slope_square(x):
+##             return maximum(4.0-(x-5.0)*(x-5.0), 0.0)
+
+##         domain = Domain(self.points2)
+##         domain.set_quantity('stage',10.0)
+##         domain.set_quantity('elevation',slope_square)
+##         domain.set_boundary({'exterior' : Reflective_boundary(domain)})
+
+##         domain.default_order = 2
+##         domain.set_timestepping_method('rk3')
+
+##         yieldstep=1.0
+##         finaltime=1.0
+
+##         for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
+##             pass
+        
+##         assert allclose( 10.0*ones(10), domain.quantities['stage'].centroid_values )
+##         assert allclose( zeros(10), domain.quantities['xmomentum'].centroid_values )
+
+
+
+#==============================================================================
+
+def local_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
+
+    tmp0 = zeros(N,Float)
+    tmp1 = zeros(N,Float)
+
+    #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]
+                #print i, ' ' , m
+                #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
+            
+
+            edgeflux, max_speed = local_flux_function(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]
+        tmp0[k] = flux[0]
+        tmp1[k] = flux[1]
+
+
+    return tmp0, tmp1
+
+
+def local_flux_function(normal, ql, qr, zl, zr):
+    """Compute fluxes between volumes for the shallow water wave equation
+    cast in terms of w = h+z using the 'central scheme' as described in
+
+    Kurganov, Noelle, Petrova. 'Semidiscrete Central-Upwind Schemes For
+    Hyperbolic Conservation Laws and Hamilton-Jacobi Equations'.
+    Siam J. Sci. Comput. Vol. 23, No. 3, pp. 707-740.
+
+    The implemented formula is given in equation (3.15) on page 714
+
+    Conserved quantities w, uh, are stored as elements 0 and 1
+    in the numerical vectors ql an qr.
+
+    Bed elevations zl and zr.
+    """
+
+    from config import g, epsilon, h0
+    from math import sqrt
+    from Numeric import array
+
+    #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 +  h0/h_left)
+
+
+    uh_left = u_left*h_left
+
+    w_right  = q_right[0]  #w=h+z
+    h_right  = w_right-z
+    uh_right = q_right[1]
+
+
+    if h_right < epsilon:
+        u_right = 0.0  #Could have been negative
+        h_right = 0.0
+    else:
+        u_right  = uh_right/(h_right + h0/h_right)
+
+    uh_right = u_right*h_right
+    
+    #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
+
+
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Shallow_Water, 'test')    
+    #suite = unittest.makeSuite(Test_Quantity, 'test_set_values_from_file_using_polygon')
+
+    #suite = unittest.makeSuite(Test_Quantity, 'test_set_vertex_values_using_general_interface_with_subset')
+    #print "restricted test"
+    #suite = unittest.makeSuite(Test_Quantity,'verbose_test_set_values_from_UTM_pts')
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/test_all.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/test_all.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/test_all.py	(revision 7884)
@@ -0,0 +1,219 @@
+"""Regression testing framework
+This module will search for scripts in the same directory named
+test_*.py.  Each such script should be a test suite that tests a
+module through PyUnit. This script will aggregate all
+found test suites into one big test suite and run them all at once.
+"""
+
+# Author: Mark Pilgrim
+# Modified by Ole Nielsen
+
+import unittest
+import os
+import sys
+import tempfile
+import time
+import anuga.utilities.system_tools as aust
+from anuga.utilities.terminal_width import terminal_width
+
+
+#List files that should be excluded from the testing process.
+#E.g. if they are known to fail and under development
+exclude_files = []
+
+# Directories that should not be searched for test files.
+exclude_dirs = ['channel',  '.svn'] 
+                
+
+
+##
+# @brief List a string sequence on the screen in columns.
+# @param names Sequence of strings to list.
+# @param func Function to apply to each string in sequence.
+# @param col_width Force columns to this width (default calculated).
+# @param page_width Set displayable page width to this (default 132).
+def list_names(names, func=None, col_width=None, page_width=None):
+    # set defaults
+    p_width = page_width - 1            # set page width
+    if p_width is None:
+        p_width = 132                   # default page width
+
+    c_width = col_width                 # set column width
+    if c_width is None:
+        c_width = 0
+        for name in names:
+            if func:
+                name = func(name)
+            c_width = max(c_width, len(name))
+    c_width += 2                        # 2 column padding
+
+    # calculate number of columns allowed
+    max_columns = int(p_width / c_width)
+
+    # print columns
+    column = 0
+    for name in names:
+        if func:
+            name = func(name)
+        print '%-*s' % (c_width-1, name),
+        column += 1
+        if column >= max_columns:
+            column = 0
+            print
+
+    # if last line not finished, end it here
+    if column > 0:
+        print
+
+
+##
+# @brief Get 'test_*.py' files and paths to directories.
+# @param path Path to directory to start walk in.
+# @return A tuple (<files>, <dirs>).
+# @note Don't include any files in and below forbidden directories.
+def get_test_files(path):
+    walk = os.walk(path)
+
+    test_files = []
+    path_files = []
+
+    for (dirpath, dirnames, filenames) in walk:
+        # exclude forbidden directories
+        for e_dir in exclude_dirs:
+            try:
+                dirnames.remove(e_dir)
+            except ValueError:
+                pass
+
+        # check for test_*.py files
+        for filename in filenames:
+            if filename.startswith('test_') and filename.endswith('.py'):
+                test_files.append(filename)
+                if dirpath not in path_files:
+                    path_files.append(dirpath)
+
+    return test_files, path_files
+
+
+def regressionTest(test_verbose=False):
+    # start off with where we are
+    path = os.getcwd()
+    print
+    print 'Testing path: %s' % path
+
+    # get the terminal width
+    term_width = terminal_width()
+
+    # explain what we are doing
+    print
+    print "The following directories will be skipped over:"
+    exclude_dirs.sort()
+    list_names(exclude_dirs, page_width=term_width)
+
+    # get all test_*.py and enclosing directories
+    test_files, path_files = get_test_files(path)
+    path_files.sort()
+
+    files = [x for x in test_files if not x == 'test_all.py']
+    files.sort()        # Ensure same order on all platforms
+
+    print
+    print 'Paths searched:'
+    list_names(path_files, os.path.basename, page_width=term_width)
+
+    print    
+    print 'Files tested:'
+    list_names(files, page_width=term_width)
+    print
+
+    # update system path with found paths
+    for path in path_files:
+        sys.path.append(path)
+   
+    # exclude files that we can't handle 
+    for file in exclude_files:
+        print 'WARNING: File '+ file + ' to be excluded from testing'
+        try:
+            files.remove(file)
+        except ValueError, e:
+            msg = 'File "%s" was not found in test suite.\n' % file
+            msg += 'Original error is "%s"\n' % e
+            msg += 'Perhaps it should be removed from exclude list?'
+            raise Exception, msg
+
+    # import all test_*.py files
+    # NOTE: This implies that test_*.py files MUST HAVE UNIQUE NAMES!
+    filenameToModuleName = lambda f: os.path.splitext(f)[0]
+    moduleNames = map(filenameToModuleName, files)
+    modules = map(__import__, moduleNames)
+
+    # Fix up the system path
+    for file in path_files:
+        sys.path.remove(file)
+
+    # bundle up all the tests
+    load = unittest.defaultTestLoader.loadTestsFromModule
+    testCaseClasses = map(load, modules)
+
+    if test_verbose is True:
+        # Test the code by setting verbose to True.
+        # The test cases have to be set up for this to work.
+        # See test data manager for an example.
+        for test_suite in testCaseClasses:
+            for tests in test_suite._tests:
+                # tests is of class TestSuite
+                if len(tests._tests) > 1:
+                    # these are the test functions
+                    try:
+                        # Calls class method set_verbose in test case classes
+                        tests._tests[0].set_verbose()
+                    except:
+                        pass                # No all classes have set_verbose
+
+    return unittest.TestSuite(testCaseClasses)
+
+
+##
+# @brief Check that the environment is sane.
+# @note Stops here if there is an error.
+def check_anuga_1d_import():
+    try:
+        # importing something that loads quickly
+        import anuga_1d.config
+    except ImportError:
+        print "Python cannot import ANUGA_1D module."
+        print "Check you have followed all steps of its installation."
+        import sys
+        sys.exit()
+
+
+if __name__ == '__main__':
+    check_anuga_1d_import()
+
+    if len(sys.argv) > 1 and sys.argv[1][0].upper() == 'V':
+        test_verbose = True
+        saveout = sys.stdout
+        filename = ".temp"
+        fid = open(filename, 'w')
+        sys.stdout = fid
+    else:
+        test_verbose = False
+    suite = regressionTest(test_verbose)
+    runner = unittest.TextTestRunner() #verbosity=2
+    runner.run(suite)
+
+    # timestamp at the end
+    timestamp = time.asctime()
+    version = aust.get_revision_number()
+    print
+    print 'Finished at %s, version %s' % (timestamp, version)
+
+    # Cleaning up
+    if len(sys.argv) > 1 and sys.argv[1][0].upper() == 'V':
+        sys.stdout = saveout
+        #fid.close() # This was causing an error in windows
+        #os.remove(filename)
+
+    
+    if sys.platform == 'win32':
+        raw_input('Press the RETURN key')
Index: trunk/anuga_work/development/2010-projects/anuga_1d/utilities/__init__.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/utilities/__init__.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/utilities/__init__.py	(revision 7884)
@@ -0,0 +1,9 @@
+#! /usr/bin/python
+
+# To change this template, choose Tools | Templates
+# and open the template in the editor.
+
+__author__="Stephen Roberts"
+__date__ ="$14/06/2010 7:50:20 PM$"
+
+pass
Index: trunk/anuga_work/development/2010-projects/anuga_1d/utilities/compile.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/utilities/compile.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/utilities/compile.py	(revision 7884)
@@ -0,0 +1,452 @@
+"""compile.py - compile Python C-extension
+
+   Commandline usage: 
+     python compile.py <filename>
+
+   Usage from within Python:
+     import compile
+     compile.compile(<filename>,..)
+
+   Ole Nielsen, Duncan Gray Oct 2001      
+"""     
+
+#NumPy ------------------------------------
+# Something like these lines recommended in "Converting from NUMARRAY to NUMPY"
+import numpy
+I_dirs = '-I"%s" ' % numpy.get_include()
+#NumPy ------------------------------------
+
+# FIXME (Ole): Although this script says it works with a range of compilers,
+# it has only really been used with gcc.
+
+import os, string, sys, types
+
+separation_line = '---------------------------------------'      
+ 
+def compile(FNs=None, CC=None, LD = None, SFLAG = None, verbose = 1):
+  """compile(FNs=None, CC=None, LD = None, SFLAG = None):
+  
+     Compile FN(s) using compiler CC (e.g. mpicc), 
+     Loader LD and shared flag SFLAG.
+     If CC is absent use default compiler dependent on platform
+     if LD is absent CC is used.
+     if SFLAG is absent platform default is used
+     FNs can be either one filename or a list of filenames
+     In the latter case, the first will be used to name so file.
+  """
+  
+  # Input check
+  #
+  assert not FNs is None, 'No filename provided'
+
+  if not type(FNs) == types.ListType:
+    FNs = [FNs]
+
+
+  libext = 'so' #Default extension (Unix)
+  libs = ''
+  version = sys.version[:3]
+  
+  # Determine platform and compiler
+  #
+  if sys.platform == 'sunos5':  #Solaris
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'G'
+      
+  elif sys.platform == 'osf1V5':  #Compaq AlphaServer
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'    
+      
+  elif sys.platform == 'linux2':  #Linux
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'    
+      
+  elif sys.platform == 'darwin':  #Mac OS X:
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'bundle -flat_namespace -undefined suppress'
+
+  elif sys.platform == 'cygwin':  #Cygwin (compilation same as linux)
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc'
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'
+    libext = 'dll'
+    libs = '/lib/python%s/config/libpython%s.dll.a' %(version,version)
+      
+  elif sys.platform == 'win32':  #Windows
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'gcc.exe' #Some systems require this (a security measure?) 
+    if LD:
+      loader = LD
+    else:  
+      loader = compiler
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'shared'
+     
+    # As of python2.5, .pyd is the extension for python extension
+    # modules.
+    if sys.version_info[0:2] >= (2, 5):
+      libext = 'pyd'
+    else:
+      libext = 'dll'
+
+    libs, is_found = set_python_dll_path()
+      
+  else:
+    if verbose: print "Unrecognised platform %s - revert to default"\
+                %sys.platform
+    
+    if CC:
+      compiler = CC
+    else:  
+      compiler = 'cc'
+    if LD:
+      loader = LD
+    else:  
+      loader = 'ld'
+    if SFLAG:
+      sharedflag = SFLAG
+    else:  
+      sharedflag = 'G'
+
+
+  # Verify that compiler can be executed
+  print 'Compiler: %s, version ' %compiler,
+  sys.stdout.flush()
+  s = '%s -dumpversion' %(compiler)
+  err = os.system(s)
+  print
+  
+  if err != 0:
+      msg = 'Unable to execute compiler: %s. ' %compiler
+      msg += 'Make sure it is available on the system path.\n'
+      msg += 'One way to check this is to run %s on ' %compiler
+      msg += 'the commandline.'
+      raise Exception, msg    
+
+  
+  # Find location of include files
+  #
+  if sys.platform == 'win32':  #Windows
+    python_include = os.path.join(sys.exec_prefix, 'include')    
+  else:  
+    python_include = os.path.join(os.path.join(sys.exec_prefix, 'include'),
+                                  'python' + version)
+
+  # Check existence of Python.h
+  #
+  headerfile = python_include + os.sep + 'Python.h'
+  try:
+    open(headerfile, 'r')
+  except:
+    raise """Did not find Python header file %s.
+    Make sure files for Python C-extensions are installed. 
+    In debian linux, for example, you need to install a
+    package called something like python2.3-dev""" %headerfile
+
+
+
+  # Add Python path + utilities to includelist (see ticket:31)
+  # Assume there is only one 'utilities' dir under path dirs
+  
+  utilities_include_dir = None
+  for pathdir in sys.path:
+
+    utilities_include_dir = pathdir + os.sep + 'utilities'
+    #print pathdir
+    #print utilities_include_dir
+    try:
+      os.stat(utilities_include_dir)
+    except OSError:
+      pass
+    else:
+      #print 'Found %s to be used as include dir' %utilities_include_dir
+      break
+
+  # This is hacky since it
+  # assumes the location of the compile_all that determines buildroot
+  try:
+    utilities_include_dir = buildroot + os.sep + "source" + os.sep + "anuga" \
+                            + os.sep + 'utilities'
+  except:
+    # This will make compile work locally
+    utilities_include_dir = '.'
+    utilities_include_dir = '../utilities'
+
+
+    
+  try:
+    os.stat(utilities_include_dir)
+  except OSError: 
+    utilities_include_dir = buildroot + os.sep + 'utilities'
+  
+  
+  
+  # Check filename(s)
+  #
+  object_files = ''
+  for FN in FNs:        
+    root, ext = os.path.splitext(FN)
+    if ext == '':
+      FN = FN + '.c'
+    elif ext.lower() != '.c':
+      raise Exception, "Unrecognised extension: " + FN
+    
+    try:
+      open(FN, 'r')
+    except:
+      raise Exception, "Could not open: " + FN
+
+    if not object_files: root1 = root  #Remember first filename        
+    object_files += root + '.o '  
+  
+  
+    # Compile
+    #
+    if utilities_include_dir is None:    
+      s = '%s -c %s -I"%s" -o "%s.o" -Wall -O3'\
+          %(compiler, FN, python_include, root)
+    else:
+      if FN == "triangle.c" or FN == "mesh_engine_c_layer.c":
+        s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -O3 -DTRILIBRARY=1 -DNO_TIMER=1'\
+            % (compiler, FN, I_dirs, python_include, utilities_include_dir, root)
+      elif FN == "polygon_ext.c":
+        # gcc 4.3.x is problematic with this file if '-O3' is used
+        s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -Wall'\
+            %(compiler, FN, I_dirs, python_include, utilities_include_dir, root)
+      else:
+        s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -Wall -O3'\
+            %(compiler, FN, I_dirs, python_include, utilities_include_dir, root)
+
+    if os.name == 'posix' and os.uname()[4] in ['x86_64', 'ia64']:
+      # Extra flags for 64 bit architectures.
+      #   AMD Opteron will give x86_64
+      #   Itanium will give ia64
+      #
+      # Second clause will always fail on Win32 because uname is UNIX specific
+      # but won't get past first clause
+
+      s += ' -fPIC' # Use position independent code for 64 bit archs
+      #s += ' -m64' # Used to be necessary for AMD Opteron
+      
+      
+    if verbose:
+      print s
+
+    # Doesn't work on Windows anyway  
+    #else:
+    #  s = s + ' 2> /dev/null' #Suppress errors
+    
+    try:
+      err = os.system(s)
+      if err != 0:
+          raise 'Attempting to compile %s failed - please try manually' %FN 
+    except:
+      raise 'Could not compile %s - please try manually' %FN  
+
+  
+  # Make shared library (*.so or *.dll)
+  if libs is "":
+    s = '%s -%s %s -o %s.%s -lm' %(loader, sharedflag, object_files, root1, libext)
+  else:
+    s = '%s -%s %s -o %s.%s "%s" -lm' %(loader, sharedflag, object_files, root1, libext, libs)
+    
+  if verbose:
+    print s
+
+  # Doesn't work on Windows anyway      
+  #else:
+  #  s = s + ' 2> /dev/null' #Suppress warnings
+  
+  try:  
+    err=os.system(s)
+    if err != 0:        
+        raise 'Attempting to link %s failed - please try manually' %root1     
+  except:
+    raise 'Could not link %s - please try manually' %root1
+    
+
+def can_use_C_extension(filename):
+    """Determine whether specified C-extension
+    can and should be used.
+    """
+
+    from anuga.config import use_extensions
+
+    from os.path import splitext
+
+    root, ext = splitext(filename)
+    
+    C=False
+    if use_extensions:
+        try:
+            s = 'import %s' %root
+            #print s
+            exec(s)
+        except:
+            try:
+                open(filename)
+            except:
+                msg = 'C extension %s cannot be opened' %filename
+                print msg                
+            else:    
+                print '------- Trying to compile c-extension %s' %filename
+            
+                try:
+                    compile(filename)
+                except:
+                    print 'WARNING: Could not compile C-extension %s'\
+                          %filename
+                else:
+                    try:
+                        exec('import %s' %root)
+                    except:
+                        msg = 'C extension %s seems to compile OK, '
+                        msg += 'but it can still not be imported.'
+                        raise msg
+                    else:
+                        C=True
+        else:
+            C=True
+            
+    if not C:
+        pass
+        print 'NOTICE: C-extension %s not used' %filename
+
+    return C
+
+
+def set_python_dll_path():
+  """ On windows, find which of the two usual hiding places the python
+  dll is located.
+
+  If the file can't be found, return None.
+  """
+  import sys
+  from os import access, F_OK
+  
+  version = sys.version[:3]
+  v = version.replace('.','')
+  dllfilename = 'python%s.dll' %(v)
+  libs = os.path.join(sys.exec_prefix,dllfilename)
+
+  is_found = True   
+  if access(libs,F_OK) == 0 :
+    # Sometimes python dll is hidden in %WINDIR%/system32
+    libs = os.path.join(os.environ.get('WINDIR', 'C:\WINNT'), 'system32',
+                        dllfilename)
+    if access(libs,F_OK) == 0 :
+      # could not find the dll
+      libs = os.path.join(sys.exec_prefix,dllfilename)
+      is_found = False
+  return libs, is_found
+
+def check_python_dll():
+  libs, is_found = set_python_dll_path()
+  if not is_found:
+    print "%s not found.\nPlease install.\nIt is available on the web." \
+              %(libs)
+    import sys; sys.exit()
+    
+      
+if __name__ == '__main__':
+  from os.path import splitext
+  
+  if sys.platform == 'win32':
+    check_python_dll()
+  if len(sys.argv) > 1:
+      files = sys.argv[1:]
+      for filename in files:
+          root, ext = splitext(filename)
+
+          if ext <> '.c':
+              print 'WARNING (compile.py): Skipping %s. I only compile C-files.' %filename
+      
+  else:  
+      #path = os.path.split(sys.argv[0])[0] or os.getcwd()
+      path = '.'
+      files = os.listdir(path)
+      
+      
+
+  for filename in files:
+      root, ext = splitext(filename)
+
+      if ext == '.c':
+          for x in ['.dll', '.so']:
+              try:
+                  os.remove(root + x)
+              except:
+                  pass
+
+          print separation_line
+          print 'Trying to compile c-extension %s in %s'\
+                %(filename, os.getcwd())
+          try:
+            if filename == 'triang.c': 
+              compile(['triang.c','triangle.c'])
+            elif  filename == 'mesh_engine_c_layer.c': 
+              compile(['mesh_engine_c_layer.c','triangle.c'])
+            else:
+              compile(filename)
+          except Exception, e:
+              msg = 'Could not compile C extension %s\n' %filename
+              msg += str(e)
+              raise Exception, msg
+          else:
+              print 'C extension %s OK' %filename
+          print    
+        
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/utilities/test_all.py
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/utilities/test_all.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/utilities/test_all.py	(revision 7884)
@@ -0,0 +1,83 @@
+"""Regression testing framework
+This module will search for scripts in the same directory named
+test_*.py.  Each such script should be a test suite that tests a
+module through PyUnit. This script will aggregate all
+found test suites into one big test suite and run them all at once.
+"""
+
+# Author: Mark Pilgrim
+# Modified by Ole Nielsen
+
+import unittest
+import os
+
+
+#List files that should be excluded from the testing process.
+#E.g. if they are known to fail and under development
+exclude = [] 
+
+
+def get_test_files(path):
+
+    import sys
+
+    files = os.listdir(path)
+
+    #Check sub directories
+    test_files = []
+    for file in files:
+        if os.path.isdir(file):
+            sys.path.append(file)
+            #print 'Recursing into', file
+            test_files += get_test_files(path + os.sep + file)
+        elif file[:5] == 'test_' and file[-2:] == 'py':
+            #print 'Appending', file
+            test_files.append(file)
+        else:
+            pass
+    return test_files
+
+
+
+def regressionTest():
+    import sys, os, re, unittest
+    path = os.path.split(sys.argv[0])[0] or os.getcwd()
+
+
+    files = get_test_files(path)
+
+
+
+    #test = re.compile('^test_[\w]*.py$', re.IGNORECASE)
+    #files = filter(test.search, files)
+
+
+    try:
+        files.remove(__file__)  #Remove self from list (Ver 2.3. or later)
+    except:
+        files.remove('test_all.py')
+
+    print 'Testing:'
+    for file in files:
+        print '  ' + file
+
+    if globals().has_key('exclude'):
+        for file in exclude:
+            files.remove(file)
+            print 'WARNING: File '+ file + ' excluded from testing'
+
+
+    filenameToModuleName = lambda f: os.path.splitext(f)[0]
+    #print "files",files 
+    moduleNames = map(filenameToModuleName, files)
+    #print "moduleNames",moduleNames
+    modules = map(__import__, moduleNames)
+    load = unittest.defaultTestLoader.loadTestsFromModule
+    return unittest.TestSuite(map(load, modules))
+
+################################################################################
+
+if __name__ == '__main__':   
+    suite = regressionTest()
+    runner = unittest.TextTestRunner() #verbosity=2)
+    runner.run(suite)
Index: trunk/anuga_work/development/2010-projects/anuga_1d/utilities/util_ext.c
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/utilities/util_ext.c	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/utilities/util_ext.c	(revision 7884)
@@ -0,0 +1,108 @@
+// Python - C extension for finite_volumes util module.
+//
+// To compile (Python2.3):
+//  gcc -c util_ext.c -I/usr/include/python2.3 -o util_ext.o -Wall -O
+//  gcc -shared util_ext.o  -o util_ext.so
+//
+// See the module util.py
+//
+//
+// Ole Nielsen, GA 2004
+//
+//NOTE: On 64 bit systems use long* instead of int* for numeric arrays
+//this will also work on 32 bit systems
+
+#include <float.h>
+
+#include "Python.h"
+#include "numpy/arrayobject.h"
+#include "math.h"
+
+//Shared snippets
+#include "util_ext.h"
+
+
+
+
+PyObject *gradient(PyObject *self, PyObject *args) {
+  //
+  // a,b = gradient(x0, y0, x1, y1, x2, y2, q0, q1, q2)
+  //
+
+  double x0, y0, x1, y1, x2, y2, q0, q1, q2, a, b;
+  PyObject *result;
+
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "ddddddddd", &x0, &y0, &x1, &y1, &x2, &y2,
+			&q0, &q1, &q2)) {
+    
+    PyErr_SetString(PyExc_RuntimeError, 
+		    "gradient could not parse input");    
+    return NULL;
+  }
+
+
+  // Call underlying routine
+  _gradient(x0, y0, x1, y1, x2, y2,
+	    q0, q1, q2, &a, &b);
+
+  // Return values a and b
+  result = Py_BuildValue("dd", a, b);
+  return result;
+}
+
+PyObject *gradient2(PyObject *self, PyObject *args) {
+  //
+  // a,b = gradient2(x0, y0, x1, y1, q0, q1)
+  //
+
+  double x0, y0, x1, y1, q0, q1, a, b;
+  PyObject *result;
+
+  // Convert Python arguments to C
+  if (!PyArg_ParseTuple(args, "dddddd", &x0, &y0, &x1, &y1, &q0, &q1)) {
+    PyErr_SetString(PyExc_RuntimeError, 
+		    "gradient2 could not parse input");      
+    return NULL;
+  }
+
+
+  // Call underlying routine
+  _gradient2(x0, y0, x1, y1, q0, q1, &a, &b);
+
+  // Return values a and b
+  result = Py_BuildValue("dd", a, b);
+  return result;
+}
+
+PyObject * double_precision(PyObject * self, PyObject * args){
+  // Get the precision of the double datatype on this system.
+  return Py_BuildValue("i", DBL_DIG);
+}
+
+// Method table for python module
+static struct PyMethodDef MethodTable[] = {
+  /* The cast of the function is necessary since PyCFunction values
+   * only take two PyObject* parameters, and rotate() takes
+   * three.
+   */
+
+  //{"rotate", (PyCFunction)rotate, METH_VARARGS | METH_KEYWORDS, "Print out"},
+  {"gradient", gradient, METH_VARARGS, "Print out"},
+  {"gradient2", gradient2, METH_VARARGS, "Print out"},  
+  {"double_precision", double_precision, METH_VARARGS, "Precision of this machine\'s \'double\' type"},
+  {NULL, NULL, 0, NULL}   /* sentinel */
+};
+
+
+
+// Module initialisation
+void initutil_ext(void){
+  Py_InitModule("util_ext", MethodTable);
+
+  import_array();     //Necessary for handling of NumPY structures
+}
+
+
+
+
Index: trunk/anuga_work/development/2010-projects/anuga_1d/utilities/util_ext.h
===================================================================
--- trunk/anuga_work/development/2010-projects/anuga_1d/utilities/util_ext.h	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/anuga_1d/utilities/util_ext.h	(revision 7884)
@@ -0,0 +1,376 @@
+// Python - C extension for finite_volumes util module.
+//
+// To compile (Python2.3):
+//  gcc -c util_ext.c -I/usr/include/python2.3 -o util_ext.o -Wall -O 
+//  gcc -shared util_ext.o  -o util_ext.so	
+//
+// See the module util.py
+//
+//
+// Ole Nielsen, GA 2004
+	
+#include "Python.h"	
+#include "numpy/arrayobject.h"
+#include "math.h"
+
+
+double max(double x, double y) {  
+  //Return maximum of two doubles
+  
+  if (x > y) return x;
+  else return y;
+}
+
+
+double min(double x, double y) {  
+  //Return minimum of two doubles
+  
+  if (x < y) return x;
+  else return y;
+}
+
+
+double sign(double x) {
+  //Return sign of a double
+
+  if (x>0.0) return 1.0;
+  else if (x<0.0) return -1.0;
+  else return 0.0;
+}
+
+
+int _gradient(double x0, double y0, 
+	      double x1, double y1, 
+	      double x2, double y2, 
+	      double q0, double q1, double q2, 
+	      double *a, double *b) {
+	      
+  /*Compute gradient (a,b) based on three points (x0,y0), (x1,y1) and (x2,y2) 
+  with values q0, q1 and q2.
+  
+  Extrapolation formula (q0 is selected as an arbitrary origin)
+    q(x,y) = q0 + a*(x-x0) + b*(y-y0)                    (1)
+  
+  Substituting the known values for q1 and q2 into (1) yield the 
+  equations for a and b 
+  
+      q1-q0 = a*(x1-x0) + b*(y1-y0)                      (2)
+      q2-q0 = a*(x2-x0) + b*(y2-y0)                      (3)      
+      
+  or in matrix form
+  
+  /               \  /   \   /       \  
+  |  x1-x0  y1-y0 |  | a |   | q1-q0 |
+  |               |  |   | = |       | 
+  |  x2-x0  y2-y0 |  | b |   | q2-q0 |
+  \               /  \   /   \       /
+   
+  which is solved using the standard determinant technique    
+      
+  */
+	      
+
+  double det;
+  
+  det = (y2-y0)*(x1-x0) - (y1-y0)*(x2-x0);
+
+  *a = (y2-y0)*(q1-q0) - (y1-y0)*(q2-q0);
+  *a /= det;
+
+  *b = (x1-x0)*(q2-q0) - (x2-x0)*(q1-q0);
+  *b /= det;
+
+  return 0;
+}
+
+
+int _gradient2(double x0, double y0, 
+	       double x1, double y1, 
+	       double q0, double q1, 
+	       double *a, double *b) {
+  /*Compute gradient (a,b) between two points (x0,y0) and (x1,y1) 
+  with values q0 and q1 such that the plane is constant in the direction 
+  orthogonal to (x1-x0, y1-y0).
+  
+  Extrapolation formula
+    q(x,y) = q0 + a*(x-x0) + b*(y-y0)                    (1)
+  
+  Substituting the known values for q1 into (1) yields an 
+  under determined  equation for a and b 
+      q1-q0 = a*(x1-x0) + b*(y1-y0)                      (2)
+      
+      
+  Now add the additional requirement that the gradient in the direction 
+  orthogonal to (x1-x0, y1-y0) should be zero. The orthogonal direction 
+  is given by the vector (y0-y1, x1-x0).
+  
+  Define the point (x2, y2) = (x0 + y0-y1, y0 + x1-x0) on the orthognal line. 
+  Then we know that the corresponding value q2 should be equal to q0 in order 
+  to obtain the zero gradient, hence applying (1) again    
+      q0 = q2 = q(x2, y2) = q0 + a*(x2-x0) + b*(y2-y0)
+                          = q0 + a*(x0 + y0-y1-x0) + b*(y0 + x1-x0 - y0)
+			  = q0 + a*(y0-y1) + b*(x1-x0)
+			  
+  leads to the orthogonality constraint
+     a*(y0-y1) + b*(x1-x0) = 0                           (3) 
+     
+  which closes the system and yields
+  
+  /               \  /   \   /       \  
+  |  x1-x0  y1-y0 |  | a |   | q1-q0 |
+  |               |  |   | = |       | 
+  |  y0-y1  x1-x0 |  | b |   |   0   |
+  \               /  \   /   \       /
+   
+  which is solved using the standard determinant technique    
+      
+  */
+
+  double det, xx, yy, qq;
+  
+  xx = x1-x0;
+  yy = y1-y0;
+  qq = q1-q0;
+    
+  det = xx*xx + yy*yy;  //FIXME  catch det == 0
+  *a = xx*qq/det;
+  *b = yy*qq/det;
+        
+  return 0;
+}
+
+
+void _limit_old(int N, double beta, double* qc, double* qv, 
+	    double* qmin, double* qmax) { 
+
+  //N are the number of elements
+  int k, i, k3;
+  double dq, dqa[3], phi, r;
+  
+  //printf("INSIDE\n");
+  for (k=0; k<N; k++) {
+    k3 = k*3;
+    
+    //Find the gradient limiter (phi) across vertices  
+    phi = 1.0;
+    for (i=0; i<3; i++) {    
+      r = 1.0;
+      
+      dq = qv[k3+i] - qc[k];    //Delta between vertex and centroid values
+      dqa[i] = dq;              //Save dq for use in the next loop
+      
+      if (dq > 0.0) r = (qmax[k] - qc[k])/dq;
+      if (dq < 0.0) r = (qmin[k] - qc[k])/dq;      
+  
+  
+      phi = min( min(r*beta, 1.0), phi);    
+    }
+    
+    //Then update using phi limiter
+    for (i=0; i<3; i++) {    
+      qv[k3+i] = qc[k] + phi*dqa[i];
+    }
+  }
+}
+
+
+void  print_double_array(char* name, double* array, int n, int m){
+
+    int k,i,km;
+
+    printf("%s = [",name);
+    for (k=0; k<n; k++){
+	km = m*k;
+	printf("[");
+	for (i=0; i<m ; i++){
+	    printf("%g ",array[km+i]);
+	}
+	if (k==(n-1))
+	    printf("]");
+	else
+	    printf("]\n");
+    }
+    printf("]\n");
+}
+
+void  print_int_array(char* name, int* array, int n, int m){
+
+    int k,i,km;
+
+    printf("%s = [",name);
+    for (k=0; k<n; k++){
+	km = m*k;
+	printf("[");
+	for (i=0; i<m ; i++){
+	    printf("%i ",array[km+i]);
+	}
+	if (k==(n-1))
+	    printf("]");
+	else
+	    printf("]\n");
+    }
+    printf("]\n");
+}
+
+
+void  print_long_array(char* name, long* array, int n, int m){
+
+    int k,i,km;
+
+    printf("%s = [",name);
+    for (k=0; k<n; k++){
+	km = m*k;
+	printf("[");
+	for (i=0; i<m ; i++){
+	  printf("%i ",(int) array[km+i]);
+	}
+	if (k==(n-1))
+	    printf("]");
+	else
+	    printf("]\n");
+    }
+    printf("]\n");
+}
+
+void print_numeric_array(PyArrayObject *x) {  
+  int i, j;
+  for (i=0; i<x->dimensions[0]; i++) {  
+    for (j=0; j<x->dimensions[1]; j++) {
+      printf("%f ", *(double*) (x->data + i*x->strides[0] + j*x->strides[1]));
+    }
+    printf("\n");  
+  }
+  printf("\n");    
+}
+
+void print_numeric_vector(PyArrayObject *x) {  
+  int i;
+  for (i=0; i<x->dimensions[0]; i++) {
+    printf("%f ", *(double*) (x->data + i*x->strides[0]));  
+  }
+  printf("\n");  
+}
+
+PyArrayObject *get_consecutive_array(PyObject *O, char *name) {
+  PyArrayObject *A, *B;
+  
+
+  //Get array object from attribute
+  
+  /*
+  //FIXME: THE TEST DOESN't WORK
+  printf("Err = %d\n", PyObject_HasAttrString(O, name));
+  if (PyObject_HasAttrString(O, name) == 1) {
+    B = (PyArrayObject*) PyObject_GetAttrString(O, name);
+    if (!B) return NULL;
+  } else {
+    return NULL;
+    } 
+  */
+    
+  B = (PyArrayObject*) PyObject_GetAttrString(O, name);
+
+  //printf("B = %p\n",(void*)B);
+  if (!B) {
+    printf("util_ext.h: get_consecutive_array could not obtain python object");
+    printf(" %s\n",name);
+    fflush(stdout);
+    PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_consecutive_array could not obtain python object");
+    return NULL;
+  }     
+  
+  //Convert to consecutive array
+  A = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*) B, 
+						    B -> descr -> type, 0, 0);
+  
+  Py_DECREF(B); //FIXME: Is this really needed??
+  
+  if (!A) {
+    printf("util_ext.h: get_consecutive_array could not obtain array object");
+    printf(" %s \n",name);
+    fflush(stdout);
+    PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_consecutive_array could not obtain array");
+    return NULL;
+  }
+
+
+  return A;
+}
+
+double get_python_double(PyObject *O, char *name) {
+  PyObject *TObject;
+  #define BUFFER_SIZE 80
+  char buf[BUFFER_SIZE];
+  double tmp;
+  int n;
+  
+
+  //Get double from attribute
+  TObject = PyObject_GetAttrString(O, name);
+  if (!TObject) {
+	n =  snprintf(buf, BUFFER_SIZE, "util_ext.h: get_python_double could not obtain double %s.\n", name);
+	//printf("name = %s",name);
+    PyErr_SetString(PyExc_RuntimeError, buf);
+
+    return 0.0;
+  }  
+  
+  tmp = PyFloat_AsDouble(TObject);
+  
+  Py_DECREF(TObject);
+  
+  return tmp;
+}
+
+
+
+
+int get_python_integer(PyObject *O, char *name) {
+  PyObject *TObject;
+  #define BUFFER_SIZE 80
+  char buf[BUFFER_SIZE];
+  long tmp;
+  int n;
+  
+
+  //Get double from attribute
+  TObject = PyObject_GetAttrString(O, name);
+  if (!TObject) {
+  	n =  snprintf(buf, BUFFER_SIZE, "util_ext.h: get_python_integer could not obtain double %s.\n", name);
+	//printf("name = %s",name);
+    PyErr_SetString(PyExc_RuntimeError, buf);
+    return 0;
+  }  
+  
+  tmp = PyInt_AsLong(TObject);
+  
+  Py_DECREF(TObject);
+  
+  return tmp;
+}
+
+
+PyObject *get_python_object(PyObject *O, char *name) {
+  PyObject *Oout;
+
+  Oout = PyObject_GetAttrString(O, name);
+  if (!Oout) {
+    PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_python_object could not obtain object");
+    return NULL;
+  }
+
+  return Oout;
+
+}
+
+
+// check that numpy array objects are C contiguous memory
+#define CHECK_C_CONTIG(varname)	if (!PyArray_ISCONTIGUOUS(varname)) { \
+				    char msg[1024]; \
+				    sprintf(msg, \
+					    "%s(): file %s, line %d: " \
+				            "'%s' object is not C contiguous memory", \
+				             __func__, __FILE__, __LINE__, #varname); \
+				    PyErr_SetString(PyExc_RuntimeError, msg); \
+				    return NULL; \
+				}
Index: trunk/anuga_work/development/2010-projects/kv/kv_solver_new.py
===================================================================
--- trunk/anuga_work/development/2010-projects/kv/kv_solver_new.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/kv/kv_solver_new.py	(revision 7884)
@@ -0,0 +1,312 @@
+from anuga.abstract_2d_finite_volumes.generic_domain import Generic_Domain
+import anuga.abstract_2d_finite_volumes.mesh_factory as mesh_factory
+from anuga.utilities.sparse import Sparse, Sparse_CSR
+from anuga.utilities.cg_solve import conjugate_gradient
+import anuga.abstract_2d_finite_volumes.neighbour_mesh as neighbour_mesh
+from generic_boundary_conditions import Dirichlet_boundary
+import numpy as num
+import anuga.utilities.log as log
+"""
+Kinematic Viscosity Class for ANUGA
+Lindon Roberts, 2010
+
+Possible extensions:
+(1) Currently assume that the line between centroids
+is parallel to the outward normal. Change formula
+for this.
+(2) Higher order approximation (eg. Least squares
+fitting or quadratic etc.)
+(3) Vectorise the for loops - multiply by diagonal matrices?
+(4) Tidy up direct application calling structure: __mul__ for matrices,
+then ensure correct setting of include_boundaries
+(5) More comprehensive testing (larger problems)
+"""
+
+
+"""
+How to use:
+
+(1) Direct application
+domain = anuga.abstract_2d_finite_volumes.generic_domain.Generic_Domain(...)
+KV_Operator = Kinematic_Viscosity_Operator(domain)
+h = [n*1 numpy column vector]
+KV_Operator.apply_stage_heights(h)
+uh = [n*1 numpy column vector]
+vh = [n*1 numpy column vector]
+KV_Operator.set_qty_considered('u') #or KV_Operator.set_qty_considered(1)
+KV_Operator.build_boundary_vector()
+div_u = KV_Operator.apply_kv_operator(uh)
+KV_Operator.set_qty_considered('v') #or KV_Operator.set_qty_considered(2)
+KV_Operator.build_boundary_vector()
+div_v = KV_Operator.apply_kv_operator(vh)
+
+[Now div_u and div_v are (n,) numpy vectors]
+
+------------------------------------------------------------------------
+(2) Implicit use
+domain = anuga.abstract_2d_finite_volumes.generic_domain.Generic_Domain(...)
+KV_Operator = Kinematic_Viscosity_Operator(domain)
+h = [n*1 numpy column vector]
+KV_Operator.apply_stage_heights(h)
+div = [n*2 numpy matrix] #column 0 = div_u, column 1 = div_v
+velocities = KV_Operator.cg_solve(div)
+
+[Now velocities is a (n,2) numpy matrix = [(uh) (vh)]]
+
+If you just want to solve for (uh), say:
+KV_Operator.apply_stage_heights(h)
+div_u = [(n,) numpy vector]
+uh = KV_Operator.cg_solve(div_u, 'u') #or KV_Operator.cg_solve(div_u,1)
+"""
+
+class Kinematic_Viscosity_Operator:
+    ## @brief Initialise a KV operator
+    # @param domain The anuga.abstract_2d_finite_volumes.generic_domain.Generic_Domain for the problem
+    # @param triangle_areas Whether we should scale the divergence by 1/|Triangle_i|
+    # @param verbose
+    def __init__(self, domain, triangle_areas=True, verbose=False):
+        #Expose the domain attributes
+        self.domain = domain
+        self.mesh = domain.mesh
+        self.boundary = domain.boundary
+        self.boundary_enum = self.enumerate_boundary()
+        self.n = len(self.domain)
+        self.boundary_len = len(domain.boundary)
+        self.qty_considered = 1 #1 or 2 (uh or vh respectively)
+        self.verbose = verbose
+        if self.verbose: log.critical('Kinematic Viscosity: Building structure')
+        self.geo_structure = self.build_geo_structure() #list of Sparse matrices
+        self.operator_matrix = Sparse(self.n,self.n+self.boundary_len)
+        self.stage_heights = num.zeros((self.n,1),num.float)
+        self.stage_heights_scaling = Sparse(self.n,self.n)
+        self.apply_triangle_areas = triangle_areas
+        self.boundary_vector = num.zeros((self.n,),num.float)
+        
+        self.triangle_areas = Sparse(self.n,self.n)
+        for i in range(self.n):
+            self.triangle_areas[i,i] = 1.0 / self.mesh.areas[i]
+        if self.verbose: log.critical('Kinematic Viscosity: Initialisation Done')
+    
+    ##
+    # Enumerate the boundary conditions in some way
+    def enumerate_boundary(self):
+        #Just enumerate by the dictionary.keys() list order
+        #NOTE If this is changed, need to fix build_boundary_vector() method
+        enumeration = {}
+        keys = self.boundary.keys()
+        for k,key in enumerate(keys):
+            enumeration[key] = k
+        return enumeration
+    
+    #Create the matrix structure for the geometric component of the operator
+    # (constant across all applications of the operator)
+    def build_geo_structure(self):
+        A = [Sparse(self.n,self.n+self.boundary_len), Sparse(self.n,self.n+self.boundary_len), Sparse(self.n,self.n+self.boundary_len)]
+        for i in range(self.n):
+            this_centroid_coords = self.mesh.centroid_coordinates[i,:]
+            for edge in range(3):
+                j = self.mesh.neighbours[i,edge]
+                edge_length = self.mesh.edgelengths[i,edge]
+                dist = 0.0
+                index = j
+                if j==-1: #Boundary edge
+                    boundary_coords = self.mesh.get_edge_midpoint_coordinate(i,edge)
+                    dist = num.linalg.norm(this_centroid_coords - boundary_coords)
+                    index = self.n + self.boundary_enum[(i,edge)]
+                else: #Interior edge
+                    other_centroid_coords = self.mesh.centroid_coordinates[j,:]
+                    dist = num.linalg.norm(this_centroid_coords - other_centroid_coords)
+                A[edge][i,i] = -edge_length / dist
+                A[edge][i,index] = edge_length / dist
+        return A
+    
+    def set_qty_considered(self,qty):
+        if qty == 1 or qty == 'u':
+            self.qty_considered = 1
+        elif qty == 2 or qty == 'v':
+            self.qty_considered = 2
+        else: #Raise an exception
+            msg = "Incorrect input qty"
+            assert 0==1, msg
+    
+    def apply_stage_heights(self,h):
+        msg = "(KV_Operator.apply_stage_heights) h vector has incorrect length"
+        assert h.size == self.n, msg
+        
+        #h is a vector of self.n stage heights (1 per triangle)
+        #scaled_geo_structure = num.zeros((3,self.n,self.n+self.boundary_len),num.float)
+        scaled_geo_structure = [Sparse(self.n,self.n+self.boundary_len), Sparse(self.n,self.n+self.boundary_len), Sparse(self.n,self.n+self.boundary_len)]
+        for i in range(self.n):
+            h_i = h[i]
+            for edge in range(3):
+                j = self.mesh.neighbours[i,edge]
+                h_j = 0.0
+                index = j
+                if j==-1: #Boundary edge
+                    h_j = self.boundary[(i,edge)].evaluate()[0]
+                    index = self.n + self.boundary_enum[(i,edge)]
+                else: #Interior edge
+                    h_j = h[j]
+                scaled_geo_structure[edge][i,i] = 0.5*(h_i+h_j)*self.geo_structure[edge][i,i]
+                scaled_geo_structure[edge][i,index] = 0.5*(h_i+h_j)*self.geo_structure[edge][i,index]
+        self.operator_matrix = Sparse_CSR(scaled_geo_structure[0]+scaled_geo_structure[1]+scaled_geo_structure[2])
+        #self.operator_matrix = scaled_geo_structure[0]+scaled_geo_structure[1]+scaled_geo_structure[2]
+        self.stage_heights = h
+        #Set up the scaling matrix
+        for i in range(self.n):
+            if h[i] == 0.0:
+                self.stage_heights_scaling[i,i] = 0.0
+            else:
+                self.stage_heights_scaling[i,i] = 1.0/h[i]
+        return self.operator_matrix
+    
+    def build_boundary_vector(self):
+        #Require self.qty_considered already set and stage heights applied
+        X = num.zeros((self.n+self.boundary_len,),num.float)
+        #TODO Can vectorise?
+        for i,key in enumerate(self.boundary.keys()):
+            quantities = self.boundary[key].evaluate()
+            h_i = quantities[0]
+            if h_i == 0.0:
+                X[self.n+i] = 0.0
+            else:
+                X[self.n+i] = quantities[self.qty_considered] / h_i
+        self.boundary_vector = self.operator_matrix * X
+        #Tidy up
+        if self.apply_triangle_areas:
+            self.boundary_vector = self.triangle_areas * self.boundary_vector
+
+        return self.boundary_vector
+    
+    def apply_kv_operator(self,V,qty_considered=None,include_boundary=True):
+        msg = "(KV_Operator.apply_vector) V vector has incorrect dimensions"
+        assert V.shape == (self.n,) or V.shape == (self.n,1), msg
+        
+        if not qty_considered==None:
+            print "Quantity Considered changed!"
+            self.set_qty_considered(qty_considered)
+            self.build_boundary_vector()
+        
+        D = num.zeros((self.n,),num.float)
+        #Change (uh) to (u), (vh) to (v)
+        X = self.stage_heights_scaling * V
+        
+        if self.apply_triangle_areas:
+            X = self.triangle_areas * X
+        
+        if include_boundary:
+            #TODO Tidy this up
+            #A = self.operator_matrix.todense()
+            #D = num.mat(A[:,:self.n]) * num.mat(X.reshape(self.n,1)) + self.boundary_vector
+            A = self.operator_matrix
+            D = A * num.concatenate((X, num.zeros(self.boundary_len,num.float))) + self.boundary_vector
+        else:
+            A = self.operator_matrix
+            D = A * num.concatenate((X, num.zeros(self.boundary_len,num.float)))
+            #A = self.operator_matrix.todense()
+            #D = num.mat(A[:,:self.n]) * num.mat(X.reshape(self.n,1))
+
+        return num.array(D).reshape(self.n,)
+    
+    def __mul__(self,other):
+        try:
+            B = num.array(other)
+        except:
+            msg = "Trying to multiply the Kinematic Viscosity Operator against a non-numeric type"
+            raise msg
+        
+        if len(B.shape) == 0:
+            #Scalar
+            R = B*self
+        elif len(B.shape) == 1 or (len(B.shape) == 2 and B.shape[1]==1):
+            #Vector
+            #include_boundary=False is this is *only* used for cg_solve()
+            R = self.apply_kv_operator(other,include_boundary=False)
+        else:
+            raise ValueError, 'Dimension too high: d=%d' %len(B.shape)
+        return R
+    
+    def __rmul__(self, other):
+        #Right multiply with scalar
+        try:
+            other = float(other)
+        except:
+            msg = 'Sparse matrix can only "right-multiply" onto a scalar'
+            raise TypeError, msg
+        else:
+            new = self.operator_matrix * new
+        return new
+    
+    def cg_solve(self,B,qty_to_consider=None):
+        if len(B.shape) == 1:
+            return self.cg_solve_vector(B,qty_to_consider)
+        elif len(B.shape) == 2:
+            return self.cg_solve_matrix(B)
+        else:
+            raise ValueError, 'Dimension too high: d=%d' %len(B.shape)
+    
+    def cg_solve_matrix(self,B):
+        assert B.shape[1] < 3, "Input matrix has too many columns (max 2)"
+        
+        X = num.zeros(B.shape,num.float)
+        for i in range(B.shape[1]):
+            X[:,i] = self.cg_solve_vector(B[:,i],i+1) #assuming B columns are (uh) and (vh)
+        return X
+    
+    def cg_solve_vector(self,b,qty_to_consider=None):
+        if not qty_to_consider==None:
+            self.set_qty_considered(qty_to_consider)
+        self.build_boundary_vector()
+        if self.verbose :
+            iprint = 1
+        else:
+            iprint = 0
+        x = conjugate_gradient(self,b - self.boundary_vector, iprint=iprint) #Call the ANUGA conjugate gradient utility
+        return x
+
+################################################################################
+
+if __name__ == "__main__":
+    #Set up a rectangular grid and check minimum/maximum principle
+
+    import time
+    t0 = time.time()
+    points,elements,boundary = mesh_factory.rectangular_cross(10, 15)
+    mesh = neighbour_mesh.Mesh(points,elements)
+    n = len(mesh)
+    boundary_map = {}
+    for (vol_id,edge) in boundary.keys():
+        x = mesh.get_edge_midpoint_coordinate(vol_id,edge)[0]
+        y = mesh.get_edge_midpoint_coordinate(vol_id,edge)[1]
+        #Define boundary conditions: u=x^2-y^2, v=x-y+2
+        boundary_map[(vol_id,edge)] = Dirichlet_boundary([1,x*x-y*y,x-y+2])
+    #Now define an operator
+    domain = Generic_Domain(source=points,triangles=elements,boundary=boundary_map)
+    KV_Operator = Kinematic_Viscosity_Operator(domain, verbose = True)
+    
+    #Set up the operator and RHS
+    h = num.ones((n,),num.float)
+    KV_Operator.apply_stage_heights(h)
+    rhs = num.zeros((n,2),num.float) #we will solve for u and v
+    
+    #Solve
+    velocities = KV_Operator.cg_solve(rhs)
+    #Alternatively, velocities = [u v] where:
+    u = KV_Operator.cg_solve(num.zeros((n,),num.float),'u')
+    v = KV_Operator.cg_solve(num.zeros((n,),num.float),'v')
+    vel_min = velocities.min(axis=0)
+    vel_max = velocities.max(axis=0)
+    
+    #Check a minimum/maximum principle
+    boundary_velocities = num.zeros((len(boundary_map),2),num.float)
+    for i,key in enumerate(boundary_map.keys()):
+        quantity = boundary_map[key].evaluate()
+        boundary_velocities[i,:] = quantity[1:]
+    boundary_vel_min = boundary_velocities.min(axis=0)
+    boundary_vel_max = boundary_velocities.max(axis=0)
+
+
+    print "Time ",time.time() - t0
+    print "Kinematic Viscosity Min/Max Principle Test"
+    print "Minimum Principle?", (vel_min > boundary_vel_min).all()
+    print "Maximum Principle?", (boundary_vel_max > vel_max).all()
Index: trunk/anuga_work/development/2010-projects/kv/test_kv_solver_new.py
===================================================================
--- trunk/anuga_work/development/2010-projects/kv/test_kv_solver_new.py	(revision 7884)
+++ trunk/anuga_work/development/2010-projects/kv/test_kv_solver_new.py	(revision 7884)
@@ -0,0 +1,153 @@
+from anuga.abstract_2d_finite_volumes.generic_domain import Generic_Domain
+from anuga.abstract_2d_finite_volumes.generic_boundary_conditions import Dirichlet_boundary
+from kv_solver_new import Kinematic_Viscosity_Operator
+import numpy as num
+from math import sqrt
+import unittest
+
+class Test_kv_solver_new(unittest.TestCase):
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+    
+    #First test operator class (1 triangle)
+    def operator1(self):
+        points = num.array([[0.0,0.0],[1.0,0.0],[0.0,1.0]])
+        elements = num.array([[0,1,2]])
+        boundary_map = {}
+        boundary_map[(0,0)] = Dirichlet_boundary([1,2,1])
+        boundary_map[(0,1)] = Dirichlet_boundary([1,1,2])
+        boundary_map[(0,2)] = Dirichlet_boundary([1,1,0])
+        #We get boundary_may.keys() = [(0, 1), (0, 0), (0, 2)]
+        domain = Generic_Domain(source=points,triangles=elements,boundary=boundary_map)
+        return Kinematic_Viscosity_Operator(domain)
+  
+    #Second test operator class (2 triangles)
+    def operator2(self):
+        points = num.array([[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]])
+        elements = num.array([[0,1,3],[1,2,3]])
+        boundary_map = {}
+        boundary_map[(0,1)] = Dirichlet_boundary([1,1,2])
+        boundary_map[(0,2)] = Dirichlet_boundary([1,2,2])
+        boundary_map[(1,0)] = Dirichlet_boundary([1,1,0])
+        boundary_map[(1,2)] = Dirichlet_boundary([1,2,1])
+        #We get boundary_map.keys() = [(0, 1), (1, 2), (1, 0), (0, 2)]
+        domain = Generic_Domain(source=points,triangles=elements,boundary=boundary_map)
+        return Kinematic_Viscosity_Operator(domain)
+    
+    def test_build_index_boundary_map(self):
+        operator1 = self.operator1()
+        boundary_map_index = operator1.boundary_enum
+        assert boundary_map_index[(0,1)] == 0
+        assert boundary_map_index[(0,0)] == 1
+        assert boundary_map_index[(0,2)] == 2
+
+        operator2 = self.operator2()
+        boundary_map_index = operator2.boundary_enum
+        assert boundary_map_index[(0,1)] == 0
+        assert boundary_map_index[(1,2)] == 1
+        assert boundary_map_index[(1,0)] == 2
+        assert boundary_map_index[(0,2)] == 3
+
+    def test_kv_system_geometry(self):
+        operator1 = self.operator1()
+        operator2 = self.operator2()
+
+        kv_geo_structure = operator1.geo_structure
+        assert num.allclose(kv_geo_structure[0].todense(), num.array([[-6.0,0.0,6.0,0.0]]))
+        assert num.allclose(kv_geo_structure[1].todense(), \
+                            num.array([[-6.0/sqrt(5.0),6.0/sqrt(5.0),0.0,0.0]]))
+        assert num.allclose(kv_geo_structure[2].todense(),\
+                            num.array([[-6.0/sqrt(5.0),0.0,0.0,6.0/sqrt(5.0)]]))
+
+        kv_geo_structure = operator2.geo_structure
+        assert num.allclose(kv_geo_structure[0].todense(), num.array([[-3.0,3.0,0.0,0.0,0.0,0.0],\
+                                                                [0.0,-6.0/sqrt(5.0),0.0,0.0,6.0/sqrt(5.0),0.0]]))
+        assert num.allclose(kv_geo_structure[1].todense(), num.array([[-6.0/sqrt(5.0),0.0,6.0/sqrt(5.0),0.0,0.0,0.0],\
+                                                                [3.0,-3.0,0.0,0.0,0.0,0.0]]))
+        assert num.allclose(kv_geo_structure[2].todense(), num.array([[-6.0/sqrt(5.0),0.0,0.0,0.0,0.0,6.0/sqrt(5.0)],\
+                                                                [0.0, -6.0/sqrt(5.0), 0.0, 6.0/sqrt(5.0), 0.0, 0.0]]))
+    
+    def test_apply_heights(self):
+        operator1 = self.operator1()
+        operator2 = self.operator2()
+        
+        h = num.array([1.0])
+        A = operator1.apply_stage_heights(h)
+        assert num.allclose(A.todense(), num.array([-6.0-12.0/sqrt(5), 6.0/sqrt(5), 6.0, 6.0/sqrt(5)]))
+        
+        h = num.array([2.0])
+        A = operator1.apply_stage_heights(h)
+        assert num.allclose(A.todense(), 1.5*num.array([-6.0-12.0/sqrt(5), 6.0/sqrt(5), 6.0, 6.0/sqrt(5)]))
+        
+        h = num.array([1.0, 1.0])
+        A = operator2.apply_stage_heights(h)
+        #From test_kv_system_geometry
+        A0 = num.array([[-3.0,3.0,0.0,0.0,0.0,0.0],
+                        [0.0,-6.0/sqrt(5.0),0.0,0.0,6.0/sqrt(5.0),0.0]])
+        A1 = num.array([[-6.0/sqrt(5.0),0.0,6.0/sqrt(5.0),0.0,0.0,0.0],\
+                        [3.0,-3.0,0.0,0.0,0.0,0.0]])
+        A2 = num.array([[-6.0/sqrt(5.0),0.0,0.0,0.0,0.0,6.0/sqrt(5.0)],\
+                        [0.0, -6.0/sqrt(5.0), 0.0, 6.0/sqrt(5.0), 0.0, 0.0]])
+        assert num.allclose(A.todense(), A0+A1+A2)
+        
+        h = num.array([2.0, 1.0])
+        A = operator2.apply_stage_heights(h)
+        assert num.allclose(A.todense()[0,:], 1.5*A0[0,:]+1.5*A1[0,:]+1.5*A2[0,:])
+        assert num.allclose(A.todense()[1,:], A0[1,:]+1.5*A1[1,:]+A2[1,:])
+        
+        h = num.array([-2.0, -2.0])
+        A = operator2.apply_stage_heights(h)
+        assert num.allclose(A.todense()[0,:], -2*A0[0,:]-0.5*A1[0,:]-0.5*A2[0,:])
+        assert num.allclose(A.todense()[1,:], -0.5*A0[1,:]-2*A1[1,:]-0.5*A2[1,:])
+    
+    def test_apply_kv_operator(self):
+        operator1 = self.operator1()
+        operator1.apply_stage_heights(num.array([[1.0]])) #h=1
+        operator1.build_boundary_vector()
+        V1 = num.array([2.0]) #(uh)=2
+        V2 = num.array([2.0]) #(vh)=2
+        A = num.array([-6.0-12.0/sqrt(5), 6.0/sqrt(5), 6.0, 6.0/sqrt(5)])
+        U1 = num.array([[2.0],[1.0],[2.0],[1.0]])
+        U2 = num.array([[2.0],[2.0],[1.0],[0.0]])
+        
+        operator1.set_qty_considered('u')
+        operator1.build_boundary_vector()
+        D1 = operator1.apply_kv_operator(V1)
+        assert num.allclose(D1, 2*num.array(num.mat(A)*num.mat(U1)).reshape(1,))
+        
+        operator1.set_qty_considered(2)
+        operator1.build_boundary_vector()
+        D2 = operator1.apply_kv_operator(V2)
+        assert num.allclose(D2, 2*num.array(num.mat(A)*num.mat(U2)).reshape(1,))
+    
+    def test_mul(self):
+        operator1 = self.operator1()
+        operator1.apply_stage_heights(num.array([[1.0]])) #h=1
+        operator1.set_qty_considered(1)
+        operator1.build_boundary_vector()
+        A = num.array([-6.0-12.0/sqrt(5), 6.0/sqrt(5), 6.0, 6.0/sqrt(5)])
+        V1 = num.array([2.0]) #(uh)=2
+        U1 = num.array([[2.0],[0.0],[0.0],[0.0]])
+        assert num.allclose(operator1 * V1, 2*num.array(num.mat(A)*num.mat(U1)).reshape(1,))
+
+    def test_cg_solve(self):
+        #cf self.test_mul()
+        operator1 = self.operator1()
+        operator1.apply_stage_heights(num.array([[1.0]])) #h=1
+        operator1.set_qty_considered('u')
+        V = num.array([2.0]) #h=1, (uh)=2
+        A = num.array([-6.0-12.0/sqrt(5), 6.0/sqrt(5), 6.0, 6.0/sqrt(5)])
+        U = num.array([[2.0,2.0],[1.0,2.0],[2.0,1.0],[1.0,0.0]])
+        test = 2*num.mat(A)*num.mat(U[:,0].reshape(4,1))
+        X = operator1.cg_solve(num.array(test).reshape(1,))
+        assert num.allclose(V, X)
+
+################################################################################
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_kv_solver_new, 'test')
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
