Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/SConscript
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/SConscript	(revision 9459)
+++ 	(revision )
@@ -1,9 +1,0 @@
-import os
-Import('env')
-env2 = env.Copy()
-env2.Append(CPPPATH=['#source/anuga/utilities'])
-
-instdir = os.path.join(env['PREFIX'], 'anuga', 'pyvolution')
-env.Install(instdir, env2.SharedLibrary('quantity_ext', ['quantity_ext.c']))
-env.Install(instdir, env2.SharedLibrary('shallow_water_ext', ['shallow_water_ext.c']))
-env.Install(instdir, env2.SharedLibrary('shallow_water_kinetic', ['shallow_water_kinetic_ext.c']))
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/show_balanced_limiters.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/show_balanced_limiters.py	(revision 9459)
+++ 	(revision )
@@ -1,87 +1,0 @@
-"""Example of shallow water wave equation.
-
-Specific methods pertaining to the 2D shallow water equation
-are imported from shallow_water
-for use with the generic finite volume framework
-
-Conserved quantities are h, uh and vh stored as elements 0, 1 and 2 in the
-numerical vector named conserved_quantities.
-"""
-
-######################
-# Module imports 
-#
-from anuga.shallow_water import Domain,\
-     Reflective_boundary, Dirichlet_boundary,\
-     Transmissive_boundary, Time_boundary
-from anuga.shallow_water.shallow_water_domain import Weir_simple as Weir
-import anuga.utilities.log as log
-
-from mesh_factory import rectangular
-
-
-######################
-# Domain
-#
-
-N = 12
-
-log.critical('Creating domain')
-#Create basic mesh
-points, vertices, boundary = rectangular(N, N/2, len1=1.2,len2=0.6,
-                                         origin=(-0.07, 0))
-
-log.critical('Number of elements=%d' % len(vertices))
-#Create shallow water domain
-domain = Domain(points, vertices, boundary)
-domain.smooth = False
-domain.default_order = 2
-domain.set_name('show_balanced_limiters')
-domain.store = True
-domain.format = 'sww'   #Native netcdf visualisation format
-
-#Set bed-slope and friction
-inflow_stage = 0.1
-manning = 0.1
-Z = Weir(inflow_stage)
-
-log.critical('Field values')
-domain.set_quantity('elevation', Z)
-domain.set_quantity('friction', manning)
-
-
-######################
-# Boundary conditions
-#
-log.critical('Boundaries')
-Br = Reflective_boundary(domain)
-Bt = Transmissive_boundary(domain)
-
-#Constant inflow
-Bd = Dirichlet_boundary([inflow_stage, 0.0, 0.0])
-
-#Time dependent inflow
-from math import sin, pi
-Bw = Time_boundary(domain=domain,
-                   f=lambda x: [(1 + sin(x*pi/4))*\
-                                (inflow_stage*(sin(2.5*x*pi)+0.7)),0,0])
-
-#Set boundary conditions
-domain.set_boundary({'left': Bd, 'right': Br, 'bottom': Br, 'top': Br})
-
-                    
-
-######################
-#Initial condition
-#
-log.critical('Initial condition')
-domain.set_quantity('stage', Z)
-
-#Evolve
-for t in domain.evolve(yieldstep = 0.1, finaltime = 30):
-    domain.write_time(track_speeds=True)
-    domain.write_boundary_statistics(['stage'],'left')
-
-log.critical('Done')
-    
-
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/show_balanced_limiters.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/show_balanced_limiters.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/show_balanced_limiters.py	(revision 9460)
@@ -0,0 +1,87 @@
+"""Example of shallow water wave equation.
+
+Specific methods pertaining to the 2D shallow water equation
+are imported from shallow_water
+for use with the generic finite volume framework
+
+Conserved quantities are h, uh and vh stored as elements 0, 1 and 2 in the
+numerical vector named conserved_quantities.
+"""
+
+######################
+# Module imports 
+#
+from anuga.shallow_water import Domain,\
+     Reflective_boundary, Dirichlet_boundary,\
+     Transmissive_boundary, Time_boundary
+from anuga.shallow_water.shallow_water_domain import Weir_simple as Weir
+import anuga.utilities.log as log
+
+from mesh_factory import rectangular
+
+
+######################
+# Domain
+#
+
+N = 12
+
+log.critical('Creating domain')
+#Create basic mesh
+points, vertices, boundary = rectangular(N, N/2, len1=1.2,len2=0.6,
+                                         origin=(-0.07, 0))
+
+log.critical('Number of elements=%d' % len(vertices))
+#Create shallow water domain
+domain = Domain(points, vertices, boundary)
+domain.smooth = False
+domain.default_order = 2
+domain.set_name('show_balanced_limiters')
+domain.store = True
+domain.format = 'sww'   #Native netcdf visualisation format
+
+#Set bed-slope and friction
+inflow_stage = 0.1
+manning = 0.1
+Z = Weir(inflow_stage)
+
+log.critical('Field values')
+domain.set_quantity('elevation', Z)
+domain.set_quantity('friction', manning)
+
+
+######################
+# Boundary conditions
+#
+log.critical('Boundaries')
+Br = Reflective_boundary(domain)
+Bt = Transmissive_boundary(domain)
+
+#Constant inflow
+Bd = Dirichlet_boundary([inflow_stage, 0.0, 0.0])
+
+#Time dependent inflow
+from math import sin, pi
+Bw = Time_boundary(domain=domain,
+                   f=lambda x: [(1 + sin(x*pi/4))*\
+                                (inflow_stage*(sin(2.5*x*pi)+0.7)),0,0])
+
+#Set boundary conditions
+domain.set_boundary({'left': Bd, 'right': Br, 'bottom': Br, 'top': Br})
+
+                    
+
+######################
+#Initial condition
+#
+log.critical('Initial condition')
+domain.set_quantity('stage', Z)
+
+#Evolve
+for t in domain.evolve(yieldstep = 0.1, finaltime = 30):
+    domain.write_time(track_speeds=True)
+    domain.write_boundary_statistics(['stage'],'left')
+
+log.critical('Done')
+    
+
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_all.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_all.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_all.py	(revision 9460)
@@ -0,0 +1,102 @@
+"""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__':
+
+    from os import sep
+
+    #Attempt to compile all extensions
+    #execfile('..' + sep + 'utilities' + sep + 'compile.py')
+
+    #FIXME: Temporary measure
+    #os.chdir('..' + sep + 'utilities')
+    #execfile('compile.py')
+    #os.chdir('..' + sep + 'pyvolution')    
+    
+    #FIXME: Temporary measure
+    #os.chdir('..' + sep + 'triangle')
+    #execfile('compile.py')
+    #os.chdir('..' + sep + 'pyvolution')   
+    
+    #os.system('python compile.py') 
+
+    #print regressionTest()
+    #unittest.main(defaultTest='regressionTest')
+    
+    suite = regressionTest()
+    runner = unittest.TextTestRunner() #(verbosity=2)
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_ermapper.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_ermapper.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_ermapper.py	(revision 9460)
@@ -0,0 +1,189 @@
+#!/usr/bin/env python
+
+import unittest
+
+
+import anuga.abstract_2d_finite_volumes.ermapper_grids as ermapper_grids
+from os import remove
+
+import numpy as num
+
+
+class Test_ERMapper(unittest.TestCase):
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+    def test_write_grid(self):
+        header_filename = 'test_write_ermapper_grid.ers'
+        data_filename = 'test_write_ermapper_grid'
+        
+        original_grid = num.array([[0.0, 0.1, 1.0], [2.0, 3.0, 4.0]])
+
+        # Check that the function works when passing the filename without
+        # a '.ers' extension
+        ermapper_grids.write_ermapper_grid(data_filename, original_grid)
+        new_grid = ermapper_grids.read_ermapper_grid(data_filename)
+        assert num.allclose(original_grid, new_grid)
+
+        # Check that the function works when passing the filename with
+        # a '.ers' extension
+        ermapper_grids.write_ermapper_grid(header_filename, original_grid)
+        new_grid = ermapper_grids.read_ermapper_grid(header_filename)
+        assert num.allclose(original_grid, new_grid)
+
+        # Clean up created files
+        remove(data_filename)
+        remove(header_filename)
+        
+    def test_basic_single_line_grid(self):
+        # Setup test data
+        filename = 'test_write_ermapper_grid'
+        original_grid = num.array([0.0, 0.1, 1.0, 2.0, 3.0, 4.0])
+
+        # Write test data
+        ermapper_grids.write_ermapper_data(original_grid, filename, num.float64)
+
+        # Read in the test data
+        new_grid = ermapper_grids.read_ermapper_data(filename, num.float64)
+
+        # Check that the test data that has been read in matches the original data
+        assert num.allclose(original_grid, new_grid)
+
+        # Clean up created files
+        remove(filename)
+        
+    def test_basic_single_line_grid_default_format(self):
+        # Setup test data
+        filename = 'test_write_ermapper_grid'
+        original_grid = num.array([0.0, 0.1, 1.0, 2.0, 3.0, 4.0])
+
+        # Write test data
+        ermapper_grids.write_ermapper_data(original_grid, filename)
+
+        # Read in the test data
+        new_grid = ermapper_grids.read_ermapper_data(filename)
+
+        # Check that the test data that has been read in matches the original data
+        assert num.allclose(original_grid, new_grid)
+
+        # Clean up created files
+        remove(filename)
+        
+    def test_write_default_header(self):
+        data_filename = 'test_write_ermapper_grid'
+
+        # setup test data
+        original_grid = num.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
+        # Write test data
+        ermapper_grids.write_ermapper_data(original_grid, data_filename)
+        # Write test header using all default values
+        header_filename = data_filename + '.ers'                              
+        ermapper_grids.write_ermapper_header(header_filename)
+
+        # Check that the read in values match the default values
+        header = ermapper_grids.read_ermapper_header(header_filename)
+
+        assert header['datum'] == '"GDA94"'
+        assert header['projection'] == '"GEOGRAPHIC"'  
+        assert header['coordinatetype'] == 'LL'
+        assert header['rotation'] == '0:0:0.0'
+        assert header['celltype'] == 'IEEE4ByteReal'
+        assert header['nullcellvalue'] == '-99999'
+        assert header['xdimension'] == '100'
+        assert header['registrationcellx'] == '0'
+        assert header['ydimension'] == '100'
+        assert header['registrationcelly'] == '2'
+        assert header['nroflines'] == '3'
+        assert header['nrofcellsperline'] == '4'
+        assert header['longitude'] == '0:0:0'
+        assert header['latitude'] == '0:0:0'
+        assert header['nrofbands'] == '1'
+        assert header['value'] == '"Default_Band"'
+
+        # Clean up created files
+        remove(data_filename)
+        remove(header_filename)
+        
+    def test_header_creation(self):
+        header = {}
+        # have some values that aren't defaults
+        header['nroflines'] = '2'
+        header['nrofcellsperline'] = '3'
+
+        header = ermapper_grids.create_default_header(header)
+
+
+        # default values
+        assert header['datum'] == '"GDA94"'
+        assert header['projection'] == '"GEOGRAPHIC"'  
+        assert header['coordinatetype'] == 'LL'
+        assert header['rotation'] == '0:0:0.0'
+        assert header['celltype'] == 'IEEE4ByteReal'
+        assert header['nullcellvalue'] == '-99999'
+        assert header['xdimension'] == '100'
+        assert header['registrationcellx'] == '0'
+        assert header['ydimension'] == '100'
+        assert header['longitude'] == '0:0:0'
+        assert header['latitude'] == '0:0:0'
+        assert header['nrofbands'] == '1'
+        assert header['value'] == '"Default_Band"'
+
+        # non-default values
+        assert header['nroflines'] == '2'
+        assert header['nrofcellsperline'] == '3'
+        assert header['registrationcelly'] == '1'
+
+
+    def test_write_non_default_header(self):
+        header_filename = 'test_write_ermapper_grid.ers'
+
+        # setup test data
+        header = {}
+        # have some values that aren't defaults
+        header['nroflines'] = '2'
+        header['nrofcellsperline'] = '3'
+        
+        # Write test header using non-default values                           
+        ermapper_grids.write_ermapper_header(header_filename, header)
+
+        # Check that the read in values match the default values
+        header = ermapper_grids.read_ermapper_header(header_filename)
+
+        # default values
+        assert header['datum'] == '"GDA94"'
+        assert header['projection'] == '"GEOGRAPHIC"'  
+        assert header['coordinatetype'] == 'LL'
+        assert header['rotation'] == '0:0:0.0'
+        assert header['celltype'] == 'IEEE4ByteReal'
+        assert header['nullcellvalue'] == '-99999'
+        assert header['xdimension'] == '100'
+        assert header['registrationcellx'] == '0'
+        assert header['ydimension'] == '100'
+        assert header['longitude'] == '0:0:0'
+        assert header['latitude'] == '0:0:0'
+        assert header['nrofbands'] == '1'
+        assert header['value'] == '"Default_Band"'
+
+        # non-default values
+        assert header['nroflines'] == '2'
+        assert header['nrofcellsperline'] == '3'
+        assert header['registrationcelly'] == '1'
+
+        # Clean up created files
+        remove(header_filename)        
+
+
+# def test_default_filenames
+# def test_write_header
+# def test_multi_band_grid
+
+       
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_ERMapper,'test')
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_gauge.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_gauge.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_gauge.py	(revision 9460)
@@ -0,0 +1,549 @@
+#!/usr/bin/env python
+
+
+import unittest
+from math import sqrt, pi
+import tempfile, os
+from os import access, F_OK,sep, removedirs,remove,mkdir,getcwd
+
+import anuga
+#from anuga.abstract_2d_finite_volumes.util import *
+from anuga.abstract_2d_finite_volumes.gauge import sww2csv_gauges
+from anuga.config import epsilon
+
+from anuga.utilities.numerical_tools import NAN,mean
+
+from sys import platform 
+
+from anuga.pmesh.mesh import Mesh
+
+from anuga.file.sww import SWW_file
+from anuga.file_conversion.file_conversion import timefile2netcdf
+from anuga.utilities.file_utils import del_dir
+from csv import reader, writer
+import time
+import string
+
+import numpy as num
+
+
+def test_function(x, y):
+    return x+y
+
+class Test_Gauge(unittest.TestCase):
+    def setUp(self):
+
+        def elevation_function(x, y):
+            return -x
+        
+        """ Setup for all tests. """
+        
+        mesh_file = tempfile.mktemp(".tsh")    
+        points = [[0.0,0.0],[6.0,0.0],[6.0,6.0],[0.0,6.0]]
+        m = Mesh()
+        m.add_vertices(points)
+        m.auto_segment()
+        m.generate_mesh(verbose=False)
+        m.export_mesh_file(mesh_file)
+        
+        # Create shallow water domain
+        domain = anuga.Domain(mesh_file)
+        os.remove(mesh_file)
+ 
+        domain.default_order = 2
+
+        # This test was made before tight_slope_limiters were introduced
+        # Since were are testing interpolation values this is OK
+        domain.tight_slope_limiters = 0
+                
+        # Set some field values
+        domain.set_quantity('elevation', elevation_function)
+        domain.set_quantity('friction', 0.03)
+        domain.set_quantity('xmomentum', 3.0)
+        domain.set_quantity('ymomentum', 4.0)
+
+        ######################
+        # Boundary conditions
+        B = anuga.Transmissive_boundary(domain)
+        domain.set_boundary( {'exterior': B})
+
+        # This call mangles the stage values.
+        domain.distribute_to_vertices_and_edges()
+        domain.set_quantity('stage', 1.0)
+
+        domain.set_name('datatest' + str(time.time()))
+        domain.smooth = True
+        domain.reduction = mean
+        
+        self.domain = domain
+        
+        
+    def tearDown(self):
+        """Called at end of each test."""
+        if self.sww:
+            os.remove(self.sww.filename)
+
+    def _create_sww(self,stage=10.0, timestep=2.0):
+        self.sww = SWW_file(self.domain)
+        self.sww.store_connectivity()
+        self.sww.store_timestep()
+        self.domain.set_quantity('stage', stage) # This is automatically limited
+        # so it will not be less than the elevation
+        self.domain.set_time(self.domain.get_time()-self.domain.starttime+timestep)
+        self.sww.store_timestep()
+        
+        
+    def test_sww2csv_0(self):
+
+        """Most of this test was copied from test_interpolate
+        test_interpole_sww2csv
+        
+        This is testing the sww2csv_gauges function, by creating a sww file and
+        then exporting the gauges and checking the results.
+        """
+        
+        domain = self.domain
+        self._create_sww()
+        
+        # test the function
+        points = [[5.0,1.],[0.5,2.]]
+
+        points_file = tempfile.mktemp(".csv") 
+#        points_file = 'test_point.csv'
+        file_id = open(points_file,"w")
+        file_id.write("name, easting, northing, elevation \n\
+point1, 5.0, 1.0, 3.0\n\
+point2, 0.5, 2.0, 9.0\n")
+        file_id.close()
+
+        
+        sww2csv_gauges(self.sww.filename, 
+                       points_file,
+                       verbose=False,
+                       use_cache=False)
+
+#        point1_answers_array = [[0.0,1.0,-5.0,3.0,4.0], [2.0,10.0,-5.0,3.0,4.0]]
+        point1_answers_array = [[0.0,0.0,1.0,6.0,-5.0,3.0,4.0], [2.0,2.0/3600.,10.0,15.0,-5.0,3.0,4.0]]
+        point1_filename = 'gauge_point1.csv'
+        point1_handle = open(point1_filename)
+        point1_reader = reader(point1_handle)
+        point1_reader.next()
+
+        line=[]
+        for i,row in enumerate(point1_reader):
+            #print 'i',i,'row',row
+            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
+                         float(row[4]),float(row[5]),float(row[6])])
+            #print 'assert line',line[i],'point1',point1_answers_array[i]
+            assert num.allclose(line[i], point1_answers_array[i])
+
+        point2_answers_array = [[0.0,0.0,1.0,1.5,-0.5,3.0,4.0], [2.0,2.0/3600.,10.0,10.5,-0.5,3.0,4.0]]
+        point2_filename = 'gauge_point2.csv' 
+        point2_handle = open(point2_filename)
+        point2_reader = reader(point2_handle)
+        point2_reader.next()
+                        
+        line=[]
+        for i,row in enumerate(point2_reader):
+#            print 'i',i,'row',row
+            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
+                         float(row[4]),float(row[5]),float(row[6])])
+#            print 'assert line',line[i],'point1',point1_answers_array[i]
+            assert num.allclose(line[i], point2_answers_array[i])
+                         
+        # clean up
+        point1_handle.close()
+        point2_handle.close()
+        #os.remove(points_file)
+        #os.remove(point1_filename)
+        #os.remove(point2_filename)
+
+
+    def test_sww2csv_gauges1(self):
+        from anuga.pmesh.mesh import Mesh
+        from csv import reader,writer
+        import time
+        import string
+        
+        """Most of this test was copied from test_interpolate
+        test_interpole_sww2csv
+        
+        This is testing the sww2csv_gauges function, by creating a sww file and
+        then exporting the gauges and checking the results.
+        
+        This tests the ablity not to have elevation in the points file and 
+        not store xmomentum and ymomentum
+        """
+        
+        domain = self.domain
+        self._create_sww()
+        
+        # test the function
+        points = [[5.0,1.],[0.5,2.]]
+
+        points_file = tempfile.mktemp(".csv")
+#        points_file = 'test_point.csv'
+        file_id = open(points_file,"w")
+        file_id.write("name,easting,northing \n\
+point1, 5.0, 1.0\n\
+point2, 0.5, 2.0\n")
+        file_id.close()
+
+        sww2csv_gauges(self.sww.filename, 
+                            points_file,
+                            quantities=['stage', 'elevation'],
+                            use_cache=False,
+                            verbose=False)
+
+        point1_answers_array = [[0.0,1.0,-5.0], [2.0,10.0,-5.0]]
+        point1_filename = 'gauge_point1.csv'
+        point1_handle = file(point1_filename)
+        point1_reader = reader(point1_handle)
+        point1_reader.next()
+
+        line=[]
+        for i,row in enumerate(point1_reader):
+#            print 'i',i,'row',row
+            # note the 'hole' (element 1) below - skip the new 'hours' field
+            line.append([float(row[0]),float(row[2]),float(row[3])])
+            #print 'line',line[i],'point1',point1_answers_array[i]
+            assert num.allclose(line[i], point1_answers_array[i])
+
+        point2_answers_array = [[0.0,1.0,-0.5], [2.0,10.0,-0.5]]
+        point2_filename = 'gauge_point2.csv' 
+        point2_handle = file(point2_filename)
+        point2_reader = reader(point2_handle)
+        point2_reader.next()
+                        
+        line=[]
+        for i,row in enumerate(point2_reader):
+#            print 'i',i,'row',row
+            # note the 'hole' (element 1) below - skip the new 'hours' field
+            line.append([float(row[0]),float(row[2]),float(row[3])])
+#            print 'line',line[i],'point1',point1_answers_array[i]
+            assert num.allclose(line[i], point2_answers_array[i])
+                         
+        # clean up
+        point1_handle.close()
+        point2_handle.close() 
+        os.remove(points_file)
+        os.remove(point1_filename)
+        os.remove(point2_filename)        
+        
+
+    def test_sww2csv_gauges2(self):
+        
+        """Most of this test was copied from test_interpolate
+        test_interpole_sww2csv
+        
+        This is testing the sww2csv_gauges function, by creating a sww file and
+        then exporting the gauges and checking the results.
+        
+        This is the same as sww2csv_gauges except set domain.set_starttime to 5.
+        Therefore testing the storing of the absolute time in the csv files
+        """
+        
+        domain = self.domain
+        domain.set_starttime(1)
+        
+        self._create_sww(timestep=2)
+        
+        # test the function
+        points = [[5.0,1.],[0.5,2.]]
+
+        points_file = tempfile.mktemp(".csv")
+#        points_file = 'test_point.csv'
+        file_id = open(points_file,"w")
+        file_id.write("name, easting, northing, elevation \n\
+point1, 5.0, 1.0, 3.0\n\
+point2, 0.5, 2.0, 9.0\n")
+        file_id.close()
+        
+        sww2csv_gauges(self.sww.filename, 
+                            points_file,
+                            verbose=False,
+                            use_cache=False)
+
+#        point1_answers_array = [[0.0,1.0,-5.0,3.0,4.0], [2.0,10.0,-5.0,3.0,4.0]]
+        point1_answers_array = [[2.0,2.0/3600.,1.0,6.0,-5.0,3.0,4.0], [3.0,3.0/3600.,10.0,15.0,-5.0,3.0,4.0]]
+        point1_filename = 'gauge_point1.csv'
+        point1_handle = file(point1_filename)
+        point1_reader = reader(point1_handle)
+        point1_reader.next()
+
+        line=[]
+        for i,row in enumerate(point1_reader):
+            #print 'i',i,'row',row
+            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
+                         float(row[4]), float(row[5]), float(row[6])])
+            #print 'assert line',line[i],'answer',point1_answers_array[i]
+            assert num.allclose(line[i], point1_answers_array[i])
+
+        point2_answers_array = [[2.0,2.0/3600.,1.0,1.5,-0.5,3.0,4.0], [3.0,3.0/3600.,10.0,10.5,-0.5,3.0,4.0]]
+        point2_filename = 'gauge_point2.csv' 
+        point2_handle = file(point2_filename)
+        point2_reader = reader(point2_handle)
+        point2_reader.next()
+                        
+        line=[]
+        for i,row in enumerate(point2_reader):
+            #print 'i',i,'row',row
+            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
+                         float(row[4]),float(row[5]), float(row[6])])
+            #print 'assert line',line[i],'point1',point1_answers_array[i]
+            assert num.allclose(line[i], point2_answers_array[i])
+                         
+        # clean up
+        point1_handle.close()
+        point2_handle.close()
+        os.remove(points_file)
+        os.remove(point1_filename)
+        os.remove(point2_filename)
+
+
+       
+    def test_sww2csv_gauge_point_off_mesh(self):
+        from anuga.pmesh.mesh import Mesh
+        from csv import reader,writer
+        import time
+        import string
+        
+        """Most of this test was copied from test_interpolate
+        test_interpole_sww2csv
+        
+        This is testing the sww2csv_gauges function with one gauge off the mesh, by creating a sww file and
+        then exporting the gauges and checking the results.
+        
+        This tests the correct values for when a gauge is off the mesh, which is important for parallel.
+        """
+
+        domain = self.domain
+        sww = self._create_sww()
+     
+        # test the function
+        points = [[50.0,1.],[50.5,-20.25]]
+
+#        points_file = tempfile.mktemp(".csv")
+        points_file = 'test_point.csv'
+        file_id = open(points_file,"w")
+        file_id.write("name,easting,northing \n\
+offmesh1, 50.0, 1.0\n\
+offmesh2, 50.5, 20.25\n")
+        file_id.close()
+
+        points_files = ['offmesh1.csv', 'offmesh2.csv']        
+        
+        for point_filename in points_files:
+            if os.path.exists(point_filename): os.remove(point_filename)         
+        
+        sww2csv_gauges(self.sww.filename, 
+                            points_file,
+                            quantities=['stage', 'elevation', 'bearing'],
+                            use_cache=False,
+                            verbose=False)
+
+        for point_filename in points_files: 
+            assert not os.path.exists(point_filename)
+            
+        os.remove(points_file)
+        
+        
+    def test_sww2csv_centroid(self):
+        
+        """Check sww2csv timeseries at centroid.
+        
+        Test the ability to get a timeseries at the centroid of a triangle, rather
+        than the given gauge point.
+        """
+        
+        domain = self.domain
+        sww = self._create_sww()
+        
+        # create a csv file containing our gauge points
+        points_file = tempfile.mktemp(".csv")
+        file_id = open(points_file,"w")
+# These values are where the centroids should be        
+#        file_id.write("name, easting, northing, elevation \n\
+#point1, 2.0, 2.0, 3.0\n\
+#point2, 4.0, 4.0, 9.0\n")
+ 
+# These values are slightly off the centroids - will it find the centroids?
+        file_id.write("name, easting, northing, elevation \n\
+point1, 2.0, 1.0, 3.0\n\
+point2, 4.5, 4.0, 9.0\n")
+
+ 
+        file_id.close()
+
+        sww2csv_gauges(self.sww.filename, 
+                       points_file,
+                       verbose=False,
+                       use_cache=False,
+                       output_centroids=True)
+
+        point1_answers_array = [[0.0,0.0,1.0,3.0,-2.0,3.0,4.0], [2.0,2.0/3600.,10.0,12.0,-2.0,3.0,4.0]]
+        point1_filename = 'gauge_point1.csv'
+        point1_handle = open(point1_filename)
+        point1_reader = reader(point1_handle)
+        point1_reader.next()
+
+        line=[]
+        for i,row in enumerate(point1_reader):
+            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
+                         float(row[4]),float(row[5]),float(row[6])])
+#           print 'assert line',line[i],'point1',point1_answers_array[i]
+            assert num.allclose(line[i], point1_answers_array[i])
+
+        point2_answers_array = [[0.0,0.0,1.0,5.0,-4.0,3.0,4.0], [2.0,2.0/3600.,10.0,14.0,-4.0,3.0,4.0]]
+        point2_filename = 'gauge_point2.csv' 
+        point2_handle = open(point2_filename)
+        point2_reader = reader(point2_handle)
+        point2_reader.next()
+                        
+        line=[]
+        for i,row in enumerate(point2_reader):
+            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
+                         float(row[4]),float(row[5]),float(row[6])])
+#           print i, 'assert line',line[i],'point2',point2_answers_array[i]
+            assert num.allclose(line[i], point2_answers_array[i])
+                         
+        # clean up
+        point1_handle.close()
+        point2_handle.close()
+        os.remove(points_file)
+        os.remove(point1_filename)
+        os.remove(point2_filename)
+
+
+    def test_sww2csv_output_centroid_attribute(self):
+        
+        """Check sww2csv timeseries at centroid, then output the centroid coordinates.
+        
+        Test the ability to get a timeseries at the centroid of a triangle, rather
+        than the given gauge point, then output the results.
+        """
+        
+        domain = self.domain        
+        self._create_sww()
+        
+        # create a csv file containing our gauge points
+        points_file = tempfile.mktemp(".csv")
+        file_id = open(points_file,"w")
+ 
+# These values are slightly off the centroids - will it find the centroids?
+        file_id.write("name, easting, northing, elevation \n\
+point1, 2.5, 4.25, 3.0\n")
+
+        file_id.close()
+
+        sww2csv_gauges(self.sww.filename, 
+                       points_file,
+                       quantities=['stage', 'xcentroid', 'ycentroid'],
+                       verbose=False,
+                       use_cache=False,
+                       output_centroids=True)
+
+        point1_answers_array = [[0.0,0.0,1.0,4.0,4.0], [2.0,2.0/3600.,10.0,4.0,4.0]]
+        point1_filename = 'gauge_point1.csv'
+        point1_handle = file(point1_filename)
+        point1_reader = reader(point1_handle)
+        point1_reader.next()
+
+        line=[]
+        for i,row in enumerate(point1_reader):
+            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),float(row[4])])
+#            print 'assert line',line[i],'point1',point1_answers_array[i]
+            assert num.allclose(line[i], point1_answers_array[i])
+
+        # clean up
+        point1_handle.close()        
+        os.remove(points_file)
+        os.remove(point1_filename)
+
+    def test_sww2csv_multiple_files(self):
+        """
+        This is testing the sww2csv_gauges function, by creating multiple 
+        sww files and then exporting the gauges and checking the results.
+        """
+        timestep=2.0
+        domain = self.domain
+        domain.set_starttime(0.)
+        # Create two sww files with timestep at end. These are to be
+        # stored consecutively in the gauge csv files
+        basename='datatest1'
+        domain.set_name(basename) 
+        self._create_sww(stage=10.,timestep=timestep)
+
+        domain.set_name(basename+str(time.time())) 
+        domain.set_time(domain.get_time()+timestep)
+        self._create_sww(stage=20.,timestep=timestep)
+
+        points_file = tempfile.mktemp(".csv")
+        file_id = open(points_file,"w")
+
+        # test the function at these points
+        points = [[5.0,1.],[0.5,2.]]
+
+        # create a csv file containing our gauge points
+        points_file = tempfile.mktemp(".csv")
+        file_id = open(points_file,"w")
+        file_id.write("name,easting,northing \n\
+point1, 5.0, 1.0\n\
+point2, 0.5, 2.0\n")
+        file_id.close()
+
+
+        sww2csv_gauges(basename+".sww", 
+                       points_file,
+                       quantities=['stage', 'elevation'],
+                       use_cache=False,
+                       verbose=False)
+
+        point1_answers_array = [[0.0,1.0,-5.0], [2.0,10.0,-5.0],[4.0,10.0,-5.0],
+                                [6.0,20.0,-5.0], [0.0,1.0,-5.0]]
+        point1_filename = 'gauge_point1.csv'
+        point1_handle = file(point1_filename)
+        point1_reader = reader(point1_handle)
+        point1_reader.next()
+
+        line=[]
+        for i,row in enumerate(point1_reader):
+            # note the 'hole' (element 1) below - skip the new 'hours' field
+            line.append([float(row[0]),float(row[2]),float(row[3])])
+            #print 'i', i
+            #print 'row',row
+            #print 'line',line[i],'point1',point1_answers_array[i]
+            assert num.allclose(line[i], point1_answers_array[i])
+
+        point2_answers_array = [[0.0,1.0,-0.5], [2.0,10.0,-0.5],[4.0,10.0,-0.5],
+                                [6.0,20.0,-0.5], [0.0,1.0,-0.5]]
+        point2_filename = 'gauge_point2.csv' 
+        point2_handle = file(point2_filename)
+        point2_reader = reader(point2_handle)
+        point2_reader.next()
+                        
+        line=[]
+        for i,row in enumerate(point2_reader):
+            # note the 'hole' (element 1) below - skip the new 'hours' field
+            line.append([float(row[0]),float(row[2]),float(row[3])])
+            #print 'line',line[i],'point2',point2_answers_array[i]
+            assert num.allclose(line[i], point2_answers_array[i])
+                         
+        # clean up
+        point1_handle.close()
+        point2_handle.close() 
+        os.remove(points_file)
+        os.remove(point1_filename)
+        os.remove(point2_filename)       
+
+        #remove second swwfile not removed by tearDown
+        os.remove(basename+".sww")
+        #os.remove(basename+str(time.time())+".sww")
+
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Gauge, 'test_')
+#    runner = unittest.TextTestRunner(verbosity=2)
+    runner = unittest.TextTestRunner(verbosity=1)
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_general_mesh.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_general_mesh.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_general_mesh.py	(revision 9460)
@@ -0,0 +1,517 @@
+#!/usr/bin/env python
+
+
+import unittest
+from math import sqrt, pi
+
+
+from anuga.config import epsilon
+from general_mesh import General_mesh
+from anuga.coordinate_transforms.geo_reference import Geo_reference
+from mesh_factory import rectangular
+from anuga.shallow_water.shallow_water_domain import Domain
+
+import numpy as num
+
+
+class Test_General_Mesh(unittest.TestCase):
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+
+    def test_get_vertex_coordinates(self):
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        nodes, triangles, _ = rectangular(1, 3)
+        domain = General_mesh(nodes, triangles)
+
+
+        assert num.allclose(domain.get_nodes(), nodes)
+
+
+        M = domain.number_of_triangles        
+
+        V = domain.get_vertex_coordinates()
+        assert V.shape[0] == 3*M
+
+        for i in range(M):
+            for j in range(3):
+                k = triangles[i,j]  #Index of vertex j in triangle i
+                assert num.allclose(V[3*i+j,:], nodes[k])
+
+    def test_get_vertex_coordinates_with_geo_ref(self):
+        x0 = 314036.58727982
+        y0 = 6224951.2960092
+        geo = Geo_reference(56, x0, y0)
+        
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+        nodes = num.array([a, b, c, d, e, f])
+
+        nodes_absolute = geo.get_absolute(nodes)
+        
+        #                        bac,     bce,     ecf,     dbe
+        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int)
+
+        domain = General_mesh(nodes, triangles, geo_reference=geo)
+
+        verts = domain.get_vertex_coordinates(triangle_id=0)    # bac
+        msg = ("num.array([b,a,c])=\n%s\nshould be close to 'verts'=\n%s"
+               % (str(num.array([b,a,c])), str(verts)))
+        self.failUnless(num.allclose(num.array([b,a,c]), verts), msg)
+
+        verts = domain.get_vertex_coordinates(triangle_id=0)       
+        msg = ("num.array([b,a,c])=\n%s\nshould be close to 'verts'=\n%s"
+               % (str(num.array([b,a,c])), str(verts)))
+        self.assert_(num.allclose(num.array([b,a,c]), verts), msg)
+
+        verts = domain.get_vertex_coordinates(triangle_id=0, absolute=True)
+        msg = ("num.array([...])=\n%s\nshould be close to 'verts'=\n%s"
+               % (str(num.array([nodes_absolute[1],
+                                 nodes_absolute[0],
+                                 nodes_absolute[2]])),
+                  str(verts)))
+        self.assert_(num.allclose(num.array([nodes_absolute[1],
+                                             nodes_absolute[0],
+                                             nodes_absolute[2]]),
+                                  verts), msg)
+
+        verts = domain.get_vertex_coordinates(triangle_id=0,
+                                              absolute=True)       
+        msg = ("num.array([...])=\n%s\nshould be close to 'verts'=\n%s"
+               % (str(num.array([nodes_absolute[1],
+                                 nodes_absolute[0],
+                                 nodes_absolute[2]])),
+                  str(verts)))
+        self.assert_(num.allclose(num.array([nodes_absolute[1],
+                                             nodes_absolute[0],
+                                             nodes_absolute[2]]),
+                                  verts), msg)
+
+    def test_get_vertex_coordinates_triangle_id(self):
+        """test_get_vertex_coordinates_triangle_id
+        Test that vertices for one triangle can be returned.
+        """
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        nodes, triangles, _ = rectangular(1, 3)
+        domain = General_mesh(nodes, triangles)
+
+
+        assert num.allclose(domain.get_nodes(), nodes)
+
+
+        M = domain.number_of_triangles        
+
+        for i in range(M):
+            V = domain.get_vertex_coordinates(triangle_id=i)
+            assert V.shape[0] == 3
+
+            for j in range(3):
+                k = triangles[i,j]  #Index of vertex j in triangle i
+                assert num.allclose(V[j,:], nodes[k])
+
+
+    def test_get_edge_midpoint_coordinates(self):
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        nodes, triangles, _ = rectangular(1, 3)
+        domain = General_mesh(nodes, triangles)
+
+
+        assert num.allclose(domain.get_nodes(), nodes)
+
+
+        M = domain.number_of_triangles        
+
+        E = domain.get_edge_midpoint_coordinates()
+        assert E.shape[0] == 3*M
+
+        for i in range(M):
+            k0 = triangles[i,0]  #Index of vertex 0 in triangle i
+            k1 = triangles[i,1]  #Index of vertex 1 in triangle i
+            k2 = triangles[i,2]  #Index of vertex 2 in triangle i
+
+            assert num.allclose(E[3*i+0,:], 0.5*(nodes[k1]+nodes[k2]) )
+            assert num.allclose(E[3*i+1,:], 0.5*(nodes[k0]+nodes[k2]) )
+            assert num.allclose(E[3*i+2,:], 0.5*(nodes[k1]+nodes[k0]) )
+
+    def test_get_edge_midpoint_coordinates_with_geo_ref(self):
+        x0 = 314036.58727982
+        y0 = 6224951.2960092
+        geo = Geo_reference(56, x0, y0)
+        
+        a = num.array([0.0, 0.0])
+        b = num.array([0.0, 2.0])
+        c = num.array([2.0, 0.0])
+        d = num.array([0.0, 4.0])
+        e = num.array([2.0, 2.0])
+        f = num.array([4.0, 0.0])
+        nodes = num.array([a, b, c, d, e, f])
+
+        nodes_absolute = geo.get_absolute(nodes)
+        
+        #                        bac,     bce,     ecf,     dbe
+        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int)
+
+        domain = General_mesh(nodes, triangles, geo_reference=geo)
+
+        verts = domain.get_edge_midpoint_coordinates(triangle_id=0)    # bac
+        msg = ("num.array(1/2[a+c,b+c,a+b])=\n%s\nshould be close to 'verts'=\n%s"
+               % (str(num.array([0.5*(a+c),0.5*(b+c),0.5*(a+b)])), str(verts)))
+        self.failUnless(num.allclose(num.array([0.5*(a+c),0.5*(b+c),0.5*(a+b)]), verts), msg)
+
+
+        verts = domain.get_edge_midpoint_coordinates(triangle_id=0, absolute=True)
+        msg = ("num.array([...])=\n%s\nshould be close to 'verts'=\n%s"
+               % (str(0.5*num.array([nodes_absolute[0]+nodes_absolute[2],
+                                     nodes_absolute[1]+nodes_absolute[2],
+                                     nodes_absolute[1]+nodes_absolute[0]])),
+                  str(verts)))
+        self.assert_(num.allclose(0.5*num.array([nodes_absolute[0]+nodes_absolute[2],
+                                                 nodes_absolute[1]+nodes_absolute[2],
+                                                 nodes_absolute[1]+nodes_absolute[0]]),
+                                  verts), msg)
+
+    def test_get_edge_midpoint_coordinates_triangle_id(self):
+        """test_get_vertex_coordinates_triangle_id
+        Test that vertices for one triangle can be returned.
+        """
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        nodes, triangles, _ = rectangular(1, 3)
+        domain = General_mesh(nodes, triangles)
+
+
+        assert num.allclose(domain.get_nodes(), nodes)
+
+
+        M = domain.number_of_triangles        
+
+        for i in range(M):
+            E = domain.get_edge_midpoint_coordinates(triangle_id=i)
+            assert E.shape[0] == 3
+
+
+            k0 = triangles[i,0]  #Index of vertex 0 in triangle i
+            k1 = triangles[i,1]  #Index of vertex 0 in triangle i
+            k2 = triangles[i,2]  #Index of vertex 0 in triangle i
+
+            assert num.allclose(E[0,:], 0.5*(nodes[k1]+nodes[k2]))
+            assert num.allclose(E[1,:], 0.5*(nodes[k0]+nodes[k2]))
+            assert num.allclose(E[2,:], 0.5*(nodes[k1]+nodes[k0]))
+
+            E0 = domain.get_edge_midpoint_coordinate(i, 0 )
+            E1 = domain.get_edge_midpoint_coordinate(i, 1 )
+            E2 = domain.get_edge_midpoint_coordinate(i, 2 )
+
+            assert num.allclose(E0, 0.5*(nodes[k1]+nodes[k2]))
+            assert num.allclose(E1, 0.5*(nodes[k0]+nodes[k2]))
+            assert num.allclose(E2, 0.5*(nodes[k1]+nodes[k0]))
+            
+
+
+        
+        
+
+    def test_get_vertex_values(self):
+        """Get connectivity based on triangle lists.
+        """
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        nodes, triangles, _ = rectangular(1, 3)
+        domain = General_mesh(nodes, triangles)
+
+        msg = ("domain.get_triangles()=\n%s\nshould be the same as "
+               "'triangles'=\n%s"
+               % (str(domain.get_triangles()), str(triangles)))
+        assert num.allclose(domain.get_triangles(), triangles), msg
+        msg = ("domain.get_triangles([0,4])=\n%s\nshould be the same as "
+               "'[triangles[0], triangles[4]]' which is\n%s"
+               % (str(domain.get_triangles([0,4])),
+                  str([triangles[0], triangles[4]])))
+        assert num.allclose(domain.get_triangles([0,4]),
+                            [triangles[0], triangles[4]]), msg
+        
+
+    def test_vertex_value_indices(self):
+        """Check that structures are correct.
+        """
+        from mesh_factory import rectangular
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        nodes = num.array([a, b, c, d, e, f])
+        #bac, bce, ecf, dbe, daf, dae
+        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+        domain1 = General_mesh(nodes, triangles)
+        
+        #Create larger mesh
+        nodes, triangles, _ = rectangular(3, 6)
+        domain2 = General_mesh(nodes, triangles)
+
+        # Test both meshes
+        for domain in [domain1, domain2]:
+            assert sum(domain.number_of_triangles_per_node) ==\
+                   len(domain.vertex_value_indices)
+
+            # Check number of triangles per node
+            count = [0]*domain.number_of_nodes
+            for triangle in domain.triangles:
+                for i in triangle:
+                    count[i] += 1
+
+            #print count
+            #
+            assert num.allclose(count, domain.number_of_triangles_per_node)
+            
+            # Check indices
+            current_node = 0
+            k = 0 # Track triangles touching on node
+            for index in domain.vertex_value_indices:
+                k += 1
+                
+                triangle = index / 3
+                vertex = index % 3
+
+                assert domain.triangles[triangle, vertex] == current_node
+
+                if domain.number_of_triangles_per_node[current_node] == k:
+                    # Move on to next node
+                    k = 0
+                    current_node += 1
+                
+
+    def test_get_triangles_and_vertices_per_node(self):
+        """test_get_triangles_and_vertices_per_node -
+
+        Test that tuples of triangle, vertex can be extracted
+        from inverted triangles structure
+
+        """
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        nodes = num.array([a, b, c, d, e, f])
+        #bac, bce, ecf, dbe, daf, dae
+        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+        domain = General_mesh(nodes, triangles)
+
+        # One node
+        L = domain.get_triangles_and_vertices_per_node(node=2)
+        assert num.allclose(L[0], [0, 2])
+        assert num.allclose(L[1], [1, 1])
+        assert num.allclose(L[2], [2, 1])
+
+        # All nodes
+        ALL = domain.get_triangles_and_vertices_per_node()
+        assert len(ALL) == 6
+        for i, Lref in enumerate(ALL):
+            L = domain.get_triangles_and_vertices_per_node(node=i)
+            assert num.allclose(L, Lref)
+            
+
+        
+
+        
+
+
+    def test_areas(self):
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+        domain = General_mesh(points, vertices)        
+
+        assert domain.get_area() == 1.0
+        
+        
+        
+    def test_one_degenerate_triangles(self):
+
+        
+        a = num.array([1.0, 1.0])
+        b = num.array([0.0, 2.0])
+        c = num.array([2.0, 0.0])
+        d = num.array([0.0, 4.0])
+        e = num.array([2.0, 2.0])
+        f = num.array([4.0, 0.0])
+        nodes = num.array([a, b, c, d, e, f])
+
+        
+        #                        bac,     bce,     ecf,     dbe
+        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int)
+
+        try:
+            domain = General_mesh(nodes, triangles)
+        except AssertionError:
+            #print 'excepted assertion error'
+            pass
+            
+            
+
+    def test_two_degenerate_triangles(self):
+
+        
+        a = num.array([1.0, 1.0])
+        b = num.array([0.0, 2.0])
+        c = num.array([2.0, 0.0])
+        d = num.array([1.0, 2.0])
+        e = num.array([2.0, 2.0])
+        f = num.array([4.0, 0.0])
+        nodes = num.array([a, b, c, d, e, f])
+
+        #                        bac,     bce,     ecf,     dbe
+        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int)
+
+        
+        try:
+            domain = General_mesh(nodes, triangles)
+        except AssertionError:
+            #print 'excepted assertion error'
+            pass
+
+
+
+
+    def test_get_unique_vertex_values(self):
+        """
+        get unique_vertex based on triangle lists.
+        """
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+        domain = General_mesh(points, vertices)                
+
+        assert  domain.get_unique_vertices() == [0,1,2,3,4,5,6,7]
+        unique_vertices = domain.get_unique_vertices([0,1,4])
+        unique_vertices.sort()
+        assert unique_vertices == [0,1,2,4,5,6,7]
+
+        unique_vertices = domain.get_unique_vertices([0,4])
+        unique_vertices.sort()
+        assert unique_vertices == [0,2,4,5,6,7]
+
+    def test_get_node(self):
+        """test_get_triangles_and_vertices_per_node -
+
+        Test that tuples of triangle, vertex can be extracted
+        from inverted triangles structure
+
+        """
+        
+        x0 = 314036.58727982
+        y0 = 6224951.2960092
+        geo = Geo_reference(56, x0, y0)
+        
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        nodes = num.array([a, b, c, d, e, f])
+
+        nodes_absolute = geo.get_absolute(nodes)
+        
+        #                        bac,     bce,     ecf,     dbe
+        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+        domain = General_mesh(nodes, triangles, geo_reference = geo)
+        node = domain.get_node(2)        
+        msg = ('\nc=%s\nnode=%s' % (str(c), str(node)))
+        self.failUnless(num.alltrue(c == node), msg)
+
+        # repeat get_node(), see if result same
+        node = domain.get_node(2)        
+        msg = ('\nc=%s\nnode=%s' % (str(c), str(node)))
+        self.failUnless(num.alltrue(c == node), msg)
+        
+        node = domain.get_node(2, absolute=True)     
+        msg = ('\nnodes_absolute[2]=%s\nnode=%s'
+               % (str(nodes_absolute[2]), str(node)))
+        self.failUnless(num.alltrue(nodes_absolute[2] == node), msg)
+       
+        # repeat get_node(2, absolute=True), see if result same
+        node = domain.get_node(2, absolute=True)     
+        msg = ('\nnodes_absolute[2]=%s\nnode=%s'
+               % (str(nodes_absolute[2]), str(node)))
+        self.failUnless(num.alltrue(nodes_absolute[2] == node), msg)
+        
+
+    def test_assert_index_in_nodes(self):
+        """test_assert_index_in_nodes -
+
+        Test that node indices in triangles are within nodes array.
+
+        """
+        
+        x0 = 314036.58727982
+        y0 = 6224951.2960092
+        geo = Geo_reference(56, x0, y0)
+        
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        nodes = num.array([a, b, c, d, e, f])
+
+        nodes_absolute = geo.get_absolute(nodes)
+        
+        # max index is 5, use 5, expect success
+        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+        General_mesh(nodes, triangles, geo_reference=geo)
+        
+        
+        # should fail with negative area
+        triangles = num.array([[0,1,2], [1,2,4], [4,2,5], [3,1,4]])
+        self.failUnlessRaises(AssertionError, General_mesh, 
+                              nodes, triangles, geo_reference=geo)
+
+        
+        # max index is 5, use 6, expect assert failure
+        triangles = num.array([[1,6,2], [1,2,4], [4,2,5], [3,1,4]])
+        self.failUnlessRaises(AssertionError, General_mesh,
+                              nodes, triangles, geo_reference=geo)
+        
+
+        
+        # max index is 5, use 10, expect assert failure
+        triangles = num.array([[1,10,2], [1,2,4], [4,2,5], [3,1,4]])
+        self.failUnlessRaises(AssertionError, General_mesh,
+                              nodes, triangles, geo_reference=geo)
+
+################################################################################
+
+if __name__ == "__main__":
+    #suite = unittest.makeSuite(Test_General_Mesh, 'test')
+    suite = unittest.makeSuite(Test_General_Mesh, 'test')     
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
+
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_generic_boundary_conditions.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_generic_boundary_conditions.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_generic_boundary_conditions.py	(revision 9460)
@@ -0,0 +1,437 @@
+#!/usr/bin/env python
+"""
+    Generic boundary conditions for a domain.
+    
+    A boundary represents the edge of the model, where inflow, outflow, and
+    reflection can take place.
+    
+    The boundaries in this model can be applied universally across all
+    domain models, without being tied to a particular implementation.
+"""
+
+import unittest
+from math import sqrt, pi
+
+from anuga.abstract_2d_finite_volumes.generic_boundary_conditions import *
+from anuga.abstract_2d_finite_volumes.generic_domain import Generic_Domain
+from anuga.config import epsilon
+
+import numpy as num
+
+
+class Test_Generic_Boundary_Conditions(unittest.TestCase):
+    def setUp(self):
+        pass
+        #print "  Setting up"
+
+    def tearDown(self):
+        pass
+        #print "  Tearing down"
+
+
+    def test_generic(self):
+        b = Boundary()
+
+        try:
+            b.evaluate()
+        except:
+            pass
+        else:
+            raise Exception('Should have raised exception')
+
+
+    def test_dirichlet_empty(self):
+
+        try:
+            Bd = Dirichlet_boundary()
+        except:
+            pass
+        else:
+            raise Exception('Should have raised exception')
+
+    def test_dirichlet(self):
+        x = [3.14,0,0.1]
+        Bd = Dirichlet_boundary(x)
+
+        q = Bd.evaluate()
+        assert num.allclose(q, x)
+
+
+    def test_time(self):
+        from quantity import Quantity
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        domain = Generic_Domain(points, elements)
+        domain.check_integrity()
+
+        domain.conserved_quantities = ['stage', 'ymomentum']
+        domain.evolved_quantities = ['stage', 'ymomentum']        
+        domain.quantities['stage'] =\
+                                   Quantity(domain, [[1,2,3], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+        domain.quantities['ymomentum'] =\
+                                   Quantity(domain, [[2,3,4], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+
+        domain.check_integrity()
+
+        #Test time bdry, you need to provide a domain and function
+        try:
+            T = Time_boundary(domain)
+        except:
+            pass
+        else:
+            raise Exception('Should have raised exception')
+
+        #Test time bdry, you need to provide a function
+        try:
+            T = Time_boundary()
+        except:
+            pass
+        else:
+            raise Exception('Should have raised exception')
+
+
+        def function(t):
+            return [1.0, 0.0]
+        
+        T = Time_boundary(domain, function)
+
+        from anuga.config import default_boundary_tag
+        domain.set_boundary( {default_boundary_tag: T} )
+
+
+        #FIXME: should not necessarily be true always.
+        #E.g. with None as a boundary object.
+        assert len(domain.boundary) == len(domain.boundary_objects)
+
+        q = T.evaluate(0, 2)  #Vol=0, edge=2
+
+        assert num.allclose(q, [1.0, 0.0])
+
+
+    def test_time_space_boundary(self):
+        from quantity import Quantity
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        domain = Generic_Domain(points, elements)
+        domain.check_integrity()
+
+        domain.conserved_quantities = ['stage', 'ymomentum']
+        domain.evolved_quantities = ['stage', 'ymomentum']        
+        domain.quantities['stage'] =\
+                                   Quantity(domain, [[1,2,3], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+        domain.quantities['ymomentum'] =\
+                                   Quantity(domain, [[2,3,4], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+
+        domain.check_integrity()
+
+        #Test time space bdry, you need to provide a domain and function
+        try:
+            T = Time_space_boundary(domain)
+        except:
+            pass
+        else:
+            raise Exception('Should have raised exception')
+
+        #Test time bdry, you need to provide a function
+        try:
+            T = Time_space_boundary()
+        except:
+            pass
+        else:
+            raise Exception('Should have raised exception')
+
+
+        def function(t,x,y):
+            return [x,y]
+        
+        T = Time_space_boundary(domain, function)
+
+        from anuga.config import default_boundary_tag
+        domain.set_boundary( {default_boundary_tag: T} )
+
+
+        #FIXME: should not necessarily be true always.
+        #E.g. with None as a boundary object.
+        assert len(domain.boundary) == len(domain.boundary_objects)
+
+        q = T.evaluate(0, 2)  #Vol=0, edge=2
+        assert num.allclose(q, domain.get_edge_midpoint_coordinate(0,2))
+
+
+        q = T.evaluate(1, 1)  #Vol=1, edge=1
+        assert num.allclose(q, domain.get_edge_midpoint_coordinate(1,1))        
+
+
+
+
+
+    def test_transmissive(self):
+        from quantity import Quantity
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        domain = Generic_Domain(points, elements)
+        domain.check_integrity()
+
+        domain.conserved_quantities = ['stage', 'ymomentum']
+        domain.evolved_quantities = ['stage', 'ymomentum']        
+        domain.quantities['stage'] =\
+                                   Quantity(domain, [[1,2,3], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+        domain.quantities['ymomentum'] =\
+                                   Quantity(domain, [[2,3,4], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+
+        domain.check_integrity()
+
+        #Test transmissve bdry
+        try:
+            T = Transmissive_boundary()
+        except:
+            pass
+        else:
+            raise Exception('Should have raised exception')
+
+        T = Transmissive_boundary(domain)
+
+        from anuga.config import default_boundary_tag
+        domain.set_boundary( {default_boundary_tag: T} )
+
+
+        #FIXME: should not necessarily be true always.
+        #E.g. with None as a boundary object.
+        assert len(domain.boundary) == len(domain.boundary_objects)
+
+        q = T.evaluate(0, 2)  #Vol=0, edge=2
+
+        assert num.allclose(q, [1.5, 2.5])
+
+
+        # Now set the centroid_transmissive_bc flag to true
+        domain.set_centroid_transmissive_bc(True)
+
+        q = T.evaluate(0, 2)  #Vol=0, edge=2
+
+        assert num.allclose(q, [2.0 ,3.0]) # centroid value
+
+
+
+        
+
+    def NOtest_fileboundary_time_only(self):
+        """Test that boundary values can be read from file and interpolated
+        This is using the .tms file format
+        
+        See also test_util for comprenhensive testing of the underlying 
+        file_function and also tests in test_datamanager which tests 
+        file_function using the sts format
+        """
+        #FIXME (Ole): This test was disabled 18 August 2008 as no
+        # need for this was found. Rather I implemented an Exception
+        # to catch possible errors in the model setup
+        
+        from quantity import Quantity
+        import time, os
+        from math import sin, pi
+        from anuga.config import time_format
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        domain = Generic_Domain(points, elements)
+        domain.conserved_quantities = ['stage', 'ymomentum']
+        domain.quantities['stage'] =\
+                                   Quantity(domain, [[1,2,3], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+        domain.quantities['ymomentum'] =\
+                                   Quantity(domain, [[2,3,4], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+        domain.check_integrity()
+
+
+        #Write file
+        filename = 'boundarytest' + str(time.time())
+        fid = open(filename + '.txt', 'w')
+        start = time.mktime(time.strptime('2000', '%Y'))
+        dt = 5*60  #Five minute intervals
+        for i in range(10):
+            t = start + i*dt
+            t_string = time.strftime(time_format, time.gmtime(t))
+
+            fid.write('%s,%f %f\n' %(t_string, 1.0*i, sin(i*2*pi/10)))
+        fid.close()
+
+
+        #Convert ASCII file to NetCDF (Which is what we really like!)
+        
+        from anuga.shallow_water.data_manager import timefile2netcdf
+        
+        timefile2netcdf(filename, quantity_names = ['stage', 'ymomentum'])
+        
+
+
+        F = File_boundary(filename + '.tms', domain)
+
+        
+        os.remove(filename + '.txt')
+        os.remove(filename + '.tms')        
+
+
+        
+
+        #Check that midpoint coordinates at boundary are correctly computed
+        assert num.allclose( F.midpoint_coordinates,
+                             [[1.0, 0.0], [0.0, 1.0], [3.0, 0.0],
+                              [3.0, 1.0], [1.0, 3.0], [0.0, 3.0]])
+
+        #assert allclose(F.midpoint_coordinates[(3,2)], [0.0, 3.0])
+        #assert allclose(F.midpoint_coordinates[(3,1)], [1.0, 3.0])
+        #assert allclose(F.midpoint_coordinates[(0,2)], [0.0, 1.0])
+        #assert allclose(F.midpoint_coordinates[(0,0)], [1.0, 0.0])
+        #assert allclose(F.midpoint_coordinates[(2,0)], [3.0, 0.0])
+        #assert allclose(F.midpoint_coordinates[(2,1)], [3.0, 1.0])
+
+
+        #Check time interpolation
+        from anuga.config import default_boundary_tag
+        domain.set_boundary( {default_boundary_tag: F} )
+
+        domain.time = 5*30/2  #A quarter way through first step
+        q = F.evaluate()
+        assert num.allclose(q, [1.0/4, sin(2*pi/10)/4])
+
+
+        domain.time = 2.5*5*60  #Half way between steps 2 and 3
+        q = F.evaluate()
+        assert num.allclose(q, [2.5, (sin(2*2*pi/10) + sin(3*2*pi/10))/2])
+
+
+
+    def test_fileboundary_exception(self):
+        """Test that boundary object complains if number of
+        conserved quantities are wrong
+        """
+
+        from quantity import Quantity
+        import time, os
+        from math import sin, pi
+        from anuga.config import time_format
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        domain = Generic_Domain(points, elements)
+        domain.conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
+        domain.evolved_quantities = ['stage', 'xmomentum', 'ymomentum']
+        domain.quantities['stage'] =\
+                                   Quantity(domain, [[1,2,3], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+        domain.quantities['xmomentum'] =\
+                                   Quantity(domain, [[2,3,4], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+        domain.quantities['ymomentum'] =\
+                                   Quantity(domain, [[2,3,4], [5,5,5],
+                                                     [0,0,9], [-6, 3, 3]])
+
+        domain.check_integrity()
+
+        #Write file (with only two values)
+        filename = 'boundarytest' + str(time.time())
+        fid = open(filename + '.txt', 'w')
+        start = time.mktime(time.strptime('2000', '%Y'))
+        dt = 5*60  #Five minute intervals
+        for i in range(10):
+            t = start + i*dt
+            t_string = time.strftime(time_format, time.gmtime(t))
+
+            fid.write('%s,%f %f\n' %(t_string, 1.0*i, sin(i*2*pi/10)))
+        fid.close()
+
+
+        #Convert ASCII file to NetCDF (Which is what we really like!)
+        from anuga.file_conversion.file_conversion import timefile2netcdf
+        
+        timefile2netcdf(filename+'.txt', quantity_names = ['stage', 'xmomentum'])
+
+        
+        try:
+            F = File_boundary(filename + '.tms',
+                              domain)
+        except:
+            pass
+        else:
+            raise Exception('Should have raised an exception')
+        
+        os.remove(filename + '.txt')
+        os.remove(filename + '.tms')        
+
+
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Generic_Boundary_Conditions, 'test')
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_generic_domain.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_generic_domain.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_generic_domain.py	(revision 9460)
@@ -0,0 +1,902 @@
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt
+
+import anuga
+
+from anuga.abstract_2d_finite_volumes.generic_domain import *
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.config import epsilon
+import numpy as num
+from anuga.pmesh.mesh import Segment, Vertex, Mesh
+
+
+def add_to_verts(tag, elements, domain):
+    if tag == "mound":
+        domain.test = "Mound"
+
+
+
+class Test_Domain(unittest.TestCase):
+    def setUp(self):
+        pass
+
+
+    def tearDown(self):
+        pass
+
+
+    def test_simple(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
+        evolved_quantities = ['stage', 'xmomentum', 'ymomentum', 'xvelocity']
+        
+        other_quantities = ['elevation', 'friction']
+
+        domain = Generic_Domain(points, vertices, None,
+                        conserved_quantities, evolved_quantities, other_quantities)
+        domain.check_integrity()
+
+        for name in conserved_quantities + other_quantities:
+            assert domain.quantities.has_key(name)
+
+
+        assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.)
+
+
+
+    def test_CFL(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
+        evolved_quantities = ['stage', 'xmomentum', 'ymomentum', 'xvelocity']
+        
+        other_quantities = ['elevation', 'friction']
+
+        domain = Generic_Domain(points, vertices, None,
+                        conserved_quantities, evolved_quantities, other_quantities)
+
+        try:
+            domain.set_CFL(-0.1)
+        except:
+            pass
+        else:
+            msg = 'Should have caught a negative cfl'
+            raise Exception, msg
+
+
+        
+        try:
+            domain.set_CFL(3.0)
+        except:
+            pass
+        else:
+            msg = 'Should have warned of cfl>2.0'
+            raise Exception, msg
+
+        assert domain.CFL == 3.0
+        
+
+    def test_conserved_quantities(self):
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        domain = Generic_Domain(points, vertices, boundary=None,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'])
+
+
+        domain.set_quantity('stage', [[1,2,3], [5,5,5],
+                                      [0,0,9], [-6, 3, 3]])
+
+        domain.set_quantity('xmomentum', [[1,2,3], [5,5,5],
+                                          [0,0,9], [-6, 3, 3]])
+
+        domain.check_integrity()
+
+        #Centroids
+        q = domain.get_conserved_quantities(0)
+        assert num.allclose(q, [2., 2., 0.])
+
+        q = domain.get_conserved_quantities(1)
+        assert num.allclose(q, [5., 5., 0.])
+
+        q = domain.get_conserved_quantities(2)
+        assert num.allclose(q, [3., 3., 0.])
+
+        q = domain.get_conserved_quantities(3)
+        assert num.allclose(q, [0., 0., 0.])
+
+
+        #Edges
+        q = domain.get_conserved_quantities(0, edge=0)
+        assert num.allclose(q, [2.5, 2.5, 0.])
+        q = domain.get_conserved_quantities(0, edge=1)
+        assert num.allclose(q, [2., 2., 0.])
+        q = domain.get_conserved_quantities(0, edge=2)
+        assert num.allclose(q, [1.5, 1.5, 0.])
+
+        for i in range(3):
+            q = domain.get_conserved_quantities(1, edge=i)
+            assert num.allclose(q, [5, 5, 0.])
+
+
+        q = domain.get_conserved_quantities(2, edge=0)
+        assert num.allclose(q, [4.5, 4.5, 0.])
+        q = domain.get_conserved_quantities(2, edge=1)
+        assert num.allclose(q, [4.5, 4.5, 0.])
+        q = domain.get_conserved_quantities(2, edge=2)
+        assert num.allclose(q, [0., 0., 0.])
+
+
+        q = domain.get_conserved_quantities(3, edge=0)
+        assert num.allclose(q, [3., 3., 0.])
+        q = domain.get_conserved_quantities(3, edge=1)
+        assert num.allclose(q, [-1.5, -1.5, 0.])
+        q = domain.get_conserved_quantities(3, edge=2)
+        assert num.allclose(q, [-1.5, -1.5, 0.])
+
+
+
+    def test_create_quantity_from_expression(self):
+        """Quantity created from other quantities using arbitrary expression
+
+        """
+
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        domain = Generic_Domain(points, vertices, boundary=None,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'],
+                        other_quantities = ['elevation', 'friction'])
+
+
+        domain.set_quantity('elevation', -1)
+
+
+        domain.set_quantity('stage', [[1,2,3], [5,5,5],
+                                      [0,0,9], [-6, 3, 3]])
+
+        domain.set_quantity('xmomentum', [[1,2,3], [5,5,5],
+                                          [0,0,9], [-6, 3, 3]])
+
+        domain.set_quantity('ymomentum', [[3,3,3], [4,2,1],
+                                          [2,4,-1], [1, 0, 1]])
+
+        domain.check_integrity()
+
+
+
+        expression = 'stage - elevation'
+        Q = domain.create_quantity_from_expression(expression)
+
+        assert num.allclose(Q.vertex_values, [[2,3,4], [6,6,6],
+                                              [1,1,10], [-5, 4, 4]])
+
+        expression = '(xmomentum*xmomentum + ymomentum*ymomentum)**0.5'
+        Q = domain.create_quantity_from_expression(expression)
+
+        X = domain.quantities['xmomentum'].vertex_values
+        Y = domain.quantities['ymomentum'].vertex_values
+
+        assert num.allclose(Q.vertex_values, (X**2 + Y**2)**0.5)
+
+
+
+    def test_set_quanitities_to_be_monitored(self):
+        """test_set_quanitities_to_be_monitored
+        """
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+
+        domain = Generic_Domain(points, vertices, boundary=None,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'],
+                        other_quantities = ['elevation', 'friction', 'depth'])
+
+
+        assert domain.quantities_to_be_monitored is None
+        domain.set_quantities_to_be_monitored(['stage', 'stage-elevation'])
+        assert len(domain.quantities_to_be_monitored) == 2
+        assert domain.quantities_to_be_monitored.has_key('stage')
+        assert domain.quantities_to_be_monitored.has_key('stage-elevation')
+        for key in domain.quantities_to_be_monitored['stage'].keys():
+            assert domain.quantities_to_be_monitored['stage'][key] is None
+
+
+        # Check that invalid requests are dealt with
+        try:
+            domain.set_quantities_to_be_monitored(['yyyyy'])        
+        except:
+            pass
+        else:
+            msg = 'Should have caught illegal quantity'
+            raise Exception, msg
+
+        try:
+            domain.set_quantities_to_be_monitored(['stage-xx'])        
+        except NameError:
+            pass
+        else:
+            msg = 'Should have caught illegal quantity'
+            raise Exception, msg
+
+        try:
+            domain.set_quantities_to_be_monitored('stage', 'stage-elevation')
+        except:
+            pass
+        else:
+            msg = 'Should have caught too many arguments'
+            raise Exception, msg
+
+        try:
+            domain.set_quantities_to_be_monitored('stage', 'blablabla')
+        except:
+            pass
+        else:
+            msg = 'Should have caught polygon as a string'
+            raise Exception, msg        
+
+
+
+        # Now try with a polygon restriction
+        domain.set_quantities_to_be_monitored('xmomentum',
+                                              polygon=[[1,1], [1,3], [3,3], [3,1]],
+                                              time_interval = [0,3])
+        assert domain.monitor_indices[0] == 1
+        assert domain.monitor_time_interval[0] == 0
+        assert domain.monitor_time_interval[1] == 3        
+        
+
+    def test_set_quantity_from_expression(self):
+        """Quantity set using arbitrary expression
+
+        """
+
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        domain = Generic_Domain(points, vertices, boundary=None,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'],
+                        other_quantities = ['elevation', 'friction', 'depth'])
+
+
+        domain.set_quantity('elevation', -1)
+
+
+        domain.set_quantity('stage', [[1,2,3], [5,5,5],
+                                      [0,0,9], [-6, 3, 3]])
+
+        domain.set_quantity('xmomentum', [[1,2,3], [5,5,5],
+                                          [0,0,9], [-6, 3, 3]])
+
+        domain.set_quantity('ymomentum', [[3,3,3], [4,2,1],
+                                          [2,4,-1], [1, 0, 1]])
+
+
+
+
+        domain.set_quantity('depth', expression = 'stage - elevation')
+
+        domain.check_integrity()
+
+
+
+
+        Q = domain.quantities['depth']
+
+        assert num.allclose(Q.vertex_values, [[2,3,4], [6,6,6],
+                                              [1,1,10], [-5, 4, 4]])
+
+
+
+                                      
+    def test_add_quantity(self):
+        """Test that quantities already set can be added to using
+        add_quantity
+
+        """
+
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        domain = Generic_Domain(points, vertices, boundary=None,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'],
+                        other_quantities = ['elevation', 'friction', 'depth'])
+
+
+        A = num.array([[1,2,3], [5,5,-5], [0,0,9], [-6,3,3]], num.float)
+        B = num.array([[2,4,4], [3,2,1], [6,-3,4], [4,5,-1]], num.float)
+        
+        # Shorthands
+        stage = domain.quantities['stage']
+        elevation = domain.quantities['elevation']
+        depth = domain.quantities['depth']
+        
+        # Go testing
+        domain.set_quantity('elevation', A)
+        domain.add_quantity('elevation', B)
+        assert num.allclose(elevation.vertex_values, A+B)
+        
+        domain.add_quantity('elevation', 4)
+        assert num.allclose(elevation.vertex_values, A+B+4)        
+        
+        
+        # Test using expression
+        domain.set_quantity('stage', [[1,2,3], [5,5,5],
+                                      [0,0,9], [-6, 3, 3]])        
+        domain.set_quantity('depth', 1.0)                                     
+        domain.add_quantity('depth', expression = 'stage - elevation')        
+        assert num.allclose(depth.vertex_values, stage.vertex_values-elevation.vertex_values+1)
+                
+        
+        # Check self referential expression
+        reference = 2*stage.vertex_values - depth.vertex_values 
+        domain.add_quantity('stage', expression = 'stage - depth')                
+        assert num.allclose(stage.vertex_values, reference)        
+                                      
+
+        # Test using a function
+        def f(x, y):
+            return x+y
+            
+        domain.set_quantity('elevation', f)            
+        domain.set_quantity('stage', 5.0)
+        domain.set_quantity('depth', expression = 'stage - elevation')
+        
+        domain.add_quantity('depth', f)
+        assert num.allclose(stage.vertex_values, depth.vertex_values)                
+         
+            
+                                      
+                                      
+    def test_setting_timestepping_method(self):
+        """test_setting_timestepping_method
+        """
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+
+        domain = Generic_Domain(points, vertices, boundary=None,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'],
+                        other_quantities = ['elevation', 'friction', 'depth'])
+
+
+        domain.timestepping_method = None
+
+
+        # Check that invalid requests are dealt with
+        try:
+            domain.set_timestepping_method('eee')        
+        except:
+            pass
+        else:
+            msg = 'Should have caught illegal method'
+            raise Exception, msg
+
+
+        #Should have no trouble with euler, rk2 or rk3
+        domain.set_timestepping_method('euler')
+        domain.set_timestepping_method('rk2')
+        domain.set_timestepping_method('rk3')
+
+        domain.set_timestepping_method(1)
+        domain.set_timestepping_method(2)
+        domain.set_timestepping_method(3)
+        # Since rk3 was just set, check if the number of substeps is correct
+        assert domain.timestep_fluxcalls == 3
+
+        #test get timestepping method
+        assert domain.get_timestepping_method() == 'rk3'
+
+
+
+    def test_boundary_indices(self):
+
+        from anuga.config import default_boundary_tag
+
+
+        a = [0.0, 0.5]
+        b = [0.0, 0.0]
+        c = [0.5, 0.5]
+
+        points = [a, b, c]
+        vertices = [ [0,1,2] ]
+        domain = Generic_Domain(points, vertices)
+
+        domain.set_boundary( \
+                {default_boundary_tag: anuga.Dirichlet_boundary([5,2,1])} )
+
+
+        domain.check_integrity()
+
+        assert num.allclose(domain.neighbours, [[-1,-2,-3]])
+
+
+
+    def test_boundary_conditions(self):
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+        boundary = { (0, 0): 'First',
+                     (0, 2): 'First',
+                     (2, 0): 'Second',
+                     (2, 1): 'Second',
+                     (3, 1): 'Second',
+                     (3, 2): 'Second'}
+
+
+        domain = Generic_Domain(points, vertices, boundary,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'])
+        domain.check_integrity()
+
+
+
+        domain.set_quantity('stage', [[1,2,3], [5,5,5],
+                                      [0,0,9], [-6, 3, 3]])
+
+
+        domain.set_boundary( {'First': anuga.Dirichlet_boundary([5,2,1]),
+                              'Second': anuga.Transmissive_boundary(domain)} )
+
+        domain.update_boundary()
+
+        assert domain.quantities['stage'].boundary_values[0] == 5. #Dirichlet
+        assert domain.quantities['stage'].boundary_values[1] == 5. #Dirichlet
+        assert domain.quantities['stage'].boundary_values[2] ==\
+               domain.get_conserved_quantities(2, edge=0)[0] #Transmissive (4.5)
+        assert domain.quantities['stage'].boundary_values[3] ==\
+               domain.get_conserved_quantities(2, edge=1)[0] #Transmissive (4.5)
+        assert domain.quantities['stage'].boundary_values[4] ==\
+               domain.get_conserved_quantities(3, edge=1)[0] #Transmissive (-1.5)
+        assert domain.quantities['stage'].boundary_values[5] ==\
+               domain.get_conserved_quantities(3, edge=2)[0] #Transmissive (-1.5)
+
+        #Check enumeration
+        for k, ((vol_id, edge_id), _) in enumerate(domain.boundary_objects):
+            assert domain.neighbours[vol_id, edge_id] == -k-1
+
+
+
+
+    def test_conserved_evolved_boundary_conditions(self):
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+        boundary = { (0, 0): 'First',
+                     (0, 2): 'First',
+                     (2, 0): 'Second',
+                     (2, 1): 'Second',
+                     (3, 1): 'Second',
+                     (3, 2): 'Second'}
+
+
+ 
+        try:
+            domain = Generic_Domain(points, vertices, boundary,
+                            conserved_quantities = ['stage', 'xmomentum', 'ymomentum'],
+                            evolved_quantities =\
+                                   ['stage', 'xmomentum', 'xvelocity', 'ymomentum', 'yvelocity'])
+        except:
+            pass
+        else:
+            msg = 'Should have caught the evolved quantities not being in order'
+            raise Exception, msg            
+
+
+        domain = Generic_Domain(points, vertices, boundary,
+                        conserved_quantities = ['stage', 'xmomentum', 'ymomentum'],
+                        evolved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum', 'xvelocity', 'yvelocity'])
+
+
+        domain.set_quantity('stage', [[1,2,3], [5,5,5],
+                                      [0,0,9], [6, -3, 3]])
+
+
+        domain.set_boundary( {'First': anuga.Dirichlet_boundary([5,2,1,4,6]),
+                              'Second': anuga.Transmissive_boundary(domain)} )
+
+#        try:
+#            domain.update_boundary()
+#        except:
+#            pass
+#        else:
+#            msg = 'Should have caught the lack of conserved_values_to_evolved_values member function'
+#            raise Exception, msg
+
+        domain.update_boundary()
+
+        def  conserved_values_to_evolved_values(q_cons, q_evol):
+
+            q_evol[0:3] = q_cons
+            q_evol[3] = q_cons[1]/q_cons[0]
+            q_evol[4] = q_cons[2]/q_cons[0]
+
+            return q_evol
+
+        domain.conserved_values_to_evolved_values = conserved_values_to_evolved_values
+
+        domain.update_boundary()
+
+
+        assert domain.quantities['stage'].boundary_values[0] == 5. #Dirichlet
+        assert domain.quantities['stage'].boundary_values[1] == 5. #Dirichlet
+        assert domain.quantities['xvelocity'].boundary_values[0] == 4. #Dirichlet
+        assert domain.quantities['yvelocity'].boundary_values[1] == 6. #Dirichlet
+
+        q_cons = domain.get_conserved_quantities(2, edge=0) #Transmissive
+        assert domain.quantities['stage'    ].boundary_values[2] == q_cons[0]
+        assert domain.quantities['xmomentum'].boundary_values[2] == q_cons[1]
+        assert domain.quantities['ymomentum'].boundary_values[2] == q_cons[2]
+        assert domain.quantities['xvelocity'].boundary_values[2] == q_cons[1]/q_cons[0]
+        assert domain.quantities['yvelocity'].boundary_values[2] == q_cons[2]/q_cons[0]
+
+        q_cons = domain.get_conserved_quantities(2, edge=1) #Transmissive
+        assert domain.quantities['stage'    ].boundary_values[3] == q_cons[0]
+        assert domain.quantities['xmomentum'].boundary_values[3] == q_cons[1]
+        assert domain.quantities['ymomentum'].boundary_values[3] == q_cons[2]
+        assert domain.quantities['xvelocity'].boundary_values[3] == q_cons[1]/q_cons[0]
+        assert domain.quantities['yvelocity'].boundary_values[3] == q_cons[2]/q_cons[0]        
+
+
+        q_cons = domain.get_conserved_quantities(3, edge=1) #Transmissive
+        assert domain.quantities['stage'    ].boundary_values[4] == q_cons[0]
+        assert domain.quantities['xmomentum'].boundary_values[4] == q_cons[1]
+        assert domain.quantities['ymomentum'].boundary_values[4] == q_cons[2]
+        assert domain.quantities['xvelocity'].boundary_values[4] == q_cons[1]/q_cons[0]
+        assert domain.quantities['yvelocity'].boundary_values[4] == q_cons[2]/q_cons[0]               
+
+
+        q_cons = domain.get_conserved_quantities(3, edge=2) #Transmissive
+        assert domain.quantities['stage'    ].boundary_values[5] == q_cons[0]
+        assert domain.quantities['xmomentum'].boundary_values[5] == q_cons[1]
+        assert domain.quantities['ymomentum'].boundary_values[5] == q_cons[2]
+        assert domain.quantities['xvelocity'].boundary_values[5] == q_cons[1]/q_cons[0]
+        assert domain.quantities['yvelocity'].boundary_values[5] == q_cons[2]/q_cons[0]
+ 
+
+    def test_distribute_first_order(self):
+        """Domain implements a default first order gradient limiter
+        """
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+        boundary = { (0, 0): 'Third',
+                     (0, 2): 'First',
+                     (2, 0): 'Second',
+                     (2, 1): 'Second',
+                     (3, 1): 'Second',
+                     (3, 2): 'Third'}
+
+
+        domain = Generic_Domain(points, vertices, boundary,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'])
+        domain.set_default_order(1)
+        domain.check_integrity()
+
+
+        domain.set_quantity('stage', [[1,2,3], [5,5,5],
+                                      [0,0,9], [-6, 3, 3]])
+
+        assert num.allclose( domain.quantities['stage'].centroid_values,
+                             [2,5,3,0] )
+
+        domain.set_quantity('xmomentum', [[1,1,1], [2,2,2],
+                                          [3,3,3], [4, 4, 4]])
+
+        domain.set_quantity('ymomentum', [[10,10,10], [20,20,20],
+                                          [30,30,30], [40, 40, 40]])
+
+
+        domain.distribute_to_vertices_and_edges()
+
+        #First order extrapolation
+        assert num.allclose( domain.quantities['stage'].vertex_values,
+                             [[ 2.,  2.,  2.],
+                              [ 5.,  5.,  5.],
+                              [ 3.,  3.,  3.],
+                              [ 0.,  0.,  0.]])
+
+
+
+
+    def test_update_conserved_quantities(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+        boundary = { (0, 0): 'Third',
+                     (0, 2): 'First',
+                     (2, 0): 'Second',
+                     (2, 1): 'Second',
+                     (3, 1): 'Second',
+                     (3, 2): 'Third'}
+
+
+        domain = Generic_Domain(points, vertices, boundary,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'])
+        domain.check_integrity()
+
+
+        domain.set_quantity('stage', [1,2,3,4], location='centroids')
+        domain.set_quantity('xmomentum', [1,2,3,4], location='centroids')
+        domain.set_quantity('ymomentum', [1,2,3,4], location='centroids')
+
+
+        #Assign some values to update vectors
+        #Set explicit_update
+
+
+        for name in domain.conserved_quantities:
+            domain.quantities[name].explicit_update = num.array([4.,3.,2.,1.])
+            domain.quantities[name].semi_implicit_update = num.array([1.,1.,1.,1.])
+
+
+        #Update with given timestep (assuming no other forcing terms)
+        domain.timestep = 0.1
+        domain.update_conserved_quantities()
+
+        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
+        denom = num.ones(4, num.float) - domain.timestep*sem
+
+#        x = array([1, 2, 3, 4]) + array( [.4,.3,.2,.1] )
+#        x /= denom
+
+        x = num.array([1., 2., 3., 4.])
+        x += domain.timestep*num.array( [4,3,2,1] )
+        x /= denom
+
+
+        for name in domain.conserved_quantities:
+            assert num.allclose(domain.quantities[name].centroid_values, x)
+
+
+    def test_set_region(self):
+        """Set quantities for sub region
+        """
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+        boundary = { (0, 0): 'Third',
+                     (0, 2): 'First',
+                     (2, 0): 'Second',
+                     (2, 1): 'Second',
+                     (3, 1): 'Second',
+                     (3, 2): 'Third'}
+
+        domain = Generic_Domain(points, vertices, boundary,
+                        conserved_quantities =\
+                        ['stage', 'xmomentum', 'ymomentum'])
+        domain.set_default_order(1)                        
+        domain.check_integrity()
+
+        domain.set_quantity('stage', [[1,2,3], [5,5,5],
+                                      [0,0,9], [-6, 3, 3]])
+
+        assert num.allclose( domain.quantities['stage'].centroid_values,
+                             [2,5,3,0] )
+
+        domain.set_quantity('xmomentum', [[1,1,1], [2,2,2],
+                                          [3,3,3], [4, 4, 4]])
+
+        domain.set_quantity('ymomentum', [[10,10,10], [20,20,20],
+                                          [30,30,30], [40, 40, 40]])
+
+
+        domain.distribute_to_vertices_and_edges()
+
+        #First order extrapolation
+        assert num.allclose( domain.quantities['stage'].vertex_values,
+                             [[ 2.,  2.,  2.],
+                              [ 5.,  5.,  5.],
+                              [ 3.,  3.,  3.],
+                              [ 0.,  0.,  0.]])
+
+        domain.build_tagged_elements_dictionary({'mound':[0,1]})
+        domain.set_tag_region([add_to_verts])
+
+        self.failUnless(domain.test == "Mound",
+                        'set region failed')
+
+                             
+    def test_rectangular_periodic_and_ghosts(self):
+
+        from mesh_factory import rectangular_periodic
+        
+
+        M=5
+        N=2
+        points, vertices, boundary, full_send_dict, ghost_recv_dict = rectangular_periodic(M, N)
+
+        assert num.allclose(ghost_recv_dict[0][0], [24, 25, 26, 27,  0,  1,  2,  3])
+        assert num.allclose(full_send_dict[0][0] , [ 4,  5,  6,  7, 20, 21, 22, 23])
+
+        conserved_quantities = ['quant1', 'quant2']
+        domain = Generic_Domain(points, vertices, boundary, conserved_quantities,
+                        full_send_dict=full_send_dict,
+                        ghost_recv_dict=ghost_recv_dict)
+
+
+
+
+        assert num.allclose(domain.ghost_recv_dict[0][0], [24, 25, 26, 27,  0,  1,  2,  3])
+        assert num.allclose(domain.full_send_dict[0][0] , [ 4,  5,  6,  7, 20, 21, 22, 23])
+
+        def xylocation(x,y):
+            return 15*x + 9*y
+
+        
+        domain.set_quantity('quant1',xylocation,location='centroids')
+        domain.set_quantity('quant2',xylocation,location='centroids')
+
+
+        assert num.allclose(domain.quantities['quant1'].centroid_values,
+                            [  0.5,   1.,   5.,    5.5,   3.5,   4.,    8.,    8.5,   6.5,  7.,   11.,   11.5,   9.5,
+                               10.,   14.,   14.5,  12.5,  13.,   17.,   17.5,  15.5,  16.,   20.,   20.5,
+                               18.5,  19.,   23.,   23.5])
+
+
+
+        assert num.allclose(domain.quantities['quant2'].centroid_values,
+                            [  0.5,   1.,   5.,    5.5,   3.5,   4.,    8.,    8.5,   6.5,  7.,   11.,   11.5,   9.5,
+                               10.,   14.,   14.5,  12.5,  13.,   17.,   17.5,  15.5,  16.,   20.,   20.5,
+                               18.5,  19.,   23.,   23.5])
+
+        domain.update_ghosts()
+
+
+        assert num.allclose(domain.quantities['quant1'].centroid_values,
+                            [  15.5,  16.,   20.,   20.5,   3.5,   4.,    8.,    8.5,   6.5,  7.,   11.,   11.5,   9.5,
+                               10.,   14.,   14.5,  12.5,  13.,   17.,   17.5,  15.5,  16.,   20.,   20.5,
+                                3.5,   4.,    8.,    8.5])
+
+
+
+        assert num.allclose(domain.quantities['quant2'].centroid_values,
+                            [  15.5,  16.,   20.,   20.5,   3.5,   4.,    8.,    8.5,   6.5,  7.,   11.,   11.5,   9.5,
+                               10.,   14.,   14.5,  12.5,  13.,   17.,   17.5,  15.5,  16.,   20.,   20.5,
+                                3.5,   4.,    8.,    8.5])
+
+        
+        assert num.allclose(domain.tri_full_flag, [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+                                                   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0])
+
+        assert num.allclose(domain.node_full_flag, [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+                                                   1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0])
+
+
+        #assert num.allclose(domain.number_of_full_nodes, 18)
+        
+        assert num.allclose(domain.number_of_full_triangles, 20)
+
+        #Test that points are arranged in a counter clock wise order
+        domain.check_integrity()
+
+
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Domain,'test_')
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_ghost.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_ghost.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_ghost.py	(revision 9460)
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt
+
+from anuga.abstract_2d_finite_volumes.generic_domain import Generic_Domain
+from anuga.config import epsilon
+
+import numpy as num
+
+
+class Test_Domain(unittest.TestCase):
+    def setUp(self):
+        pass
+
+
+    def tearDown(self):
+        pass
+
+
+    def test_simple(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
+        other_quantities = ['elevation', 'friction']
+
+        domain = Generic_Domain(points, vertices, None,
+                        conserved_quantities, None, other_quantities)
+        domain.check_integrity()
+
+        for name in conserved_quantities + other_quantities:
+            assert domain.quantities.has_key(name)
+
+
+        assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.)
+
+
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Domain,'test')
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_neighbour_mesh.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_neighbour_mesh.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_neighbour_mesh.py	(revision 9460)
@@ -0,0 +1,1854 @@
+#!/usr/bin/env python
+
+
+
+#FIXME: Seperate the tests for mesh and general_mesh
+
+#FIXME (Ole): Maxe this test independent of anything that inherits from General_mesh (namely shallow_water)
+
+import unittest
+from math import sqrt
+
+
+from anuga.abstract_2d_finite_volumes.neighbour_mesh import *
+from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular
+from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular_periodic
+from anuga.config import epsilon
+
+from anuga.coordinate_transforms.geo_reference import Geo_reference
+from anuga.geometry.polygon import is_inside_polygon
+from anuga.utilities.numerical_tools import ensure_numeric
+
+import numpy as num
+
+
+def distance(x, y):
+    return sqrt(num.sum((num.array(x)-num.array(y))**2))
+
+class Test_Mesh(unittest.TestCase):
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+    def test_triangle_inputs(self):
+        points = [[0.0, 0.0], [4.0, 0.0], [0.0, 3.0]]
+        vertices = [0,1,2] #Wrong
+
+        try:
+            mesh = Mesh(points, vertices)
+        except:
+            pass
+        else:
+            msg = 'Should have raised exception'
+            raise Exception(msg)
+
+
+    def test_basic_triangle(self):
+
+        a = [0.0, 0.0]
+        b = [4.0, 0.0]
+        c = [0.0, 3.0]
+
+        points = [a, b, c]
+        vertices = [[0,1,2]]
+        mesh = Mesh(points, vertices)
+
+        #Centroid
+        centroid = mesh.centroid_coordinates[0]
+        assert centroid[0] == 4.0/3
+        assert centroid[1] == 1.0
+
+        #Area
+        assert mesh.areas[0] == 6.0,\
+               'Area was %f, should have been 6.0' %mesh.areas[0]
+
+        #Normals
+        normals = mesh.get_normals()
+        assert num.allclose(normals[0, 0:2], [3.0/5, 4.0/5])
+        assert num.allclose(normals[0, 2:4], [-1.0, 0.0])
+        assert num.allclose(normals[0, 4:6], [0.0, -1.0])
+
+        assert num.allclose(mesh.get_normal(0,0), [3.0/5, 4.0/5])
+        assert num.allclose(mesh.get_normal(0,1), [-1.0, 0.0])
+        assert num.allclose(mesh.get_normal(0,2), [0.0, -1.0])
+
+        #Edge lengths
+        assert num.allclose(mesh.edgelengths[0], [5.0, 3.0, 4.0])
+
+
+        #Vertex coordinates
+        #V = mesh.get_vertex_coordinates()
+        #assert allclose(V[0], [0.0, 0.0, 4.0, 0.0, 0.0, 3.0])
+        
+
+        V = mesh.get_vertex_coordinates()
+        assert num.allclose(V, [ [0.0, 0.0],
+                             [4.0, 0.0],
+                             [0.0, 3.0] ])
+
+        V0 = mesh.get_vertex_coordinate(0, 0)
+        assert num.allclose(V0, [0.0, 0.0])
+
+        V1 = mesh.get_vertex_coordinate(0, 1)
+        assert num.allclose(V1, [4.0, 0.0])
+
+        V2 = mesh.get_vertex_coordinate(0, 2)
+        assert num.allclose(V2, [0.0, 3.0])
+
+
+        #General tests:
+
+        #Test that points are arranged in a counter clock wise order etc
+        mesh.check_integrity()
+
+
+        #Test that the centroid is located 2/3 of the way
+        #from each vertex to the midpoint of the opposite side
+
+        V = mesh.get_vertex_coordinates()
+        x0 = V[0, 0]; y0 = V[0, 1]
+        x1 = V[1, 0]; y1 = V[1, 1]
+        x2 = V[2, 0]; y2 = V[2, 1]
+        #x0 = V[0,0]
+        #y0 = V[0,1]
+        #x1 = V[0,2]
+        #y1 = V[0,3]
+        #x2 = V[0,4]
+        #y2 = V[0,5]
+
+        m0 = [(x1 + x2)/2, (y1 + y2)/2]
+        m1 = [(x0 + x2)/2, (y0 + y2)/2]
+        m2 = [(x1 + x0)/2, (y1 + y0)/2]
+
+        d0 = distance(centroid, [x0, y0])
+        d1 = distance(m0, [x0, y0])
+        assert d0 == 2*d1/3
+        #
+        d0 = distance(centroid, [x1, y1])
+        d1 = distance(m1, [x1, y1])
+        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
+
+        d0 = distance(centroid, [x2, y2])
+        d1 = distance(m2, [x2, y2])
+        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
+
+        #Radius
+        d0 = distance(centroid, m0)
+        assert d0 == 5.0/6
+
+        d1 = distance(centroid, m1)
+        assert d1 == sqrt(73.0/36)
+
+        d2 = distance(centroid, m2)
+        assert d2 == sqrt(13.0/9)
+
+        assert mesh.radii[0] == min(d0, d1, d2)
+        assert mesh.radii[0] == 5.0/6
+
+
+        #Let x be the centroid of triangle abc.
+        #Test that areas of the three triangles axc, cxb, and bxa are equal.
+        points = [a, b, c, centroid]
+        vertices = [[0,3,2], [2,3,1], [1,3,0]]
+        new_mesh = Mesh(points, vertices)
+
+        assert new_mesh.areas[0] == new_mesh.areas[1]
+        assert new_mesh.areas[1] == new_mesh.areas[2]
+        assert new_mesh.areas[1] == new_mesh.areas[2]
+
+        assert new_mesh.areas[1] == mesh.areas[0]/3
+
+
+
+    def test_general_triangle(self):
+        a = [2.0, 1.0]
+        b = [6.0, 2.0]
+        c = [1.0, 3.0]
+
+        points = [a, b, c]
+        vertices = [[0,1,2]]
+
+        mesh = Mesh(points, vertices)
+        centroid = mesh.centroid_coordinates[0]
+
+
+        #Test that the centroid is located 2/3 of the way
+        #from each vertex to the midpoint of the opposite side
+
+        V = mesh.get_vertex_coordinates()
+        x0 = V[0, 0]; y0 = V[0, 1]
+        x1 = V[1, 0]; y1 = V[1, 1]
+        x2 = V[2, 0]; y2 = V[2, 1]        
+
+        #x0 = V[0,0]
+        #y0 = V[0,1]
+        #x1 = V[0,2]
+        #y1 = V[0,3]
+        #x2 = V[0,4]
+        #y2 = V[0,5]
+
+        m0 = [(x1 + x2)/2, (y1 + y2)/2]
+        m1 = [(x0 + x2)/2, (y0 + y2)/2]
+        m2 = [(x1 + x0)/2, (y1 + y0)/2]
+
+        d0 = distance(centroid, [x0, y0])
+        d1 = distance(m0, [x0, y0])
+        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
+        #
+        d0 = distance(centroid, [x1, y1])
+        d1 = distance(m1, [x1, y1])
+        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
+
+        d0 = distance(centroid, [x2, y2])
+        d1 = distance(m2, [x2, y2])
+        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
+
+        #Radius
+        d0 = distance(centroid, m0)
+        d1 = distance(centroid, m1)
+        d2 = distance(centroid, m2)
+        assert mesh.radii[0] == min(d0, d1, d2)
+
+
+
+        #Let x be the centroid of triangle abc.
+        #Test that areas of the three triangles axc, cxb, and bxa are equal.
+
+        points = [a, b, c, centroid]
+        vertices = [[0,3,2], [2,3,1], [1,3,0]]
+        new_mesh = Mesh(points, vertices)
+
+        assert new_mesh.areas[0] == new_mesh.areas[1]
+        assert new_mesh.areas[1] == new_mesh.areas[2]
+        assert new_mesh.areas[1] == new_mesh.areas[2]
+
+        assert new_mesh.areas[1] == mesh.areas[0]/3
+
+
+        #Test that points are arranged in a counter clock wise order
+        mesh.check_integrity()
+
+    def test_inscribed_circle_equilateral(self):
+        """test that the radius is calculated correctly by mesh in the case of an equilateral triangle"""
+        a = [0.0, 0.0]
+        b = [2.0, 0.0]
+        c = [1.0, sqrt(3.0)]
+
+        points = [a, b, c]
+        vertices = [[0,1,2]]
+
+        mesh = Mesh(points, vertices,use_inscribed_circle=False)
+        assert num.allclose(mesh.radii[0],sqrt(3.0)/3),'Steve''s doesn''t work'
+
+        mesh = Mesh(points, vertices,use_inscribed_circle=True)
+        assert num.allclose(mesh.radii[0],sqrt(3.0)/3),'inscribed circle doesn''t work'
+
+    def test_inscribed_circle_rightangle_triangle(self):
+        """test that the radius is calculated correctly by mesh in the case of a right-angled triangle"""
+        a = [0.0, 0.0]
+        b = [4.0, 0.0]
+        c = [0.0, 3.0]
+
+        points = [a, b, c]
+        vertices = [[0,1,2]]
+
+        mesh = Mesh(points, vertices,use_inscribed_circle=False)
+        assert num.allclose(mesh.radii[0],5.0/6),'Steve''s doesn''t work'
+
+        mesh = Mesh(points, vertices,use_inscribed_circle=True)
+        assert num.allclose(mesh.radii[0],1.0),'inscribed circle doesn''t work'
+
+
+    def test_two_triangles(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        e = [2.0, 2.0]
+        points = [a, b, c, e]
+        vertices = [ [1,0,2], [1,2,3] ]   #bac, bce
+        mesh = Mesh(points, vertices)
+
+        assert mesh.areas[0] == 2.0
+
+        assert num.allclose(mesh.centroid_coordinates[0], [2.0/3, 2.0/3])
+
+
+        #Test that points are arranged in a counter clock wise order
+        mesh.check_integrity()
+
+
+
+    def test_more_triangles(self):
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe, daf, dae
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+        mesh = Mesh(points, vertices)
+
+        #Test that points are arranged in a counter clock wise order
+        mesh.check_integrity()
+
+        assert mesh.areas[0] == 2.0
+        assert mesh.areas[1] == 2.0
+        assert mesh.areas[2] == 2.0
+        assert mesh.areas[3] == 2.0
+
+        assert mesh.edgelengths[1,0] == 2.0
+        assert mesh.edgelengths[1,1] == 2.0
+        assert mesh.edgelengths[1,2] == sqrt(8.0)
+
+        assert num.allclose(mesh.centroid_coordinates[0], [2.0/3, 2.0/3])
+        assert num.allclose(mesh.centroid_coordinates[1], [4.0/3, 4.0/3])
+        assert num.allclose(mesh.centroid_coordinates[2], [8.0/3, 2.0/3])
+        assert num.allclose(mesh.centroid_coordinates[3], [2.0/3, 8.0/3])
+
+    def test_mesh_and_neighbours(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+        mesh = Mesh(points, vertices)
+
+        mesh.check_integrity()
+
+
+        T = mesh
+        tid = 0
+        assert T.number_of_boundaries[tid] == 2
+        assert T.neighbours[tid, 0] < 0  #Opposite point b (0,2)
+        assert T.neighbours[tid, 1] == 1 #Opposite point a (0,0)
+        assert T.neighbours[tid, 2] < 0  #Opposite point c (2,0)
+
+        tid = 1
+        assert T.number_of_boundaries[tid] == 0
+        assert T.neighbours[tid, 0] == 2  #Opposite point b (0,2)
+        assert T.neighbours[tid, 1] == 3  #Opposite point c (2,0)
+        assert T.neighbours[tid, 2] == 0  #Opposite point e (2,2)
+
+        tid = 2
+        assert T.number_of_boundaries[tid] == 2
+        assert T.neighbours[tid, 0] < 0   #Opposite point e (2,2)
+        assert T.neighbours[tid, 1] < 0   #Opposite point c (2,0)
+        assert T.neighbours[tid, 2] == 1  #Opposite point f (4,0)
+
+        tid = 3
+        assert T.number_of_boundaries[tid] == 2
+        assert T.neighbours[tid, 0] == 1  #Opposite point d (0,4)
+        assert T.neighbours[tid, 1] < 0   #Opposite point b (0,3)
+        assert T.neighbours[tid, 2] < 0   #Opposite point e (2,2)
+
+        #Neighbouring edges
+        tid = 0
+        assert T.neighbour_edges[tid, 0] < 0  #Opposite point b (0,2)
+        assert T.neighbour_edges[tid, 1] == 2 #Opposite point a (0,0)
+        assert T.neighbour_edges[tid, 2] < 0  #Opposite point c (2,0)
+
+        tid = 1
+        assert T.neighbour_edges[tid, 0] == 2 #Opposite point b (0,2)
+        assert T.neighbour_edges[tid, 1] == 0 #Opposite point c (2,0)
+        assert T.neighbour_edges[tid, 2] == 1 #Opposite point e (2,2)
+
+        tid = 2
+        assert T.neighbour_edges[tid, 0] < 0  #Opposite point e (2,2)
+        assert T.neighbour_edges[tid, 1] < 0  #Opposite point c (2,0)
+        assert T.neighbour_edges[tid, 2] == 0 #Opposite point f (4,0)
+
+        tid = 3
+        assert T.neighbour_edges[tid, 0] == 1 #Opposite point d (0,4)
+        assert T.neighbour_edges[tid, 1] < 0  #Opposite point b (0,3)
+        assert T.neighbour_edges[tid, 2] < 0  #Opposite point e (2,2)
+
+
+    def test_build_neighbour_structure_duplicates(self):
+        p0 = [-66.0, 14.0]
+        p1 = [14.0, -66.0]
+        p2 = [14.0, 14.0]
+        p3 = [60.0, 20.0]
+        p4 = [10.0, 60.0]
+        p5 = [60.0, 60.0]
+
+        points = [p0, p1, p2, p3, p4, p5]
+        triangles = [ [0, 1, 2],
+                      [3, 2, 1],
+                      [0, 2, 4],
+                      [0, 2, 4],
+                      [4, 2, 5],
+                      [5, 2, 3]]
+        try:
+            mesh = Mesh(points, triangles)
+        except:
+            pass
+        else:
+            raise Exception("triangle edge duplicates not caught")
+
+
+    def test_rectangular_mesh_basic(self):
+        M=1
+        N=1
+
+        points, vertices, boundary = rectangular(M, N)
+        mesh = Mesh(points, vertices, boundary)
+
+        #Test that points are arranged in a counter clock wise order
+        mesh.check_integrity()
+
+        M=2
+        N=2
+        points, vertices, boundary = rectangular(M, N)
+        mesh = Mesh(points, vertices, boundary)
+
+        #Test that points are arranged in a counter clock wise order
+        mesh.check_integrity()
+
+        #assert mesh.boundary[(7,1)] == 2 # top
+        assert mesh.boundary[(7,1)] == 'top' # top
+        assert mesh.boundary[(3,1)] == 'top' # top
+
+
+
+
+
+
+    def test_boundary_tags(self):
+
+
+        points, vertices, boundary = rectangular(4, 4)
+        mesh = Mesh(points, vertices, boundary)
+
+
+        #Test that points are arranged in a counter clock wise order
+        mesh.check_integrity()
+
+        #print mesh.get_boundary_tags()
+        #print mesh.boundary
+
+        for k in [1, 3, 5, 7]:
+            assert mesh.boundary[(k,2)] == 'left'
+
+        for k in [24, 26, 28, 30]:
+            assert mesh.boundary[(k,2)] == 'right'
+
+        for k in [7, 15, 23, 31]:
+            assert mesh.boundary[(k,1)] == 'top'
+        for k in [0, 8, 16, 24]:
+            assert mesh.boundary[(k,1)] == 'bottom'
+
+
+
+    def test_rectangular_mesh(self):
+        M=4
+        N=16
+        len1 = 100.0
+        len2 = 17.0
+
+        points, vertices, boundary = rectangular(M, N, len1, len2)
+        mesh = Mesh(points, vertices, boundary)
+
+        assert len(mesh) == 2*M*N
+
+        for i in range(len(mesh)):
+            assert mesh.areas[i] == len1*len2/(2*M*N)
+
+            hypo = sqrt((len1/M)**2 + (len2/N)**2) #hypothenuse
+            assert mesh.edgelengths[i, 0] == hypo
+            assert mesh.edgelengths[i, 1] == len1/M #x direction
+            assert mesh.edgelengths[i, 2] == len2/N #y direction
+
+        #Test that points are arranged in a counter clock wise order
+        mesh.check_integrity()
+
+
+    def test_rectangular_mesh2(self):
+        #Check that integers don't cause trouble
+        N = 16
+
+        points, vertices, boundary = rectangular(2*N, N, len1=10, len2=10)
+        mesh = Mesh(points, vertices, boundary)
+
+
+    def test_surrogate_neighbours(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+        mesh = Mesh(points, vertices)
+        mesh.check_integrity()
+
+
+        T = mesh
+        tid = 0
+        assert T.number_of_boundaries[tid] == 2
+        assert T.surrogate_neighbours[tid, 0] == tid
+        assert T.surrogate_neighbours[tid, 1] == 1
+        assert T.surrogate_neighbours[tid, 2] == tid
+
+        tid = 1
+        assert T.number_of_boundaries[tid] == 0
+        assert T.surrogate_neighbours[tid, 0] == 2
+        assert T.surrogate_neighbours[tid, 1] == 3
+        assert T.surrogate_neighbours[tid, 2] == 0
+
+        tid = 2
+        assert T.number_of_boundaries[tid] == 2
+        assert T.surrogate_neighbours[tid, 0] == tid
+        assert T.surrogate_neighbours[tid, 1] == tid
+        assert T.surrogate_neighbours[tid, 2] == 1
+
+        tid = 3
+        assert T.number_of_boundaries[tid] == 2
+        assert T.surrogate_neighbours[tid, 0] == 1
+        assert T.surrogate_neighbours[tid, 1] == tid
+        assert T.surrogate_neighbours[tid, 2] == tid
+
+
+    def test_boundary_inputs(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        boundary = { (0, 0): 'First',
+                     (0, 2): 'Second',
+                     (2, 0): 'Third',
+                     (2, 1): 'Fourth',
+                     (3, 1): 'Fifth',
+                     (3, 2): 'Sixth'}
+
+
+        mesh = Mesh(points, vertices, boundary)
+        mesh.check_integrity()
+
+
+        #Check enumeration
+        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
+        #    b = -k-1
+        #    assert mesh.neighbours[vol_id, edge_id] == b
+
+
+
+    def test_boundary_inputs_using_one_default(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        boundary = { (0, 0): 'First',
+                     (0, 2): 'Second',
+                     (2, 0): 'Third',
+                     (2, 1): 'Fourth',
+                     #(3, 1): 'Fifth',  #Skip this
+                     (3, 2): 'Sixth'}
+
+
+        mesh = Mesh(points, vertices, boundary)
+        mesh.check_integrity()
+
+        from anuga.config import default_boundary_tag
+        assert mesh.boundary[ (3, 1) ] == default_boundary_tag
+
+
+        #Check enumeration
+        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
+        #    b = -k-1
+        #    assert mesh.neighbours[vol_id, edge_id] == b
+
+    def test_boundary_inputs_using_all_defaults(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        boundary = { (0, 0): 'First',
+                     (0, 2): 'Second',
+                     (2, 0): 'Third',
+                     (2, 1): 'Fourth',
+                     #(3, 1): 'Fifth',  #Skip this
+                     (3, 2): 'Sixth'}
+
+
+        mesh = Mesh(points, vertices) #, boundary)
+        mesh.check_integrity()
+
+        from anuga.config import default_boundary_tag
+        assert mesh.boundary[ (0, 0) ] == default_boundary_tag
+        assert mesh.boundary[ (0, 2) ] == default_boundary_tag
+        assert mesh.boundary[ (2, 0) ] == default_boundary_tag
+        assert mesh.boundary[ (2, 1) ] == default_boundary_tag
+        assert mesh.boundary[ (3, 1) ] == default_boundary_tag
+        assert mesh.boundary[ (3, 2) ] == default_boundary_tag
+
+
+        #Check enumeration
+        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
+        #    b = -k-1
+        #    assert mesh.neighbours[vol_id, edge_id] == b
+
+
+
+
+
+
+    def test_inputs(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        #Too few points
+        try:
+            mesh = Mesh([points[0]], vertices)
+        except AssertionError:
+            pass
+        else:
+            raise Exception('Should have raised an exception')
+
+        #Too few points - 1 element
+        try:
+            mesh = Mesh([points[0]], [vertices[0]])
+        except AssertionError:
+            pass
+        else:
+            raise Exception('Should have raised an exception')
+
+        #Wrong dimension of vertices
+        try:
+            mesh = Mesh(points, vertices[0])
+        except AssertionError:
+            pass
+        else:
+            raise Exception('Should have raised an exception')
+
+        #Unsubscriptable coordinates object raises exception
+        try:
+            mesh = Mesh(points[0], [vertices[0]])
+        except AssertionError:
+            pass
+        else:
+            raise Exception('Should have raised an exception')
+
+        #FIXME: This has been commented out pending a decision
+        #whether to allow partial boundary tags or not
+        #
+        #Not specifying all boundary tags
+        #try:
+        #    mesh = Mesh(points, vertices, {(3,0): 'x'})
+        #except AssertionError:
+        #    pass
+        #else:
+        #    raise Exception('Should have raised an exception')
+
+        #Specifying wrong non existing segment       
+        try:
+            mesh = Mesh(points, vertices, {(5,0): 'x'})
+        except AssertionError:
+            pass
+        except RuntimeError:
+            pass
+        else:
+            raise Exception('Should have raised an exception')
+
+
+
+
+    def test_internal_boundaries(self):
+        """
+        get values based on triangle lists.
+        """
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        # Add an internal boundary
+        boundary[(2,0)] = 'internal'
+        boundary[(1,0)] = 'internal'
+
+        #Create shallow water domain
+        domain = Mesh(points, vertices, boundary)
+        domain.build_tagged_elements_dictionary({'bottom':[0,1],
+                                                 'top':[4,5],
+                                                 'all':[0,1,2,3,4,5]})
+
+
+    def test_boundary_polygon(self):
+        from mesh_factory import rectangular
+        #from mesh import Mesh
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(2, 2)
+        mesh = Mesh(points, vertices, boundary)
+
+
+        P = mesh.get_boundary_polygon()
+
+        assert len(P) == 8
+        assert num.allclose(P, [[0.0, 0.0], [0.5, 0.0], [1.0, 0.0],
+                                [1.0, 0.5], [1.0, 1.0], [0.5, 1.0],
+                                [0.0, 1.0], [0.0, 0.5]])
+        for p in points:
+            #print p, P
+            assert is_inside_polygon(p, P)
+
+
+    def test_boundary_polygon_II(self):
+
+        #Points
+        a = [0.0, 0.0] #0
+        b = [0.0, 0.5] #1
+        c = [0.0, 1.0] #2
+        d = [0.5, 0.0] #3
+        e = [0.5, 0.5] #4
+        f = [1.0, 0.0] #5
+        g = [1.0, 0.5] #6
+        h = [1.0, 1.0] #7
+        i = [1.5, 0.5] #8
+
+        points = [a, b, c, d, e, f, g, h, i]
+
+        #dea, bae, bec, fgd,
+        #edg, ghe, gfi, gih
+        vertices = [ [3,4,0], [1,0,4], [1,4,2], [5,6,3],
+                     [4,3,6], [6,7,4], [6,5,8], [6,8,7]]
+
+        mesh = Mesh(points, vertices)
+
+        mesh.check_integrity()
+
+        P = mesh.get_boundary_polygon()
+
+        assert len(P) == 8
+        assert num.allclose(P, [a, d, f, i, h, e, c, b])
+
+        for p in points:
+            #print p, P
+            assert is_inside_polygon(p, P)
+
+
+    def test_boundary_polygon_III(self):
+        """Same as II but vertices ordered differently
+        """
+
+
+        #Points
+        a = [0.0, 0.0] #0
+        b = [0.0, 0.5] #1
+        c = [0.0, 1.0] #2
+        d = [0.5, 0.0] #3
+        e = [0.5, 0.5] #4
+        f = [1.0, 0.0] #5
+        g = [1.0, 0.5] #6
+        h = [1.0, 1.0] #7
+        i = [1.5, 0.5] #8
+
+        points = [a, b, c, d, e, f, g, h, i]
+
+        #edg, ghe, gfi, gih
+        #dea, bae, bec, fgd,
+        vertices = [[4,3,6], [6,7,4], [6,5,8], [6,8,7],
+                    [3,4,0], [1,0,4], [1,4,2], [5,6,3]]
+
+
+        mesh = Mesh(points, vertices)
+        mesh.check_integrity()
+
+
+        P = mesh.get_boundary_polygon()
+
+        assert len(P) == 8
+        assert num.allclose(P, [a, d, f, i, h, e, c, b])
+
+        for p in points:
+            assert is_inside_polygon(p, P)
+
+	    
+    def test_boundary_polygon_IIIa(self):
+        """test_boundary_polygon_IIIa - Check pathological situation where
+	one triangle has no neighbours. This may be the case if a mesh
+	is partitioned using pymetis.
+        """
+
+
+        #Points
+        a = [0.0, 0.0] #0
+        b = [0.0, 0.5] #1
+        c = [0.0, 1.0] #2
+        d = [0.5, 0.0] #3
+        e = [0.5, 0.5] #4
+        f = [1.0, 0.0] #5
+        g = [1.0, 0.5] #6
+        h = [1.0, 1.0] #7
+       
+	# Add pathological triangle with no neighbours to an otherwise
+	# trivial mesh
+	
+	points = [a, b, c, d, e, f, g, h]
+
+        #cbe, aeb, dea, fed, ghe (pathological triangle)
+        vertices = [[2,1,4], [0,4,1], [3,4,0], [5,4,3],
+     	            [6,7,4]]	
+		    
+        mesh = Mesh(points, vertices)
+        mesh.check_integrity()
+
+        P = mesh.get_boundary_polygon(verbose=False)
+
+        
+        assert len(P) == 9
+	
+	# Note that point e appears twice!
+        assert num.allclose(P, [a, d, f, e, g, h, e, c, b])
+
+        for p in points:
+	    msg = 'Point %s is not inside polygon %s'\
+	    %(p, P)	
+            assert is_inside_polygon(p, P), msg		    
+
+
+				 	
+	    
+	    
+
+    def test_boundary_polygon_IV(self):
+        """Reproduce test test_spatio_temporal_file_function_time
+        from test_util.py that looked as if it produced the wrong boundary
+        """
+
+        from mesh_factory import rectangular        
+
+        #Create a domain to hold test grid
+        #(0:15, -20:10)
+        points, vertices, boundary =\
+                rectangular(4, 4, 15, 30, origin = (0, -20))        
+
+        #####
+        mesh = Mesh(points, vertices)
+        mesh.check_integrity()
+
+        P = mesh.get_boundary_polygon()
+
+        #print P
+        assert len(P) == 16
+        for p in points:
+            assert is_inside_polygon(p, P)
+
+
+
+        #####
+        mesh = Mesh(points, vertices, boundary)
+        mesh.check_integrity()
+
+        P = mesh.get_boundary_polygon()
+
+        
+        #print P, len(P)
+        assert len(P) == 16
+
+        for p in points:
+            assert is_inside_polygon(p, P)
+
+        #print mesh.statistics()    
+
+
+
+    def test_boundary_polygon_V(self):
+        """Create a discontinuous mesh (duplicate vertices)
+        and check that boundary is as expected
+        
+        """
+
+        #Points
+        a = [0.0, 0.0] #0
+        b = [0.0, 0.5] #1
+        c = [0.0, 1.0] #2
+        d = [0.5, 0.0] #3
+        e = [0.5, 0.5] #4
+        f = [1.0, 0.0] #5
+        g = [1.0, 0.5] #6
+        h = [1.0, 1.0] #7
+        i = [1.5, 0.5] #8
+
+        #Duplicate points for triangles edg [4,3,6] (central) and
+        #gid [6,8,7] (top right boundary) to them disconnected
+        #from the others
+
+        e0 = [0.5, 0.5] #9 
+        d0 = [0.5, 0.0] #10
+        g0 = [1.0, 0.5] #11
+        i0 = [1.5, 0.5] #12        
+        
+
+        points = [a, b, c, d, e, f, g, h, i, e0, d0, g0, i0]
+
+
+
+        #dea, bae, bec, fgd,
+        #edg, ghe, gfi, gih
+        #vertices = [ [3,4,0], [1,0,4], [1,4,2], [5,6,3],
+        #             [4,3,6], [6,7,4], [6,5,8], [6,8,7]]
+
+
+        #dea, bae, bec, fgd,
+        #e0d0g0, ghe, gfi, g0i0h
+        vertices = [[3,4,0], [1,0,4], [1,4,2], [5,6,3],
+                    [9,10,11], [6,7,4], [6,5,8], [11,12,7]]        
+
+        mesh = Mesh(points, vertices)
+
+        mesh.check_integrity()
+
+        P = mesh.get_boundary_polygon()
+
+        #print P
+        
+        assert len(P) == 8
+        assert num.allclose(P, [a, d, f, i, h, e, c, b])
+        assert num.allclose(P, [(0.0, 0.0), (0.5, 0.0), (1.0, 0.0), (1.5, 0.5), (1.0, 1.0), (0.5, 0.5), (0.0, 1.0), (0.0, 0.5)])
+        
+
+        for p in points:
+            #print p, P
+            assert is_inside_polygon(p, P)
+
+
+
+    def test_boundary_polygon_VI(self):
+        """test_boundary_polygon_VI(self)
+
+        Create a discontinuous mesh (duplicate vertices) from a real situation that failed
+        and check that boundary is as expected
+        """
+
+        # First do the continuous version of mesh
+
+        points = [[   6626.85400391,      0.        ],
+                  [      0.        ,  38246.4140625 ],
+                  [   9656.2734375 ,  68351.265625  ],
+                  [  20827.25585938,  77818.203125  ],
+                  [  32755.59375   ,  58126.9765625 ],
+                  [  35406.3359375 ,  79332.9140625 ],
+                  [  31998.23828125,  88799.84375   ],
+                  [  23288.65820313, 104704.296875  ],
+                  [  32187.57617188, 109816.4375    ],
+                  [  50364.08984375, 110763.1328125 ],
+                  [  80468.9453125 ,  96184.0546875 ],
+                  [  86149.1015625 , 129886.34375   ],
+                  [ 118715.359375  , 129886.34375   ],
+                  [ 117768.6640625 ,  85770.4296875 ],
+                  [ 101485.5390625 ,  45251.9453125 ],
+                  [  49985.4140625 ,   2272.06396484],
+                  [  51737.94140625,  90559.2109375 ],
+                  [  56659.0703125 ,  65907.6796875 ],
+                  [  75735.4765625 ,  23762.00585938],
+                  [  52341.70703125,  38563.39453125]]
+
+        triangles = [[19, 0,15],
+                     [ 2, 4, 3],
+                     [ 4, 2, 1],
+                     [ 1,19, 4],
+                     [15,18,19],
+                     [18,14,17],
+                     [19, 1, 0],
+                     [ 6, 8, 7],
+                     [ 8, 6,16],
+                     [10, 9,16],
+                     [17, 5, 4],
+                     [16,17,10],
+                     [17,19,18],
+                     [ 5,17,16],
+                     [10,14,13],
+                     [10,17,14],
+                     [ 8,16, 9],
+                     [12,11,10],
+                     [10,13,12],
+                     [19,17, 4],
+                     [16, 6, 5]]
+
+
+        triangles = num.array(triangles,num.int)
+        points = num.array(points,num.float)
+
+        mesh = Mesh(points, triangles)
+        mesh.check_integrity()
+        Pref = mesh.get_boundary_polygon()
+
+        #plot_polygons([ensure_numeric(Pref)], 'goodP')
+
+        for p in points:
+            assert is_inside_polygon(p, Pref)
+        
+        
+        # Then do the discontinuous version
+        import warnings
+        warnings.filterwarnings('ignore')
+
+        
+        points = [[  52341.70703125,  38563.39453125],
+                  [   6626.85400391,      0.        ],
+                  [  49985.4140625 ,   2272.06396484],
+                  [   9656.2734375 ,  68351.265625  ],
+                  [  32755.59375   ,  58126.9765625 ],
+                  [  20827.25585938,  77818.203125  ],
+                  [  32755.59375   ,  58126.9765625 ],
+                  [   9656.2734375 ,  68351.265625  ],
+                  [      0.        ,  38246.4140625 ],
+                  [      0.        ,  38246.4140625 ],
+                  [  52341.70703125,  38563.39453125],
+                  [  32755.59375   ,  58126.9765625 ],
+                  [  49985.4140625 ,   2272.06396484],
+                  [  75735.4765625 ,  23762.00585938],
+                  [  52341.70703125,  38563.39453125],
+                  [  75735.4765625 ,  23762.00585938],
+                  [ 101485.5390625 ,  45251.9453125 ],
+                  [  56659.0703125 ,  65907.6796875 ],
+                  [  52341.70703125,  38563.39453125],
+                  [      0.        ,  38246.4140625 ],
+                  [   6626.85400391,      0.        ],
+                  [  31998.23828125,  88799.84375   ],
+                  [  32187.57617188, 109816.4375    ],
+                  [  23288.65820313, 104704.296875  ],
+                  [  32187.57617188, 109816.4375    ],
+                  [  31998.23828125,  88799.84375   ],
+                  [  51737.94140625,  90559.2109375 ],
+                  [  80468.9453125 ,  96184.0546875 ],
+                  [  50364.08984375, 110763.1328125 ],
+                  [  51737.94140625,  90559.2109375 ],
+                  [  56659.0703125 ,  65907.6796875 ],
+                  [  35406.3359375 ,  79332.9140625 ],
+                  [  32755.59375   ,  58126.9765625 ],
+                  [  51737.94140625,  90559.2109375 ],
+                  [  56659.0703125 ,  65907.6796875 ],
+                  [  80468.9453125 ,  96184.0546875 ],
+                  [  56659.0703125 ,  65907.6796875 ],
+                  [  52341.70703125,  38563.39453125],
+                  [  75735.4765625 ,  23762.00585938],
+                  [  35406.3359375 ,  79332.9140625 ],
+                  [  56659.0703125 ,  65907.6796875 ],
+                  [  51737.94140625,  90559.2109375 ],
+                  [  80468.9453125 ,  96184.0546875 ],
+                  [ 101485.5390625 ,  45251.9453125 ],
+                  [ 117768.6640625 ,  85770.4296875 ],
+                  [  80468.9453125 ,  96184.0546875 ],
+                  [  56659.0703125 ,  65907.6796875 ],
+                  [ 101485.5390625 ,  45251.9453125 ],
+                  [  32187.57617188, 109816.4375    ],
+                  [  51737.94140625,  90559.2109375 ],
+                  [  50364.08984375, 110763.1328125 ],
+                  [ 118715.359375  , 129886.34375   ],
+                  [  86149.1015625 , 129886.34375   ],
+                  [  80468.9453125 ,  96184.0546875 ],
+                  [  80468.9453125 ,  96184.0546875 ],
+                  [ 117768.6640625 ,  85770.4296875 ],
+                  [ 118715.359375  , 129886.34375   ],
+                  [  52341.70703125,  38563.39453125],
+                  [  56659.0703125 ,  65907.6796875 ],
+                  [  32755.59375   ,  58126.9765625 ],
+                  [  51737.94140625,  90559.2109375 ],
+                  [  31998.23828125,  88799.84375   ],
+                  [  35406.3359375 ,  79332.9140625 ]]
+
+        scaled_points = ensure_numeric(points, num.int)/1000  # Simplify for ease of interpretation
+
+        triangles = [[ 0, 1, 2],
+                     [ 3, 4, 5],
+                     [ 6, 7, 8],
+                     [ 9,10,11],
+                     [12,13,14],
+                     [15,16,17],
+                     [18,19,20],
+                     [21,22,23],
+                     [24,25,26],
+                     [27,28,29],
+                     [30,31,32],
+                     [33,34,35],
+                     [36,37,38],
+                     [39,40,41],
+                     [42,43,44],
+                     [45,46,47],
+                     [48,49,50],
+                     [51,52,53],
+                     [54,55,56],
+                     [57,58,59],
+                     [60,61,62]]
+
+
+        # First use scaled points for ease of debugging
+        mesh = Mesh(scaled_points, triangles)
+        mesh.check_integrity()
+        P = mesh.get_boundary_polygon()
+
+        for p in scaled_points:
+            assert is_inside_polygon(p, P)            
+
+        # Then use original points and test        
+        mesh = Mesh(points, triangles)
+        mesh.check_integrity()
+        P = mesh.get_boundary_polygon()
+
+        for p in points:
+            assert is_inside_polygon(p, P)            
+
+        assert num.allclose(P, Pref)    
+
+    def test_lone_vertices(self):
+        a = [2.0, 1.0]
+        b = [6.0, 2.0]
+        c = [1.0, 3.0]
+        d = [2.0, 4.0]
+        e = [4.0, 3.0]
+
+        points = [a, b, d, c, e]
+        vertices = [[0,1,3]]
+
+        mesh = Mesh(points, vertices)
+        mesh.check_integrity()
+        loners = mesh.get_lone_vertices()
+
+        #print loners
+        self.failUnless(loners==[2,4],
+                        'FAILED!')
+
+        
+        a = [2.0, 1.0]
+        b = [6.0, 2.0]
+        c = [1.0, 3.0]
+        d = [2.0, 4.0]
+
+        points = [d, a, b, c]
+        vertices = [[3,1,2]]
+
+        mesh = Mesh(points, vertices)
+        mesh.check_integrity()
+        loners = mesh.get_lone_vertices()
+        self.failUnless(loners==[0],
+                        'FAILED!') 
+
+    def test_mesh_get_boundary_polygon_with_georeferencing(self):
+        """test_mesh_get_boundary_polygon_with_georeferencing
+        
+        Test that get_boundary_polygon returns absolute coordinates
+        """
+        
+        # test
+        a = [0.0, 0.0]
+        b = [4.0, 0.0]
+        c = [0.0, 4.0]
+
+        absolute_points = [a, b, c]
+        vertices = [[0, 1, 2]]
+        
+        geo = Geo_reference(56, 67, -56)
+
+        relative_points = geo.change_points_geo_ref(absolute_points)
+
+        mesh = Mesh(relative_points, vertices, geo_reference=geo)
+        boundary_polygon = mesh.get_boundary_polygon()
+
+        assert num.allclose(absolute_points, boundary_polygon)
+
+    def test_get_triangle_containing_point(self):
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+        mesh = Mesh(points, vertices)
+        
+        mesh.check_integrity()
+
+
+        try:
+            id = mesh.get_triangle_containing_point([3.0, 5.0])
+        except:
+            pass
+        else:
+            msg = 'Should have caught point outside polygon (Non)'            
+            raise Exception(msg)
+            
+        id = mesh.get_triangle_containing_point([0.5, 1.0])
+        assert id == 0
+
+        id = mesh.get_triangle_containing_point([1.0, 3.0])
+        assert id == 3        
+
+        for i, point in enumerate(mesh.get_centroid_coordinates()):
+            id = mesh.get_triangle_containing_point(point)
+            assert id == i        
+
+    def test_get_triangle_neighbours(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        e = [2.0, 2.0]
+        points = [a, b, c, e]
+        vertices = [ [1,0,2], [1,2,3] ]   #bac, bce
+        mesh = Mesh(points, vertices)
+
+        neighbours = mesh.get_triangle_neighbours(0)
+        assert num.allclose(neighbours, [-1,1,-2])
+        neighbours = mesh.get_triangle_neighbours(-10)
+        assert neighbours == []
+        neighbours = mesh.get_triangle_neighbours(2)
+        assert neighbours == []
+
+
+    def test_get_intersecting_segments1(self):
+        """test_get_intersecting_segments(self):
+
+        Very simple test (horizontal lines)
+        """
+
+        # Build test mesh
+        
+        # Create basic mesh
+        # 9 points at (0,0), (0, 1), ..., (2,2)
+        # 8 triangles enumerated from left bottom to right top.
+        points, vertices, boundary = rectangular(2, 2, 2, 2)
+        mesh = Mesh(points, vertices, boundary)
+
+        # Very simple horizontal line intersecting
+        #
+
+
+        for y_line in [0.1, 0.2, 0.314159, 0.41, 0.6, 0.99, 1.01, 1.5, 1.77, 1.9]:
+            if y_line < 1:
+                ceiling = 1
+                floor = 0
+                intersected_triangles = [0,1,4,5]
+            elif y_line > 1:
+                ceiling = 2
+                floor = 1
+                intersected_triangles = [2,3,6,7]
+            else:
+                raise Exception('this test is not for parallel lines')
+
+
+            line = [[-1,y_line], [3,y_line]]
+
+            L = mesh.get_intersecting_segments(line)
+            assert len(L) == 4
+
+            
+
+            # Check all normals point straight down etc
+            total_length = 0
+            for x in L:
+                if x.triangle_id % 2 == 0:
+                    assert num.allclose(x.length, ceiling-y_line)
+                else:
+                    assert num.allclose(x.length, y_line-floor)                
+
+                
+                assert num.allclose(x.normal, [0,-1])
+
+                assert num.allclose(x.segment[1][0], x.segment[0][0] + x.length)
+                assert num.allclose(x.segment[0][1], y_line)
+                assert num.allclose(x.segment[1][1], y_line)                
+
+                assert x.triangle_id in intersected_triangles
+
+                total_length += x.length
+
+            msg = 'Segments do not add up'
+            assert num.allclose(total_length, 2), msg
+            
+
+    def test_get_intersecting_segments_coinciding(self):
+        """test_get_intersecting_segments_coinciding(self):
+
+        Test that lines coinciding with triangle edges work.
+        """
+
+        # Build test mesh
+        
+        # Create basic mesh
+        # 9 points at (0,0), (0, 1), ..., (2,2)
+        # 8 triangles enumerated from left bottom to right top.
+        points, vertices, boundary = rectangular(2, 2, 2, 2)
+        mesh = Mesh(points, vertices, boundary)
+        intersected_triangles = [1,5]
+
+        # Very simple horizontal line intersecting
+        #
+
+        y_line = 1.0
+        
+        line = [[-1,y_line], [3,y_line]]
+
+        L = mesh.get_intersecting_segments(line)
+
+
+        msg = 'Only two triangles should be returned'    
+        assert len(L) == 2, msg    
+            
+
+        # Check all 
+        total_length = 0
+        for x in L:
+            assert num.allclose(x.length, 1.0)
+            assert num.allclose(x.normal, [0,-1])
+
+            assert num.allclose(x.segment[1][0], x.segment[0][0] + x.length)
+            assert num.allclose(x.segment[0][1], y_line)
+            assert num.allclose(x.segment[1][1], y_line)                            
+
+
+
+            assert x.triangle_id in intersected_triangles
+
+            total_length += x.length
+
+        msg = 'Segments do not add up'
+        assert num.allclose(total_length, 2), msg
+        
+
+    def test_get_intersecting_segments_partially_coinciding(self):
+        """test_get_intersecting_segments_partially_coinciding(self):
+
+        Test that line coinciding with triangle edges work.
+        But this ones only coincide with parts of the edge. 
+        """
+
+        # Build test mesh
+        
+        # Create basic mesh
+        # 9 points at (0,0), (0, 1), ..., (2,2)
+        # 8 triangles enumerated from left bottom to right top.
+        points, vertices, boundary = rectangular(2, 2, 2, 2)
+        mesh = Mesh(points, vertices, boundary)
+        intersected_triangles = [1,5]
+
+        # Horizontal line intersecting along center but stopping
+        # parway through second triangle's edge
+        #
+
+        y_line = 1.0
+        
+        #line = [[0, y_line], [2, y_line]]
+        line = [[0, y_line], [1.5, y_line]]
+
+        L = mesh.get_intersecting_segments(line)
+        #for x in L:
+        #    print x
+
+        msg = 'Two triangles should be returned'    
+        assert len(L) == 2, msg    
+            
+
+        # Check all 
+        total_length = 0
+        for x in L:
+            if x.triangle_id == 1:
+                assert num.allclose(x.length, 1)        
+                assert num.allclose(x.normal, [0, -1])
+                
+            if x.triangle_id == 5:
+                assert num.allclose(x.length, 0.5)
+                assert num.allclose(x.normal, [0, -1])
+
+
+            assert x.triangle_id in intersected_triangles
+
+            total_length += x.length
+
+        msg = 'Segments do not add up'
+        assert num.allclose(total_length, 1.5), msg            
+
+
+
+    def test_get_intersecting_segments2(self):
+        """test_get_intersecting_segments(self):
+
+        Lines with a slope
+        """
+
+        s2 = sqrt(2.0)/2
+        
+
+        # Build test mesh
+        
+        # Create basic mesh
+        # 9 points at (0,0), (0, 1), ..., (2,2)
+        # 8 triangles enumerated from left bottom to right top.
+        points, vertices, boundary = rectangular(2, 2, 2, 2)
+        mesh = Mesh(points, vertices, boundary)
+        
+
+        # Diagonal cutting through a vertex and hypothenuses
+        line = [[0, 2], [2, 0]]
+        intersected_triangles = [3,2,5,4]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 4
+
+        #print L
+        
+        # Check all segments
+        total_length = 0
+        for i, x in enumerate(L): 
+            assert num.allclose(x.length, s2)
+            assert num.allclose(x.normal, [-s2, -s2])
+            assert num.allclose(sum(x.normal**2), 1)
+            
+            assert x.triangle_id in intersected_triangles
+
+            total_length += x.length
+
+        msg = 'Segments do not add up'
+        assert num.allclose(total_length, 4*s2), msg
+
+
+        # Diagonal cutting through a vertex and hypothenuses (reversed)
+        line = [[2, 0], [0, 2]]
+        intersected_triangles = [3,2,5,4]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 4
+
+        #print L
+        
+        # Check all segments
+        total_length = 0
+        for i, x in enumerate(L): 
+            assert num.allclose(x.length, s2)
+            assert num.allclose(x.normal, [s2, s2])
+            assert num.allclose(sum(x.normal**2), 1)
+            
+            assert x.triangle_id in intersected_triangles
+
+            total_length += x.length
+
+        msg = 'Segments do not add up'
+        assert num.allclose(total_length, 4*s2), msg                    
+
+
+
+        # Diagonal coinciding with hypothenuses
+        line = [[2, 2], [0, 0]]
+        intersected_triangles = [6,0]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 2
+
+        #print L
+        
+        # Check all segments
+        total_length = 0
+        for i, x in enumerate(L): 
+            assert num.allclose(x.length, 2*s2)
+            assert num.allclose(x.normal, [-s2, s2])
+            assert num.allclose(sum(x.normal**2), 1)
+            
+            assert x.triangle_id in intersected_triangles
+
+            total_length += x.length
+
+        msg = 'Segments do not add up'
+        assert num.allclose(total_length, 4*s2), msg                        
+
+
+        # Diagonal coinciding with hypothenuses (reversed)
+        line = [[0, 0], [2, 2]]
+        intersected_triangles = [6,0]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 2
+
+        #print L
+        
+        # Check all segments
+        total_length = 0
+        for i, x in enumerate(L): 
+            assert num.allclose(x.length, 2*s2)
+            assert num.allclose(x.normal, [s2, -s2])
+            assert num.allclose(sum(x.normal**2), 1)
+            
+            assert x.triangle_id in intersected_triangles
+
+            total_length += x.length
+
+        msg = 'Segments do not add up'
+        assert num.allclose(total_length, 4*s2), msg                        
+
+
+
+        # line with slope [1, -1] cutting through vertices of tri 7 and 6
+        line = [[1, 2], [2, 1]]
+        intersected_triangles = [7,6]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 2
+
+        #print L
+        
+        # Check all segments
+        total_length = 0
+        for i, x in enumerate(L): 
+            assert num.allclose(x.length, s2)
+            assert num.allclose(x.normal, [-s2, -s2])
+            assert num.allclose(sum(x.normal**2), 1)
+            
+            assert x.triangle_id in intersected_triangles
+
+            total_length += x.length
+
+        msg = 'Segments do not add up'
+        assert num.allclose(total_length, 2*s2), msg
+
+
+        # Arbitrary line with slope [1, -1] cutting through tri 7 and 6
+        line = [[1.1, 2], [2.1, 1]]
+        intersected_triangles = [7,6]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 2
+        
+        # Check all segments
+        total_length = 0
+        for i, x in enumerate(L): 
+            assert num.allclose(x.normal, [-s2, -s2])
+            assert num.allclose(sum(x.normal**2), 1)
+
+            msg = 'Triangle %d' %x.triangle_id + ' is not in %s' %(intersected_triangles)
+            assert x.triangle_id in intersected_triangles, msg
+            
+
+
+    def test_get_intersecting_segments3(self):
+        """test_get_intersecting_segments(self):
+
+        Check that line can stop inside a triangle
+        
+        """
+
+
+
+        s2 = sqrt(2.0)/2
+        
+
+        # Build test mesh
+        
+        # Create basic mesh
+        # 9 points at (0,0), (0, 1), ..., (2,2)
+        # 8 triangles enumerated from left bottom to right top.
+        points, vertices, boundary = rectangular(2, 2, 2, 2)
+        mesh = Mesh(points, vertices, boundary)
+        
+
+        # Line cutting through one triangle and ending on its edge
+        line = [[0.5, 3], [0.5, 1.5]]
+        intersected_triangles = [3]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 1
+        assert L[0].triangle_id == 3
+        assert num.allclose(L[0].length, 0.5)        
+        assert num.allclose(L[0].normal, [-1,0])                
+
+
+
+        # Now try to shorten it so that its endpoint falls short of the far edge
+        line = [[0.5, 3], [0.5, 1.6]]
+        intersected_triangles = [3]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 1
+        assert L[0].triangle_id == 3
+        assert num.allclose(L[0].length, 0.4)
+        assert num.allclose(L[0].normal, [-1,0])
+
+        intersected_triangles = [3]
+
+        # Now the same, but with direction changed
+        line = [[0.5, 3], [0.5, 1.6]]
+        line = [[0.5, 1.6], [0.5, 3]]        
+        intersected_triangles = [3]                
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 1
+        assert L[0].triangle_id == 3
+        assert num.allclose(L[0].length, 0.4)
+        assert num.allclose(L[0].normal, [1,0])                
+        
+
+            
+
+    def test_get_intersecting_segments4(self):
+        """test_get_intersecting_segments(self):
+
+        Simple poly line
+        
+        """
+
+
+
+        s2 = sqrt(2.0)/2
+        
+
+        # Build test mesh
+        
+        # Create basic mesh
+        # 9 points at (0,0), (0, 1), ..., (2,2)
+        # 8 triangles enumerated from left bottom to right top.
+        points, vertices, boundary = rectangular(2, 2, 2, 2)
+        mesh = Mesh(points, vertices, boundary)
+        
+
+        # Polyline with three segments cutting through mesh
+        line = [[0.5, 3], [0.5, 1.5], [1,1]]
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 2
+
+        for x in L:
+            if x.triangle_id == 3:
+                assert num.allclose(x.length, 0.5)        
+                assert num.allclose(x.normal, [-1,0])
+                
+            if x.triangle_id == 2:
+                assert num.allclose(x.length, s2)
+                assert num.allclose(x.normal, [-s2,-s2])
+
+
+
+    def test_get_intersecting_segments5(self):
+        """test_get_intersecting_segments(self):
+
+        More complex poly line
+        
+        """
+
+
+
+        s2 = sqrt(2.0)/2
+        
+
+        # Build test mesh
+        
+        # Create basic mesh
+        # 9 points at (0,0), (0, 1), ..., (2,2)
+        # 8 triangles enumerated from left bottom to right top.
+        points, vertices, boundary = rectangular(2, 2, 2, 2)
+        mesh = Mesh(points, vertices, boundary)
+        
+
+        # Polyline with three segments cutting through mesh
+        line = [[0.5, 3], [0.5, 1.5], [1.25, 0.75]] 
+
+        L = mesh.get_intersecting_segments(line)
+        assert len(L) == 3
+
+        for x in L:
+            if x.triangle_id == 3:
+                assert num.allclose(x.length, 0.5)        
+                assert num.allclose(x.normal, [-1,0])
+                
+            if x.triangle_id == 2:
+                msg = str(x.length)
+                assert num.allclose(x.length, s2), msg
+                assert num.allclose(x.normal, [-s2,-s2])
+
+            if x.triangle_id == 5:
+                segvec = num.array([line[2][0]-1,
+                                    line[2][1]-1])
+                msg = str(x.length)
+                assert num.allclose(x.length, sqrt(sum(segvec**2))), msg
+                assert num.allclose(x.normal, [-s2,-s2])                                                
+
+
+    def test_get_intersecting_segments6(self):
+        """test_get_intersecting_segments(self):
+
+        Even more complex poly line, where line breaks within triangle 5
+
+        5 segments are returned even though only four triangles [3,2,5,6] are touched.
+        Triangle 5 therefor has two segments in it.
+        
+        """
+
+
+
+        s2 = sqrt(2.0)/2
+        
+
+        # Build test mesh
+        
+        # Create basic mesh
+        # 9 points at (0,0), (0, 1), ..., (2,2)
+        # 8 triangles enumerated from left bottom to right top.
+        points, vertices, boundary = rectangular(2, 2, 2, 2)
+        mesh = Mesh(points, vertices, boundary)
+        
+
+        # Polyline with three segments cutting through mesh
+        line = [[0.5, 3], [0.5, 1.5], [1.25, 0.75], [2.25, 1.75]]
+
+        L = mesh.get_intersecting_segments(line)
+        #for x in L:
+        #    print x
+
+        assert len(L) == 5
+
+        for x in L:
+            if x.triangle_id == 3:
+                assert num.allclose(x.length, 0.5)        
+                assert num.allclose(x.normal, [-1,0])
+                
+            if x.triangle_id == 2:
+                msg = str(x.length)
+                assert num.allclose(x.length, s2), msg
+                assert num.allclose(x.normal, [-s2,-s2])
+
+            if x.triangle_id == 5:
+                if x.segment == ((1.0, 1.0), (1.25, 0.75)):                    
+                    segvec = num.array([line[2][0]-1,
+                                        line[2][1]-1])
+                    msg = str(x.length)
+                    assert num.allclose(x.length, sqrt(sum(segvec**2))), msg
+                    assert num.allclose(x.normal, [-s2,-s2])
+                elif x.segment == ((1.25, 0.75), (1.5, 1.0)):
+                    segvec = num.array([1.5-line[2][0],
+                                        1.0-line[2][1]])
+                    
+                    assert num.allclose(x.length, sqrt(sum(segvec**2))), msg
+                    assert num.allclose(x.normal, [s2,-s2])
+                else:
+                    msg = 'Unknown segment: %s' %x.segment
+                    raise Exception(msg)
+                
+
+                    
+            if x.triangle_id == 6:
+                assert num.allclose(x.normal, [s2,-s2])
+                assert num.allclose(x.segment, ((1.5, 1.0), (2, 1.5)))
+
+
+      # Internal test that sum of line segments add up
+      # to length of input line
+      #
+      # Could be useful perhaps
+      #
+      #xi1 = line[1][0]
+      #eta1 = line[1][1]
+      #linevector = num.array([xi1-xi0, eta1-eta0])
+      #linelength = sqrt(sum(linevector**2))
+      #
+      #segmentlength = 0
+      #for segment in triangle_intersections:
+      #    vector = array([segment[1][0] - segment[0][0],
+      #                    segment[1][1] - segment[0][1]])
+      #    length = sqrt(sum(vector**2))      
+      #    segmentlength += length
+      #
+      #msg = 'Sum of intersecting segments do not add up'    
+      #assert allclose(segmentlength, linelength), msg    
+
+
+
+
+    def test_get_intersecting_segments7(self):
+        """test_get_intersecting_segments(self):
+
+        Check that line can stop inside a triangle - this is from
+        flow throug a cross sections example in test_datamanager.
+        
+        """
+
+        # Build test mesh
+        width = 5
+        length = 100
+        t_end = 1
+        points, vertices, boundary = rectangular(length, width,
+                                                 length, width)
+
+        mesh = Mesh(points, vertices, boundary)
+        
+
+        # A range of partial lines
+        x = length/2.
+        for i in range(10):
+            start_point = [length/2., i*width/10.]
+            #print 
+            #print start_point
+                            
+            line = [start_point, [length/2., width]]
+ 
+            L = mesh.get_intersecting_segments(line)
+
+            if start_point[1] < 1:
+                assert len(L) == 5
+                
+            
+            total_length = 0    
+            for x in L:
+                total_length += x.length
+                
+
+            ref_length = line[1][1] - line[0][1]
+            #print ref_length, total_length
+            assert num.allclose(total_length, ref_length)
+
+
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Mesh, 'test_mesh_and_neighbours')
+    runner = unittest.TextTestRunner()#verbosity=2)
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_pmesh2domain.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_pmesh2domain.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_pmesh2domain.py	(revision 9460)
@@ -0,0 +1,260 @@
+#!/usr/bin/env python
+#
+
+import unittest
+
+from anuga.abstract_2d_finite_volumes.pmesh2domain import *
+
+from anuga.shallow_water.shallow_water_domain import Domain
+from anuga.abstract_2d_finite_volumes.generic_boundary_conditions \
+                        import Dirichlet_boundary
+
+from anuga.coordinate_transforms.geo_reference import Geo_reference
+from anuga.pmesh.mesh import importMeshFromFile
+
+import numpy as num
+
+
+class Test_pmesh2domain(unittest.TestCase):
+
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+    def test_pmesh2Domain(self):
+         import os
+         import tempfile
+
+         fileName = tempfile.mktemp(".tsh")
+         file = open(fileName,"w")
+         file.write("4 3 # <vertex #> <x> <y> [attributes]\n \
+0 0.0 0.0 0.0 0.0 0.01 \n \
+1 1.0 0.0 10.0 10.0 0.02  \n \
+2 0.0 1.0 0.0 10.0 0.03  \n \
+3 0.5 0.25 8.0 12.0 0.04  \n \
+# Vert att title  \n \
+elevation  \n \
+stage  \n \
+friction  \n \
+2 # <triangle #> [<vertex #>] [<neigbouring triangle #>]  \n\
+0 0 3 2 -1  -1  1 dsg\n\
+1 0 1 3 -1  0 -1   ole nielsen\n\
+4 # <segment #> <vertex #>  <vertex #> [boundary tag] \n\
+0 1 0 2 \n\
+1 0 2 3 \n\
+2 2 3 \n\
+3 3 1 1 \n\
+3 0 # <x> <y> [attributes] ...Mesh Vertices... \n \
+0 216.0 -86.0 \n \
+1 160.0 -167.0 \n \
+2 114.0 -91.0 \n \
+3 # <vertex #>  <vertex #> [boundary tag] ...Mesh Segments... \n \
+0 0 1 0 \n \
+1 1 2 0 \n \
+2 2 0 0 \n \
+0 # <x> <y> ...Mesh Holes... \n \
+0 # <x> <y> <attribute>...Mesh Regions... \n \
+0 # <x> <y> <attribute>...Mesh Regions, area... \n\
+#Geo reference \n \
+56 \n \
+140 \n \
+120 \n")
+         file.close()
+
+         tags = {}
+         b1 =  Dirichlet_boundary(dirichlet_values = num.array([0.0]))
+         b2 =  Dirichlet_boundary(dirichlet_values = num.array([1.0]))
+         b3 =  Dirichlet_boundary(dirichlet_values = num.array([2.0]))
+         tags["1"] = b1
+         tags["2"] = b2
+         tags["3"] = b3
+
+         domain = pmesh_to_domain_instance(fileName, Domain)
+         os.remove(fileName)
+         #print "domain.tagged_elements", domain.tagged_elements
+         ## check the quantities
+         #print domain.quantities['elevation'].vertex_values
+         answer = [[0., 8., 0.],
+                   [0., 10., 8.]]
+         assert num.allclose(domain.quantities['elevation'].vertex_values,
+                             answer)
+
+         #print domain.quantities['stage'].vertex_values
+         answer = [[0., 12., 10.],
+                   [0., 10., 12.]]
+         assert num.allclose(domain.quantities['stage'].vertex_values,
+                             answer)
+
+         #print domain.quantities['friction'].vertex_values
+         answer = [[0.01, 0.04, 0.03],
+                   [0.01, 0.02, 0.04]]
+         assert num.allclose(domain.quantities['friction'].vertex_values,
+                             answer)
+
+         #print domain.quantities['friction'].vertex_values
+         tagged_elements = domain.get_tagged_elements()
+         assert num.allclose(tagged_elements['dsg'][0],0)
+         assert num.allclose(tagged_elements['ole nielsen'][0],1)
+
+         self.failUnless( domain.boundary[(1, 0)]  == '1',
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+         self.failUnless( domain.boundary[(1, 2)]  == '2',
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+         self.failUnless( domain.boundary[(0, 1)]  == '3',
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+         self.failUnless( domain.boundary[(0, 0)]  == 'exterior',
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+         #print "domain.boundary",domain.boundary
+         self.failUnless( len(domain.boundary)  == 4,
+                          "test_pmesh2Domain Too many boundaries")
+         #FIXME change to use get_xllcorner
+         #print "d.geo_reference.xllcorner",domain.geo_reference.xllcorner 
+         self.failUnless(domain.geo_reference.xllcorner  == 140.0,
+                          "bad geo_referece")
+    #************
+    
+    def test_pmesh2Domain_instance(self):
+         import os
+         import tempfile
+
+         fileName = tempfile.mktemp(".tsh")
+         file = open(fileName,"w")
+         file.write("4 3 # <vertex #> <x> <y> [attributes]\n \
+0 0.0 0.0 0.0 0.0 0.01 \n \
+1 1.0 0.0 10.0 10.0 0.02  \n \
+2 0.0 1.0 0.0 10.0 0.03  \n \
+3 0.5 0.25 8.0 12.0 0.04  \n \
+# Vert att title  \n \
+elevation  \n \
+stage  \n \
+friction  \n \
+2 # <triangle #> [<vertex #>] [<neigbouring triangle #>]  \n\
+0 0 3 2 -1  -1  1 dsg\n\
+1 0 1 3 -1  0 -1   ole nielsen\n\
+4 # <segment #> <vertex #>  <vertex #> [boundary tag] \n\
+0 1 0 2 \n\
+1 0 2 3 \n\
+2 2 3 \n\
+3 3 1 1 \n\
+3 0 # <x> <y> [attributes] ...Mesh Vertices... \n \
+0 216.0 -86.0 \n \
+1 160.0 -167.0 \n \
+2 114.0 -91.0 \n \
+3 # <vertex #>  <vertex #> [boundary tag] ...Mesh Segments... \n \
+0 0 1 0 \n \
+1 1 2 0 \n \
+2 2 0 0 \n \
+0 # <x> <y> ...Mesh Holes... \n \
+0 # <x> <y> <attribute>...Mesh Regions... \n \
+0 # <x> <y> <attribute>...Mesh Regions, area... \n\
+#Geo reference \n \
+56 \n \
+140 \n \
+120 \n")
+         file.close()
+
+         mesh_instance = importMeshFromFile(fileName)
+        
+         tags = {}
+         b1 =  Dirichlet_boundary(dirichlet_values = num.array([0.0]))
+         b2 =  Dirichlet_boundary(dirichlet_values = num.array([1.0]))
+         b3 =  Dirichlet_boundary(dirichlet_values = num.array([2.0]))
+         tags["1"] = b1
+         tags["2"] = b2
+         tags["3"] = b3
+
+         domain = pmesh_to_domain_instance(mesh_instance, Domain)
+
+         os.remove(fileName)
+         #print "domain.tagged_elements", domain.tagged_elements
+         ## check the quantities
+         #print domain.quantities['elevation'].vertex_values
+         answer = [[0., 8., 0.],
+                   [0., 10., 8.]]
+         assert num.allclose(domain.quantities['elevation'].vertex_values,
+                             answer)
+
+         #print domain.quantities['stage'].vertex_values
+         answer = [[0., 12., 10.],
+                   [0., 10., 12.]]
+         assert num.allclose(domain.quantities['stage'].vertex_values,
+                             answer)
+
+         #print domain.quantities['friction'].vertex_values
+         answer = [[0.01, 0.04, 0.03],
+                   [0.01, 0.02, 0.04]]
+         assert num.allclose(domain.quantities['friction'].vertex_values,
+                             answer)
+
+         #print domain.quantities['friction'].vertex_values
+         tagged_elements = domain.get_tagged_elements()         
+         assert num.allclose(tagged_elements['dsg'][0],0)
+         assert num.allclose(tagged_elements['ole nielsen'][0],1)
+
+         self.failUnless( domain.boundary[(1, 0)]  == '1',
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+         self.failUnless( domain.boundary[(1, 2)]  == '2',
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+         self.failUnless( domain.boundary[(0, 1)]  == '3',
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+         self.failUnless( domain.boundary[(0, 0)]  == 'exterior',
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+         #print "domain.boundary",domain.boundary
+         self.failUnless( len(domain.boundary)  == 4,
+                          "test_pmesh2Domain Too many boundaries")
+         #FIXME change to use get_xllcorner
+         #print "d.geo_reference.xllcorner",domain.geo_reference.xllcorner 
+         self.failUnless(domain.geo_reference.xllcorner  == 140.0,
+                          "bad geo_referece")
+         
+    #***********
+    def old_test_tags_to_boundaries (self):
+         meshDict = {}
+         p0 = [0.0, 0.0]
+         p1 = [1.0, 0.0]
+         p2 = [0.0, 1.0]
+         p3 = [0.646446609407, 0.353553390593]
+         meshDict['vertices'] = [p0,p1,p2,p3]
+         meshDict['vertex_attributes'] = [[0.0, 0.0,7.0],[10.0, 0.0,7.0],[0.0, 10.0,7.0],[6.46446609407, 3.53553390593,7.0]]
+         meshDict['triangles'] = [[0,3,2],[0,1,3]]
+         meshDict['triangle_tags'] = [6.6,6.6]
+         meshDict['triangle_neighbors'] = [[-1,-1,1],[-1,0,-1]]
+         meshDict['segments'] = [[1,0],[0,2],[2,3],[3,1]]
+         meshDict['segment_tags'] = [2,3,1,1]
+
+         domain = Domain.pmesh_dictionary_to_domain(meshDict)
+
+         #domain.set_tag_dict(tag_dict)
+         #Boundary tests
+         b1 =  Dirichlet_boundary(conserved_quantities = num.array([0.0]))
+         b2 =  Dirichlet_boundary(conserved_quantities = num.array([1.0]))
+         b3 =  Dirichlet_boundary(conserved_quantities = num.array([1.0]))
+         #test adding a boundary
+         tags = {}
+         tags[1] = b1
+         tags[2] = b2
+         tags[3] = b3
+         domain.set_boundary(tags)
+         inverted_id = Volume.instances[0].neighbours[0]
+         id = -(inverted_id+1)
+         boundary_value = Boundary_value.instances[id]
+         boundary_obj = boundary_value.boundary_object
+
+         self.failUnless( boundary_obj  == b1,
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+
+         inverted_id = Volume.instances[0].neighbours[1]
+         id = -(inverted_id+1)
+         boundary_value = Boundary_value.instances[id]
+         boundary_obj = boundary_value.boundary_object
+         self.failUnless( boundary_obj  == b3,
+                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
+
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_pmesh2domain, 'test')
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_quantity.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_quantity.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_quantity.py	(revision 9460)
@@ -0,0 +1,2859 @@
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt, pi
+import tempfile
+
+from anuga.abstract_2d_finite_volumes.quantity import *
+from anuga.config import epsilon
+
+from anuga.fit_interpolate.fit import fit_to_mesh
+#from anuga.pyvolution.least_squares import fit_to_mesh         
+from anuga.abstract_2d_finite_volumes.generic_domain \
+                import Generic_Domain
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+from anuga.coordinate_transforms.geo_reference import Geo_reference
+from anuga.geometry.polygon import *
+
+import numpy as num
+
+
+#Aux for fit_interpolate.fit example
+def linear_function(point):
+    point = num.array(point)
+    return point[:,0]+3*point[:,1]
+    #return point[:,1]
+
+
+def axes2points(x, y):
+    """Generate all combinations of grid point coordinates from x and y axes
+
+    Args:
+        * x: x coordinates (array)
+        * y: y coordinates (array)
+
+    Returns:
+        * P: Nx2 array consisting of coordinates for all
+             grid points defined by x and y axes. The x coordinate
+             will vary the fastest to match the way 2D numpy
+             arrays are laid out by default ('C' order). That way,
+             the x and y coordinates will match a corresponding
+             2D array A when flattened (A.flat[:] or A.reshape(-1))
+
+    Note:
+        Example
+
+        x = [1, 2, 3]
+        y = [10, 20]
+
+        P = [[1, 10],
+             [2, 10],
+             [3, 10],
+             [1, 20],
+             [2, 20],
+             [3, 20]]
+    """
+    import numpy 
+    
+    # Reverse y coordinates to have them start at bottom of array
+    y = numpy.flipud(y)
+
+    # Repeat x coordinates for each y (fastest varying)
+    X = numpy.kron(numpy.ones(len(y)), x)
+
+    # Repeat y coordinates for each x (slowest varying)
+    Y = numpy.kron(y, numpy.ones(len(x)))
+
+    # Check
+    N = len(X)
+    assert len(Y) == N
+
+    # Create Nx2 array of x and y coordinates
+    X = numpy.reshape(X, (N, 1))
+    Y = numpy.reshape(Y, (N, 1))
+    P = numpy.concatenate((X, Y), axis=1)
+
+    # Return
+    return P
+
+
+
+class Test_Quantity(unittest.TestCase):
+    def setUp(self):
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        self.mesh1 = Generic_Domain(points[:3], [elements[0]])
+        self.mesh1.check_integrity()
+        
+        #print self.mesh1.__class__
+        #print isinstance(self.mesh1, Domain)
+
+        self.mesh4 = Generic_Domain(points, elements)
+        self.mesh4.check_integrity()
+
+        # UTM round Onslow
+        a = [240000, 7620000]
+        b = [240000, 7680000]
+        c = [300000, 7620000]
+
+        points = [a, b, c]
+        elements = [[0,2,1]]
+        
+        self.mesh_onslow = Generic_Domain(points, elements)
+        self.mesh_onslow.check_integrity()
+        
+    def tearDown(self):
+        pass
+        #print "  Tearing down"
+
+
+    def test_creation(self):
+
+        quantity = Quantity(self.mesh1, [[1,2,3]])
+        assert num.allclose(quantity.vertex_values, [[1.,2.,3.]])
+
+        try:
+            quantity = Quantity()
+        except:
+            pass
+        else:
+            raise Exception('Should have raised empty quantity exception')
+
+
+        # FIXME(Ole): Temporarily disabled 18 Jan 2009
+        #try:
+        #    quantity = Quantity([1,2,3])
+        #except AssertionError:
+        #    pass
+        #except:
+        #    raise Exception('Should have raised "mising mesh object" error')
+
+
+    def test_creation_zeros(self):
+
+        quantity = Quantity(self.mesh1)
+        assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
+
+
+        quantity = Quantity(self.mesh4)
+        assert num.allclose(quantity.vertex_values, [[0.,0.,0.], [0.,0.,0.],
+                                                     [0.,0.,0.], [0.,0.,0.]])
+
+    def test_set_boundary_values(self):
+
+        quantity = Quantity(self.mesh1)
+
+        quantity.set_boundary_values()
+
+        assert  num.allclose(quantity.boundary_values, [0.0, 0.0, 0.0])
+
+
+    def test_set_boundary_values_with_function(self):
+
+        quantity = Quantity(self.mesh1)
+        #assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
+
+        def simple(x,y):
+            return x+3*y
+
+        quantity.set_boundary_values(simple)
+
+        assert  num.allclose(quantity.boundary_values, [1.0, 4.0, 3.0])
+
+    def test_set_boundary_values_with_constant(self):
+
+        quantity = Quantity(self.mesh1)
+        #assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
+
+        quantity.set_boundary_values(10.0)
+
+        assert  num.allclose(quantity.boundary_values, [10.0, 10.0, 10.0])
+
+
+    def test_set_boundary_values_with_array(self):
+
+        quantity = Quantity(self.mesh1)
+        #assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
+
+
+        quantity.set_boundary_values([10.0, 4.0, 5.0])
+
+        assert  num.allclose(quantity.boundary_values, [10.0, 4.0, 5.0])
+
+    def test_set_boundary_values_with_wrong_sized_array(self):
+
+        quantity = Quantity(self.mesh1)
+        #assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
+
+        try:
+            quantity.set_boundary_values([10.0, 4.0, 5.0, 8.0])
+        except:
+            pass
+        else:
+            msg = 'Should have caught this'
+            raise Exception(msg)
+
+    def test_set_boundary_values_from_edges(self):
+
+        quantity = Quantity(self.mesh4)
+
+        def simple(x,y):
+            return x+3*y
+
+        quantity.set_values(simple)
+
+        assert  num.allclose(quantity.boundary_values, [  0.,   0.,   0.,   0.,  0.,   0.])
+
+        quantity.set_boundary_values_from_edges()
+
+        assert  num.allclose(quantity.boundary_values, [  1.,   3.,   3.,   6.,  10.,   9.])
+
+        
+    def test_interpolation(self):
+        quantity = Quantity(self.mesh1, [[1,2,3]])
+        assert num.allclose(quantity.centroid_values, [2.0]) #Centroid
+
+        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5]])
+
+
+    def test_interpolation2(self):
+        quantity = Quantity(self.mesh4,
+                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
+
+
+        quantity.extrapolate_second_order()
+
+        #print quantity.vertex_values
+        assert num.allclose(quantity.vertex_values, [[3.5, -1.0, 3.5],
+                                                     [3.+2./3, 6.+2./3, 4.+2./3],
+                                                 [4.6, 3.4, 1.],
+                                                 [-5.0, 1.0, 4.0]])
+
+        #print quantity.edge_values
+        assert num.allclose(quantity.edge_values, [[1.25, 3.5, 1.25],
+                                                   [5. + 2/3.0, 4.0 + 1.0/6, 5.0 + 1.0/6],
+                                                   [2.2, 2.8, 4.0],
+                                                   [2.5, -0.5, -2.0]])
+        
+    def test_save_to_array(self):
+        quantity = Quantity(self.mesh4,
+                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+        
+        
+        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
+
+        cellsize = 1.0
+        x,y,z = quantity.save_to_array(cellsize=cellsize, smooth=False)
+        #x,y,z = quantity.save_to_array(smooth=False)
+        
+        from pprint import pprint
+        #pprint(x)
+        #pprint(y)
+        #pprint(z)
+        
+        
+        x_ex = [ 0.,  1.,  2.,  3.,  4.]
+        y_ex = [ 0.,  1.,  2.,  3.,  4.]
+        
+        z_ex = [[  2.00000000e+00,   2.50000000e+00,   0.00000000e+00,
+          4.50000000e+00,   9.00000000e+00],
+       [  1.50000000e+00,   5.00000000e+00,   0.00000000e+00,
+          4.50000000e+00,  -9.99900000e+03],
+       [  3.00000000e+00,   3.00000000e+00,   3.00000000e+00,
+         -9.99900000e+03,  -9.99900000e+03],
+       [ -1.50000000e+00,  -1.50000000e+00,  -9.99900000e+03,
+         -9.99900000e+03,  -9.99900000e+03],
+       [ -6.00000000e+00,  -9.99900000e+03,  -9.99900000e+03,
+         -9.99900000e+03,  -9.99900000e+03]]
+
+        assert num.allclose(x_ex,x)
+        assert num.allclose(y_ex,y)
+        assert num.allclose(z_ex,z)
+                
+               
+        Plot = False 
+        if Plot: 
+            import pylab
+            import numpy
+            #a = numpy.where(a == -9999, numpy.nan, a)
+            #a = numpy.where(a > 10.0, numpy.nan, a)
+        
+            #z = z[::-1,:]
+
+            
+            print z
+            print z.shape
+            print x
+            print y
+
+            nrows = z.shape[0]
+            ncols = z.shape[1]            
+        
+            ratio = float(nrows)/float(ncols)
+            print ratio
+            
+            #y = numpy.arange(nrows)*cellsize
+            #x = numpy.arange(ncols)*cellsize
+        
+            #Setup fig size to correpond to array size
+            fig = pylab.figure(figsize=(10, 10*ratio))
+        
+            levels = numpy.arange(-7, 10, 0.1)
+            CF = pylab.contourf(x,y,z, levels=levels)
+            CB = pylab.colorbar(CF, shrink=0.8, extend='both')
+            #CC = pylab.contour(x,y,a, levels=levels)
+            
+            pylab.show()
+        
+
+
+        x,y,z = quantity.save_to_array(cellsize=cellsize, smooth=True)
+        
+        
+        x_ex = [ 0.,  1.,  2.,  3.,  4.]
+        y_ex = [ 0.,  1.,  2.,  3.,  4.]
+        z_ex = [[  2.00000000e+00,   2.33333333e+00,   2.66666667e+00,
+          5.83333333e+00,   9.00000000e+00],
+       [  2.50000000e+00,   2.83333333e+00,   2.66666667e+00,
+          5.83333333e+00,  -9.99900000e+03],
+       [  3.00000000e+00,   2.83333333e+00,   2.66666667e+00,
+         -9.99900000e+03,  -9.99900000e+03],
+       [ -1.50000000e+00,  -1.66666667e+00,  -9.99900000e+03,
+         -9.99900000e+03,  -9.99900000e+03],
+       [ -6.00000000e+00,  -9.99900000e+03,  -9.99900000e+03,
+         -9.99900000e+03,  -9.99900000e+03]]
+
+        #pprint(z)
+        assert num.allclose(x_ex,x)
+        assert num.allclose(y_ex,y)
+        assert num.allclose(z_ex,z)
+        
+        if Plot:
+            import pylab
+            import numpy
+            #a = numpy.where(a == -9999, numpy.nan, a)
+            #a = numpy.where(a > 10.0, numpy.nan, a)
+        
+            #a = a[::-1,:]
+            nrows = z.shape[0]
+            ncols = z.shape[1]
+        
+            ratio = float(nrows)/float(ncols)
+            print ratio
+        
+            #Setup fig size to correpond to array size
+            fig = pylab.figure(figsize=(10, 10*ratio))
+        
+            levels = numpy.arange(-7, 10, 0.1)
+            CF = pylab.contourf(x,y,z, levels=levels)
+            CB = pylab.colorbar(CF, shrink=0.8, extend='both')
+            #CC = pylab.contour(x,y,a, levels=[0.0,1.0,2.0,3.0])
+            
+            pylab.show()        
+        
+
+
+
+
+    def test_get_extrema_1(self):
+        quantity = Quantity(self.mesh4,
+                                      [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroids
+
+        v = quantity.get_maximum_value()
+        assert v == 5
+
+        v = quantity.get_minimum_value()
+        assert v == 0        
+
+        i = quantity.get_maximum_index()
+        assert i == 1
+
+        i = quantity.get_minimum_index()
+        assert i == 3        
+        
+        x,y = quantity.get_maximum_location()
+        xref, yref = 4.0/3, 4.0/3
+        assert x == xref
+        assert y == yref
+
+        v = quantity.get_values(interpolation_points = [[x,y]])
+        assert num.allclose(v, 5)
+
+
+        x,y = quantity.get_minimum_location()
+        v = quantity.get_values(interpolation_points = [[x,y]])
+        assert num.allclose(v, 0)
+
+
+    def test_get_maximum_2(self):
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        domain = Generic_Domain(points, vertices)
+
+        quantity = Quantity(domain)
+        quantity.set_values(lambda x, y: x+2*y) #2 4 4 6
+        
+        v = quantity.get_maximum_value()
+        assert v == 6
+
+        v = quantity.get_minimum_value()
+        assert v == 2        
+
+        i = quantity.get_maximum_index()
+        assert i == 3
+
+        i = quantity.get_minimum_index()
+        assert i == 0        
+        
+        x,y = quantity.get_maximum_location()
+        xref, yref = 2.0/3, 8.0/3
+        assert x == xref
+        assert y == yref
+
+        v = quantity.get_values(interpolation_points = [[x,y]])
+        assert num.allclose(v, 6)
+
+        x,y = quantity.get_minimum_location()        
+        v = quantity.get_values(interpolation_points = [[x,y]])
+        assert num.allclose(v, 2)
+
+        #Multiple locations for maximum -
+        #Test that the algorithm picks the first occurrence        
+        v = quantity.get_maximum_value(indices=[0,1,2])
+        assert num.allclose(v, 4)
+
+        i = quantity.get_maximum_index(indices=[0,1,2])
+        assert i == 1
+        
+        x,y = quantity.get_maximum_location(indices=[0,1,2])
+        xref, yref = 4.0/3, 4.0/3
+        assert x == xref
+        assert y == yref
+
+        v = quantity.get_values(interpolation_points = [[x,y]])
+        assert num.allclose(v, 4)        
+
+        # More test of indices......
+        v = quantity.get_maximum_value(indices=[2,3])
+        assert num.allclose(v, 6)
+
+        i = quantity.get_maximum_index(indices=[2,3])
+        assert i == 3
+        
+        x,y = quantity.get_maximum_location(indices=[2,3])
+        xref, yref = 2.0/3, 8.0/3
+        assert x == xref
+        assert y == yref
+
+        v = quantity.get_values(interpolation_points = [[x,y]])
+        assert num.allclose(v, 6)        
+
+        
+
+    def test_boundary_allocation(self):
+        quantity = Quantity(self.mesh4,
+                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+
+        assert quantity.boundary_values.shape[0] == len(self.mesh4.boundary)
+
+
+    def test_set_values(self):
+        quantity = Quantity(self.mesh4)
+
+        # get referece to data arrays
+        centroid_values = quantity.centroid_values
+        vertex_values = quantity.vertex_values
+
+        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
+                            location = 'vertices')
+        assert num.allclose(quantity.vertex_values,
+                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+
+        assert id(vertex_values) == id(quantity.vertex_values)
+        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
+        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
+                                                   [5., 5., 5.],
+                                                   [4.5, 4.5, 0.],
+                                                   [3.0, -1.5, -1.5]])
+
+
+        # Test default
+        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+        assert num.allclose(quantity.vertex_values,
+                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
+        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
+                                                   [5., 5., 5.],
+                                                   [4.5, 4.5, 0.],
+                                                   [3.0, -1.5, -1.5]])
+
+        # Test centroids
+        quantity.set_values([1,2,3,4], location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [1., 2., 3., 4.]) #Centroid
+
+        # Test exceptions
+        try:
+            quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
+                                location = 'bas kamel tuba')
+        except:
+            pass
+
+
+
+        try:
+            quantity.set_values([[1,2,3], [0,0,9]])
+        except ValueError:
+            pass
+        except:
+            raise Exception('should have raised ValueeError')
+
+
+
+    def test_set_values_const(self):
+        quantity = Quantity(self.mesh4)
+
+        quantity.set_values(1.0, location = 'vertices')
+        assert num.allclose(quantity.vertex_values,
+                            [[1,1,1], [1,1,1], [1,1,1], [1, 1, 1]])
+
+        assert num.allclose(quantity.centroid_values, [1, 1, 1, 1]) #Centroid
+        assert num.allclose(quantity.edge_values, [[1, 1, 1],
+                                                   [1, 1, 1],
+                                                   [1, 1, 1],
+                                                   [1, 1, 1]])
+
+
+        quantity.set_values(2.0, location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [2, 2, 2, 2])
+
+
+    def test_set_values_func(self):
+        quantity = Quantity(self.mesh4)
+
+        def f(x, y):
+            return x+y
+
+        quantity.set_values(f, location = 'vertices')
+        #print "quantity.vertex_values",quantity.vertex_values
+        assert num.allclose(quantity.vertex_values,
+                            [[2,0,2], [2,2,4], [4,2,4], [4,2,4]])
+        assert num.allclose(quantity.centroid_values,
+                            [4.0/3, 8.0/3, 10.0/3, 10.0/3])
+        assert num.allclose(quantity.edge_values,
+                            [[1,2,1], [3,3,2], [3,4,3], [3,4,3]])
+
+
+        quantity.set_values(f, location = 'centroids')
+        assert num.allclose(quantity.centroid_values,
+                            [4.0/3, 8.0/3, 10.0/3, 10.0/3])
+
+
+    def test_integral(self):
+        quantity = Quantity(self.mesh4)
+
+        # Try constants first
+        const = 5
+        quantity.set_values(const, location = 'vertices')
+        #print 'Q', quantity.get_integral()
+
+        assert num.allclose(quantity.get_integral(), self.mesh4.get_area() * const)
+
+        # Try with a linear function
+        def f(x, y):
+            return x+y
+
+        quantity.set_values(f, location = 'vertices')
+
+
+        ref_integral = (4.0/3 + 8.0/3 + 10.0/3 + 10.0/3) * 2
+
+        assert num.allclose (quantity.get_integral(), ref_integral)
+
+    def test_integral_with_region(self):
+        quantity = Quantity(self.mesh4)
+
+        # Try constants first
+        const = 5
+        quantity.set_values(const, location = 'vertices')
+        #print 'Q', quantity.get_integral()
+
+        assert num.allclose(quantity.get_integral(), self.mesh4.get_area() * const)
+
+        # Try with a linear function
+        def f(x, y):
+            return x+y
+
+        quantity.set_values(f, location = 'vertices')
+
+
+        from anuga import Region
+
+        reg1 = Region(self.mesh4, indices=[2])
+        ref_integral = (10.0/3) * 2
+
+        assert num.allclose (quantity.get_integral(region=reg1), ref_integral)
+
+        reg2 = Region(self.mesh4, indices=[2,3])
+        ref_integral = (10.0/3 + 10.0/3) * 2
+
+        assert num.allclose (quantity.get_integral(region=reg2), ref_integral)
+
+        id=[2,3]
+        ref_integral = (10.0/3 + 10.0/3) * 2
+
+        assert num.allclose (quantity.get_integral(indices=id), ref_integral)
+
+    def test_set_vertex_values(self):
+        quantity = Quantity(self.mesh4)
+        quantity.set_vertex_values([0,1,2,3,4,5])
+
+        assert num.allclose(quantity.vertex_values,
+                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+        assert num.allclose(quantity.centroid_values,
+                            [1., 7./3, 11./3, 8./3]) #Centroid
+        assert num.allclose(quantity.edge_values, [[1., 1.5, 0.5],
+                                                   [3., 2.5, 1.5],
+                                                   [3.5, 4.5, 3.],
+                                                   [2.5, 3.5, 2]])
+
+
+    def test_set_vertex_values_subset(self):
+        quantity = Quantity(self.mesh4)
+        quantity.set_vertex_values([0,1,2,3,4,5])
+        quantity.set_vertex_values([0,20,30,50], indices = [0,2,3,5])
+
+        assert num.allclose(quantity.vertex_values,
+                            [[1,0,20], [1,20,4], [4,20,50], [30,1,4]])
+
+
+    def test_set_vertex_values_using_general_interface(self):
+        quantity = Quantity(self.mesh4)
+
+
+        quantity.set_values([0,1,2,3,4,5])
+
+
+        assert num.allclose(quantity.vertex_values,
+                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+        #Centroid
+        assert num.allclose(quantity.centroid_values, [1., 7./3, 11./3, 8./3])
+
+        assert num.allclose(quantity.edge_values, [[1., 1.5, 0.5],
+                                                   [3., 2.5, 1.5],
+                                                   [3.5, 4.5, 3.],
+                                                   [2.5, 3.5, 2]])
+
+
+
+    def test_set_vertex_values_using_general_interface_with_subset(self):
+        """test_set_vertex_values_using_general_interface_with_subset(self):
+        
+        Test that indices and polygon works (for constants values)
+        """
+        
+        quantity = Quantity(self.mesh4)
+
+
+        quantity.set_values([0,2,3,5], indices=[0,2,3,5])
+        assert num.allclose(quantity.vertex_values,
+                            [[0,0,2], [0,2,0], [0,2,5], [3,0,0]])
+
+
+        # Constant
+        quantity.set_values(0.0)
+        quantity.set_values(3.14, indices=[0,2], location='vertices')
+
+        # Indices refer to triangle numbers
+        assert num.allclose(quantity.vertex_values,
+                            [[3.14,3.14,3.14], [0,0,0],
+                             [3.14,3.14,3.14], [0,0,0]])        
+        
+
+
+        # Now try with polygon (pick points where y>2)
+        polygon = [[0,2.1], [4,2.1], [4,7], [0,7]]
+        quantity.set_values(0.0)
+        quantity.set_values(3.14, polygon=polygon)
+        
+        assert num.allclose(quantity.vertex_values,
+                            [[0,0,0], [0,0,0], [0,0,0],
+                             [3.14,3.14,3.14]])                
+
+
+        # Another polygon (pick triangle 1 and 2 (rightmost triangles) 
+        # using centroids
+        polygon = [[2.1, 0.0], [3.5,0.1], [2,2.2], [0.2,2]]
+        quantity.set_values(0.0)
+        quantity.set_values(3.14, location='centroids', polygon=polygon)
+        assert num.allclose(quantity.vertex_values,
+                            [[0,0,0],
+                             [3.14,3.14,3.14],
+                             [3.14,3.14,3.14],                         
+                             [0,0,0]])                
+
+
+        # Same polygon now use vertices (default)
+        polygon = [[2.1, 0.0], [3.5,0.1], [2,2.2], [0.2,2]]
+        quantity.set_values(0.0)
+        #print 'Here 2'
+        quantity.set_values(3.14, polygon=polygon)
+        assert num.allclose(quantity.vertex_values,
+                            [[0,0,0],
+                             [3.14,3.14,3.14],
+                             [3.14,3.14,3.14],                         
+                             [0,0,0]])                
+        
+
+        # Test input checking
+        try:
+            quantity.set_values(3.14, polygon=polygon, indices = [0,2])
+        except:
+            pass
+        else:
+            msg = 'Should have caught this'
+            raise Exception(msg)
+
+
+
+
+
+    def test_set_vertex_values_using_general_interface_subset_and_geo(self):
+        """test_set_vertex_values_using_general_interface_with_subset(self):
+        Test that indices and polygon works using georeferencing
+        """
+        
+        quantity = Quantity(self.mesh4)
+        G = Geo_reference(56, 10, 100)
+        quantity.domain.set_georeference(G)
+
+
+        # Constant
+        quantity.set_values(0.0)
+        quantity.set_values(3.14, indices=[0,2], location='vertices')
+
+        # Indices refer to triangle numbers here - not vertices (why?)
+        assert num.allclose(quantity.vertex_values,
+                            [[3.14,3.14,3.14], [0,0,0],
+                             [3.14,3.14,3.14], [0,0,0]])        
+        
+
+
+        # Now try with polygon (pick points where y>2)
+        polygon = num.array([[0,2.1], [4,2.1], [4,7], [0,7]])
+        polygon += [G.xllcorner, G.yllcorner]
+        
+        quantity.set_values(0.0)
+        quantity.set_values(3.14, polygon=polygon, location='centroids')
+        assert num.allclose(quantity.vertex_values,
+                            [[0,0,0], [0,0,0], [0,0,0],
+                             [3.14,3.14,3.14]])                
+
+
+        # Another polygon (pick triangle 1 and 2 (rightmost triangles)
+        polygon = num.array([[2.1, 0.0], [3.5,0.1], [2,2.2], [0.2,2]])
+        polygon += [G.xllcorner, G.yllcorner]
+        
+        quantity.set_values(0.0)
+        quantity.set_values(3.14, polygon=polygon)
+        msg = ('quantity.vertex_values=\n%s\nshould be close to\n'
+               '[[0,0,0],\n'
+               ' [3.14,3.14,3.14],\n'
+               ' [3.14,3.14,3.14],\n'
+               ' [0,0,0]]' % str(quantity.vertex_values))
+        assert num.allclose(quantity.vertex_values,
+                            [[0,0,0],
+                             [3.14,3.14,3.14],
+                             [3.14,3.14,3.14],                         
+                             [0,0,0]]), msg
+
+
+
+    def test_set_values_using_fit(self):
+
+
+        quantity = Quantity(self.mesh4)
+
+        #Get (enough) datapoints
+        data_points = [[ 0.66666667, 0.66666667],
+                       [ 1.33333333, 1.33333333],
+                       [ 2.66666667, 0.66666667],
+                       [ 0.66666667, 2.66666667],
+                       [ 0.0, 1.0],
+                       [ 0.0, 3.0],
+                       [ 1.0, 0.0],
+                       [ 1.0, 1.0],
+                       [ 1.0, 2.0],
+                       [ 1.0, 3.0],
+                       [ 2.0, 1.0],
+                       [ 3.0, 0.0],
+                       [ 3.0, 1.0]]
+
+        z = linear_function(data_points)
+
+        #Use built-in fit_interpolate.fit
+        quantity.set_values( Geospatial_data(data_points, z), alpha = 0 )
+        #quantity.set_values(points = data_points, values = z, alpha = 0)
+
+
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+        #print quantity.vertex_values, answer
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        #Now try by setting the same values directly
+        vertex_attributes = fit_to_mesh(data_points,
+                                        quantity.domain.get_nodes(),
+                                        quantity.domain.get_triangles(),
+                                        point_attributes=z,
+                                        alpha = 0,
+                                        verbose=False)
+
+        #print vertex_attributes
+        quantity.set_values(vertex_attributes)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+
+
+
+    def test_test_set_values_using_fit_w_geo(self):
+
+
+        #Mesh
+        vertex_coordinates = [[0.76, 0.76],
+                              [0.76, 5.76],
+                              [5.76, 0.76]]
+        triangles = [[0,2,1]]
+
+        mesh_georef = Geo_reference(56,-0.76,-0.76)
+        mesh1 = Generic_Domain(vertex_coordinates, triangles,
+                       geo_reference = mesh_georef)
+        mesh1.check_integrity()
+
+        #Quantity
+        quantity = Quantity(mesh1)
+
+        #Data
+        data_points = [[ 201.0, 401.0],
+                       [ 201.0, 403.0],
+                       [ 203.0, 401.0]]
+
+        z = [2, 4, 4]
+
+        data_georef = Geo_reference(56,-200,-400)
+
+
+        #Reference
+        ref = fit_to_mesh(data_points, vertex_coordinates, triangles,
+                          point_attributes=z,
+                          data_origin = data_georef.get_origin(),
+                          mesh_origin = mesh_georef.get_origin(),
+                          alpha = 0)
+
+        assert num.allclose( ref, [0,5,5] )
+
+
+        #Test set_values
+
+        quantity.set_values( Geospatial_data(data_points, z, data_georef), alpha = 0 )
+
+        #quantity.set_values(points = data_points,
+        #                    values = z,
+        #                    data_georef = data_georef,
+        #                    alpha = 0)
+
+
+        #quantity.set_values(points = data_points,
+        #                    values = z,
+        #                    data_georef = data_georef,
+        #                    alpha = 0)
+        assert num.allclose(quantity.vertex_values.flat, ref)
+
+
+
+        #Test set_values using geospatial data object
+        quantity.vertex_values[:] = 0.0
+
+        geo = Geospatial_data(data_points, z, data_georef)
+
+
+        quantity.set_values(geospatial_data = geo, alpha = 0)
+        assert num.allclose(quantity.vertex_values.flat, ref)
+
+
+
+    def test_set_values_from_file1(self):
+        quantity = Quantity(self.mesh4)
+
+        #Get (enough) datapoints
+        data_points = [[ 0.66666667, 0.66666667],
+                       [ 1.33333333, 1.33333333],
+                       [ 2.66666667, 0.66666667],
+                       [ 0.66666667, 2.66666667],
+                       [ 0.0, 1.0],
+                       [ 0.0, 3.0],
+                       [ 1.0, 0.0],
+                       [ 1.0, 1.0],
+                       [ 1.0, 2.0],
+                       [ 1.0, 3.0],
+                       [ 2.0, 1.0],
+                       [ 3.0, 0.0],
+                       [ 3.0, 1.0]]
+
+        data_geo_spatial = Geospatial_data(data_points,
+                         geo_reference = Geo_reference(56, 0, 0))
+        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(data_points_absolute)
+        att = 'spam_and_eggs'
+        
+        #Create .txt file
+        ptsfile = tempfile.mktemp(".txt")
+        file = open(ptsfile,"w")
+        file.write(" x,y," + att + " \n")
+        for data_point, attribute in map(None, data_points_absolute
+                                         ,attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            file.write(row + "\n")
+        file.close()
+
+
+        #Check that values can be set from file
+        quantity.set_values(filename = ptsfile,
+                            attribute_name = att, alpha = 0)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+
+        #print quantity.vertex_values.flat
+        #print answer
+
+
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        #Check that values can be set from file using default attribute
+        quantity.set_values(filename = ptsfile, alpha = 0)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Cleanup
+        import os
+        os.remove(ptsfile)
+
+
+
+    def Xtest_set_values_from_file_using_polygon(self):
+        """test_set_values_from_file_using_polygon(self):
+        
+        Test that polygon restriction works for general points data
+        """
+        
+        quantity = Quantity(self.mesh4)
+
+        #Get (enough) datapoints
+        data_points = [[ 0.66666667, 0.66666667],
+                       [ 1.33333333, 1.33333333],
+                       [ 2.66666667, 0.66666667],
+                       [ 0.66666667, 2.66666667],
+                       [ 0.0, 1.0],
+                       [ 0.0, 3.0],
+                       [ 1.0, 0.0],
+                       [ 1.0, 1.0],
+                       [ 1.0, 2.0],
+                       [ 1.0, 3.0],
+                       [ 2.0, 1.0],
+                       [ 3.0, 0.0],
+                       [ 3.0, 1.0]]
+
+        data_geo_spatial = Geospatial_data(data_points,
+                         geo_reference = Geo_reference(56, 0, 0))
+        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(data_points_absolute)
+        att = 'spam_and_eggs'
+        
+        #Create .txt file
+        ptsfile = tempfile.mktemp(".txt")
+        file = open(ptsfile,"w")
+        file.write(" x,y," + att + " \n")
+        for data_point, attribute in map(None, data_points_absolute
+                                         ,attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            file.write(row + "\n")
+        file.close()
+
+        # Create restricting polygon (containing node #4 (2,2) and 
+        # centroid of triangle #1 (bce)
+        polygon = [[1.0, 1.0], [4.0, 1.0],
+                   [4.0, 4.0], [1.0, 4.0]]
+
+        #print self.mesh4.nodes
+        #print inside_polygon(self.mesh4.nodes, polygon)
+        assert num.allclose(inside_polygon(self.mesh4.nodes, polygon), 4)
+
+        #print quantity.domain.get_vertex_coordinates()
+        #print quantity.domain.get_nodes()        
+        
+        # Check that values can be set from file
+        quantity.set_values(filename=ptsfile,
+                            polygon=polygon,
+                            location='unique vertices',
+                            alpha=0)
+
+        # Get indices for vertex coordinates in polygon
+        indices = inside_polygon(quantity.domain.get_vertex_coordinates(), 
+                                 polygon)
+        points = take(quantity.domain.get_vertex_coordinates(), indices)
+        
+        answer = linear_function(points)
+
+        #print quantity.vertex_values.flat
+        #print answer
+
+        # Check vertices in polygon have been set
+        assert num.allclose(take(quantity.vertex_values.flat, indices),
+                            answer)
+
+        # Check vertices outside polygon are zero
+        indices = outside_polygon(quantity.domain.get_vertex_coordinates(), 
+                                  polygon)        
+        assert num.allclose(take(quantity.vertex_values.flat, indices),
+                            0.0)        
+
+        #Cleanup
+        import os
+        os.remove(ptsfile)
+
+
+        
+
+    def test_cache_test_set_values_from_file(self):
+        # FIXME (Ole): What is this about?
+        # I don't think it checks anything new
+        quantity = Quantity(self.mesh4)
+
+        #Get (enough) datapoints
+        data_points = [[ 0.66666667, 0.66666667],
+                       [ 1.33333333, 1.33333333],
+                       [ 2.66666667, 0.66666667],
+                       [ 0.66666667, 2.66666667],
+                       [ 0.0, 1.0],
+                       [ 0.0, 3.0],
+                       [ 1.0, 0.0],
+                       [ 1.0, 1.0],
+                       [ 1.0, 2.0],
+                       [ 1.0, 3.0],
+                       [ 2.0, 1.0],
+                       [ 3.0, 0.0],
+                       [ 3.0, 1.0]]
+
+        georef = Geo_reference(56, 0, 0)
+        data_geo_spatial = Geospatial_data(data_points,
+                                           geo_reference=georef)
+                                           
+        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(data_points_absolute)
+        att = 'spam_and_eggs'
+        
+        # Create .txt file
+        ptsfile = tempfile.mktemp(".txt")
+        file = open(ptsfile,"w")
+        file.write(" x,y," + att + " \n")
+        for data_point, attribute in map(None, data_points_absolute
+                                         ,attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            file.write(row + "\n")
+        file.close()
+
+
+        # Check that values can be set from file
+        quantity.set_values(filename=ptsfile,
+                            attribute_name=att, 
+                            alpha=0, 
+                            use_cache=True,
+                            verbose=False)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        # Check that values can be set from file using default attribute
+        quantity.set_values(filename=ptsfile, 
+                            alpha=0)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        # Check cache
+        quantity.set_values(filename=ptsfile,
+                            attribute_name=att, 
+                            alpha=0, 
+                            use_cache=True,
+                            verbose=False)
+        
+        
+        #Cleanup
+        import os
+        os.remove(ptsfile)
+
+    def test_set_values_from_lat_long(self):
+        quantity = Quantity(self.mesh_onslow)
+
+        #Get (enough) datapoints
+        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6]]
+
+        data_geo_spatial = Geospatial_data(data_points,
+                                           points_are_lats_longs=True)
+        points_UTM = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(points_UTM)
+        att = 'elevation'
+        
+        #Create .txt file
+        txt_file = tempfile.mktemp(".txt")
+        file = open(txt_file,"w")
+        file.write(" lat,long," + att + " \n")
+        for data_point, attribute in map(None, data_points, attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            #print "row", row 
+            file.write(row + "\n")
+        file.close()
+
+
+        #Check that values can be set from file
+        quantity.set_values(filename=txt_file,
+                            attribute_name=att, 
+                            alpha=0)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+
+        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
+        #print "answer",answer
+
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        #Check that values can be set from file using default attribute
+        quantity.set_values(filename=txt_file, alpha=0)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Cleanup
+        import os
+        os.remove(txt_file)
+         
+    def test_set_values_from_lat_long(self):
+        quantity = Quantity(self.mesh_onslow)
+
+        #Get (enough) datapoints
+        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6]]
+
+        data_geo_spatial = Geospatial_data(data_points,
+                                           points_are_lats_longs=True)
+        points_UTM = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(points_UTM)
+        att = 'elevation'
+        
+        #Create .txt file
+        txt_file = tempfile.mktemp(".txt")
+        file = open(txt_file,"w")
+        file.write(" lat,long," + att + " \n")
+        for data_point, attribute in map(None, data_points, attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            #print "row", row 
+            file.write(row + "\n")
+        file.close()
+
+
+        #Check that values can be set from file
+        quantity.set_values(filename=txt_file,
+                            attribute_name=att, alpha=0)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+
+        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
+        #print "answer",answer
+
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        #Check that values can be set from file using default attribute
+        quantity.set_values(filename=txt_file, alpha=0)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Cleanup
+        import os
+        os.remove(txt_file)
+        
+    def test_set_values_from_UTM_pts(self):
+        quantity = Quantity(self.mesh_onslow)
+
+        #Get (enough) datapoints
+        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6]]
+
+        data_geo_spatial = Geospatial_data(data_points,
+                                           points_are_lats_longs=True)
+        points_UTM = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(points_UTM)
+        att = 'elevation'
+        
+        #Create .txt file
+        txt_file = tempfile.mktemp(".txt")
+        file = open(txt_file,"w")
+        file.write(" x,y," + att + " \n")
+        for data_point, attribute in map(None, points_UTM, attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            #print "row", row 
+            file.write(row + "\n")
+        file.close()
+
+
+        pts_file = tempfile.mktemp(".pts")        
+        convert = Geospatial_data(txt_file)
+        convert.export_points_file(pts_file)
+
+        #Check that values can be set from file
+        quantity.set_values_from_file(pts_file, att, 0,
+                                      'vertices', None)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
+        #print "answer",answer
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Check that values can be set from file
+        quantity.set_values(filename=pts_file,
+                            attribute_name=att, alpha=0)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
+        #print "answer",answer
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        #Check that values can be set from file using default attribute
+        quantity.set_values(filename=txt_file, alpha=0)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Cleanup
+        import os
+        os.remove(txt_file)
+        os.remove(pts_file)
+        
+    def verbose_test_set_values_from_UTM_pts(self):
+        quantity = Quantity(self.mesh_onslow)
+
+        #Get (enough) datapoints
+        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
+                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
+                       ]
+
+        data_geo_spatial = Geospatial_data(data_points,
+                                           points_are_lats_longs=True)
+        points_UTM = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(points_UTM)
+        att = 'elevation'
+        
+        #Create .txt file
+        txt_file = tempfile.mktemp(".txt")
+        file = open(txt_file,"w")
+        file.write(" x,y," + att + " \n")
+        for data_point, attribute in map(None, points_UTM, attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            #print "row", row 
+            file.write(row + "\n")
+        file.close()
+
+
+        pts_file = tempfile.mktemp(".pts")        
+        convert = Geospatial_data(txt_file)
+        convert.export_points_file(pts_file)
+
+        #Check that values can be set from file
+        quantity.set_values_from_file(pts_file, att, 0,
+                                      'vertices', None, verbose = True,
+                                      max_read_lines=2)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
+        #print "answer",answer
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Check that values can be set from file
+        quantity.set_values(filename=pts_file,
+                            attribute_name=att, alpha=0)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
+        #print "answer",answer
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        #Check that values can be set from file using default attribute
+        quantity.set_values(filename=txt_file, alpha=0)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Cleanup
+        import os
+        os.remove(txt_file)
+        os.remove(pts_file)
+        
+    def test_set_values_from_file_with_georef1(self):
+
+        #Mesh in zone 56 (absolute coords)
+
+        x0 = 314036.58727982
+        y0 = 6224951.2960092
+
+        a = [x0+0.0, y0+0.0]
+        b = [x0+0.0, y0+2.0]
+        c = [x0+2.0, y0+0.0]
+        d = [x0+0.0, y0+4.0]
+        e = [x0+2.0, y0+2.0]
+        f = [x0+4.0, y0+0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        #absolute going in ..
+        mesh4 = Generic_Domain(points, elements,
+                       geo_reference = Geo_reference(56, 0, 0))
+        mesh4.check_integrity()
+        quantity = Quantity(mesh4)
+
+        #Get (enough) datapoints (relative to georef)
+        data_points_rel = [[ 0.66666667, 0.66666667],
+                       [ 1.33333333, 1.33333333],
+                       [ 2.66666667, 0.66666667],
+                       [ 0.66666667, 2.66666667],
+                       [ 0.0, 1.0],
+                       [ 0.0, 3.0],
+                       [ 1.0, 0.0],
+                       [ 1.0, 1.0],
+                       [ 1.0, 2.0],
+                       [ 1.0, 3.0],
+                       [ 2.0, 1.0],
+                       [ 3.0, 0.0],
+                       [ 3.0, 1.0]]
+
+        data_geo_spatial = Geospatial_data(data_points_rel,
+                         geo_reference = Geo_reference(56, x0, y0))
+        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(data_points_absolute)
+        att = 'spam_and_eggs'
+        
+        #Create .txt file
+        ptsfile = tempfile.mktemp(".txt")
+        file = open(ptsfile,"w")
+        file.write(" x,y," + att + " \n")
+        for data_point, attribute in map(None, data_points_absolute
+                                         ,attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            file.write(row + "\n")
+        file.close()
+
+        #file = open(ptsfile, 'r')
+        #lines = file.readlines()
+        #file.close()
+     
+
+        #Check that values can be set from file
+        quantity.set_values(filename=ptsfile,
+                            attribute_name=att, alpha=0)
+        answer = linear_function(quantity.domain.get_vertex_coordinates())
+
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        #Check that values can be set from file using default attribute
+        quantity.set_values(filename=ptsfile, alpha=0)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Cleanup
+        import os
+        os.remove(ptsfile)
+
+
+    def test_set_values_from_file_with_georef2(self):
+
+        #Mesh in zone 56 (relative coords)
+
+        x0 = 314036.58727982
+        y0 = 6224951.2960092
+        #x0 = 0.0
+        #y0 = 0.0
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        mesh4 = Generic_Domain(points, elements,
+                       geo_reference = Geo_reference(56, x0, y0))
+        mesh4.check_integrity()
+        quantity = Quantity(mesh4)
+
+        #Get (enough) datapoints
+        data_points = [[ x0+0.66666667, y0+0.66666667],
+                       [ x0+1.33333333, y0+1.33333333],
+                       [ x0+2.66666667, y0+0.66666667],
+                       [ x0+0.66666667, y0+2.66666667],
+                       [ x0+0.0, y0+1.0],
+                       [ x0+0.0, y0+3.0],
+                       [ x0+1.0, y0+0.0],
+                       [ x0+1.0, y0+1.0],
+                       [ x0+1.0, y0+2.0],
+                       [ x0+1.0, y0+3.0],
+                       [ x0+2.0, y0+1.0],
+                       [ x0+3.0, y0+0.0],
+                       [ x0+3.0, y0+1.0]]
+
+
+        data_geo_spatial = Geospatial_data(data_points,
+                         geo_reference = Geo_reference(56, 0, 0))
+        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
+        attributes = linear_function(data_points_absolute)
+        att = 'spam_and_eggs'
+        
+        #Create .txt file
+        ptsfile = tempfile.mktemp(".txt")
+        file = open(ptsfile,"w")
+        file.write(" x,y," + att + " \n")
+        for data_point, attribute in map(None, data_points_absolute
+                                         ,attributes):
+            row = str(data_point[0]) + ',' + str(data_point[1]) \
+                  + ',' + str(attribute)
+            file.write(row + "\n")
+        file.close()
+
+
+        #Check that values can be set from file
+        quantity.set_values(filename=ptsfile,
+                            attribute_name=att, alpha=0)
+        answer = linear_function(quantity.domain. \
+                                 get_vertex_coordinates(absolute=True))
+
+
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+
+        #Check that values can be set from file using default attribute
+        quantity.set_values(filename=ptsfile, alpha=0)
+        assert num.allclose(quantity.vertex_values.flat, answer)
+
+        #Cleanup
+        import os
+        os.remove(ptsfile)
+
+
+    def test_set_values_from_utm_grid_file(self):
+        
+        
+
+        x0 = 0.0
+        y0 = 0.0
+
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0, 0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0, 0.0]
+
+        points = [a, b, c, d, e, f]
+
+        #bac, bce, ecf, dbe
+        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
+
+        mesh4 = Generic_Domain(points, elements)
+                     #  geo_reference = Geo_reference(56, x0, y0))
+        mesh4.check_integrity()
+        quantity = Quantity(mesh4)
+
+        """ Format of asc file 
+        ncols         11
+        nrows         12
+        xllcorner     240000
+        yllcorner     7620000
+        cellsize      6000
+        NODATA_value  -9999
+        """
+        ncols = 11  # Nx
+        nrows = 12  # Ny
+        xllcorner = x0
+        yllcorner = y0
+        cellsize  = 1.0
+        NODATA_value =  -9999
+        
+        #xllcorner = 0
+        #yllcorner = 100
+        #cellsize  = 10
+        #NODATA_value =  -9999
+        
+        #Create .asc file
+        #txt_file = tempfile.mktemp(".asc")
+        txt_file = 'test_asc.asc'
+        datafile = open(txt_file,"w")
+        datafile.write('ncols '+str(ncols)+"\n")
+        datafile.write('nrows '+str(nrows)+"\n")
+        datafile.write('xllcorner '+str(xllcorner)+"\n")
+        datafile.write('yllcorner '+str(yllcorner)+"\n")
+        datafile.write('cellsize '+str(cellsize)+"\n")
+        datafile.write('NODATA_value '+str(NODATA_value)+"\n")
+        
+        x = num.linspace(xllcorner, xllcorner+(ncols-1)*cellsize, ncols)
+        y = num.linspace(yllcorner, yllcorner+(nrows-1)*cellsize, nrows)
+        points = axes2points(x, y)
+        
+        #print points
+        #print x.shape, x
+        #print y.shape, y
+        
+        datavalues = linear_function(points)
+        #print datavalues 
+        
+        datavalues = datavalues.reshape(nrows,ncols)
+
+        #print datavalues
+        #print datavalues.shape
+        for row in datavalues:
+            #print row
+            datafile.write(" ".join(str(elem) for elem in row) + "\n")         
+        datafile.close()
+
+        #print quantity.vertex_values
+        #print quantity.centroid_values 
+
+        quantity.set_values_from_utm_grid_file(txt_file,
+                             location='vertices',
+                             indices=None,
+                             verbose=False)
+
+        # check order of vertices
+
+        answer = [[  6.,   0.,   2.],
+                  [  6.,   2.,   8.],
+                  [  8.,  2.,   4.],
+                  [ 12.,   6.,   8.]]
+        #print quantity.vertex_values
+        assert num.allclose(quantity.vertex_values, answer)
+        
+        
+        #print quantity.vertex_values
+        #print quantity.centroid_values 
+        quantity.set_values(0.0)
+        
+        
+        #print quantity.vertex_values
+        #print quantity.centroid_values 
+        quantity.set_values_from_utm_grid_file(txt_file,
+                             location='centroids',
+                             indices=None,
+                             verbose=False)
+        
+        #print quantity.vertex_values
+        #print quantity.centroid_values      
+        
+
+        answer = [ 2.66666667,  5.33333333,  4.66666667,  8.66666667]
+        
+        assert num.allclose(quantity.centroid_values, answer)
+        #Cleanup
+        #import os
+        os.remove(txt_file)        
+        
+
+
+    def test_set_values_from_quantity(self):
+
+        quantity1 = Quantity(self.mesh4)
+        quantity1.set_vertex_values([0,1,2,3,4,5])
+
+        assert num.allclose(quantity1.vertex_values,
+                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+
+        quantity2 = Quantity(self.mesh4)
+        quantity2.set_values(quantity=quantity1)
+        assert num.allclose(quantity2.vertex_values,
+                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+        quantity2.set_values(quantity = 2*quantity1)
+        assert num.allclose(quantity2.vertex_values,
+                            [[2,0,4], [2,4,8], [8,4,10], [6,2,8]])
+
+        quantity2.set_values(quantity = 2*quantity1 + 3)
+        assert num.allclose(quantity2.vertex_values,
+                            [[5,3,7], [5,7,11], [11,7,13], [9,5,11]])
+
+
+        #Check detection of quantity as first orgument
+        quantity2.set_values(2*quantity1 + 3)
+        assert num.allclose(quantity2.vertex_values,
+                            [[5,3,7], [5,7,11], [11,7,13], [9,5,11]])
+
+
+
+    def Xtest_set_values_from_quantity_using_polygon(self):
+        """test_set_values_from_quantity_using_polygon(self):
+        
+        Check that polygon can be used to restrict set_values when
+        using another quantity as argument.
+        """
+        
+        # Create restricting polygon (containing node #4 (2,2) and 
+        # centroid of triangle #1 (bce)
+        polygon = [[1.0, 1.0], [4.0, 1.0],
+                   [4.0, 4.0], [1.0, 4.0]]
+        assert num.allclose(inside_polygon(self.mesh4.nodes, polygon), 4)                   
+        
+        quantity1 = Quantity(self.mesh4)
+        quantity1.set_vertex_values([0,1,2,3,4,5])
+
+        assert num.allclose(quantity1.vertex_values,
+                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+
+        quantity2 = Quantity(self.mesh4)
+        quantity2.set_values(quantity=quantity1,
+                             polygon=polygon)
+                             
+        msg = 'Only node #4(e) at (2,2) should have values applied '
+        assert num.allclose(quantity2.vertex_values,
+                            [[0,0,0], [0,0,4], [4,0,0], [0,0,4]]), msg        
+                            #bac,     bce,     ecf,     dbe
+                        
+
+
+    def test_overloading(self):
+
+        quantity1 = Quantity(self.mesh4)
+        quantity1.set_vertex_values([0,1,2,3,4,5])
+
+        assert num.allclose(quantity1.vertex_values,
+                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+
+        quantity2 = Quantity(self.mesh4)
+        quantity2.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
+                             location = 'vertices')
+
+
+
+        quantity3 = Quantity(self.mesh4)
+        quantity3.set_values([[2,2,2], [7,8,9], [7,6,3], [3, 8, -8]],
+                             location = 'vertices')
+
+
+        # Negation
+        Q = -quantity1
+        assert num.allclose(Q.vertex_values, -quantity1.vertex_values)
+        assert num.allclose(Q.centroid_values, -quantity1.centroid_values)
+        assert num.allclose(Q.edge_values, -quantity1.edge_values)
+
+        # Addition
+        Q = quantity1 + 7
+        assert num.allclose(Q.vertex_values, quantity1.vertex_values + 7)
+        assert num.allclose(Q.centroid_values, quantity1.centroid_values + 7)
+        assert num.allclose(Q.edge_values, quantity1.edge_values + 7)
+
+        Q = 7 + quantity1
+        assert num.allclose(Q.vertex_values, quantity1.vertex_values + 7)
+        assert num.allclose(Q.centroid_values, quantity1.centroid_values + 7)
+        assert num.allclose(Q.edge_values, quantity1.edge_values + 7)
+
+        Q = quantity1 + quantity2
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values + quantity2.vertex_values)
+        assert num.allclose(Q.centroid_values,
+                            quantity1.centroid_values + quantity2.centroid_values)
+        assert num.allclose(Q.edge_values,
+                            quantity1.edge_values + quantity2.edge_values)
+
+
+        Q = quantity1 + quantity2 - 3
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values + quantity2.vertex_values - 3)
+
+        Q = quantity1 - quantity2
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values - quantity2.vertex_values)
+
+        #Scaling
+        Q = quantity1*3
+        assert num.allclose(Q.vertex_values, quantity1.vertex_values*3)
+        assert num.allclose(Q.centroid_values, quantity1.centroid_values*3)
+        assert num.allclose(Q.edge_values, quantity1.edge_values*3)
+        Q = 3*quantity1
+        assert num.allclose(Q.vertex_values, quantity1.vertex_values*3)
+
+        #Multiplication
+        Q = quantity1 * quantity2
+        #print Q.vertex_values
+        #print Q.centroid_values
+        #print quantity1.centroid_values
+        #print quantity2.centroid_values
+
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values * quantity2.vertex_values)
+
+        #Linear combinations
+        Q = 4*quantity1 + 2
+        assert num.allclose(Q.vertex_values,
+                            4*quantity1.vertex_values + 2)
+
+        Q = quantity1*quantity2 + 2
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values * quantity2.vertex_values + 2)
+
+        Q = quantity1*quantity2 + quantity3
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values * quantity2.vertex_values +
+                        quantity3.vertex_values)
+        Q = quantity1*quantity2 + 3*quantity3
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values * quantity2.vertex_values +
+                            3*quantity3.vertex_values)
+        Q = quantity1*quantity2 + 3*quantity3 + 5.0
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values * quantity2.vertex_values +
+                            3*quantity3.vertex_values + 5)
+
+        Q = quantity1*quantity2 - quantity3
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values * quantity2.vertex_values -
+                            quantity3.vertex_values)
+        Q = 1.5*quantity1*quantity2 - 3*quantity3 + 5.0
+        assert num.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 num.allclose(Q.vertex_values,
+                            1.5*quantity1.vertex_values * quantity2.vertex_values -
+                            3*quantity3.vertex_values + 5)
+
+
+        #Powers
+        Q = quantity1**2
+        assert num.allclose(Q.vertex_values, quantity1.vertex_values**2)
+
+        Q = quantity1**2 +quantity2**2
+        assert num.allclose(Q.vertex_values,
+                            quantity1.vertex_values**2 + \
+                            quantity2.vertex_values**2)
+
+        Q = (quantity1**2 +quantity2**2)**0.5
+        assert num.allclose(Q.vertex_values,
+                            (quantity1.vertex_values**2 + \
+                            quantity2.vertex_values**2)**0.5)
+
+
+
+
+
+
+
+    def test_compute_gradient(self):
+        quantity = Quantity(self.mesh4)
+
+        #Set up for a gradient of (2,0) at mid triangle
+        quantity.set_values([2.0, 4.0, 6.0, 2.0],
+                            location = 'centroids')
+
+
+        #Gradients
+        quantity.compute_gradients()
+
+        a = quantity.x_gradient
+        b = quantity.y_gradient
+        #print self.mesh4.centroid_coordinates
+        #print a, b
+
+        #The central triangle (1)
+        #(using standard gradient based on neigbours controid values)
+        assert num.allclose(a[1], 2.0)
+        assert num.allclose(b[1], 0.0)
+
+
+        #Left triangle (0) using two point gradient
+        #q0 = q1 + a*(x0-x1) + b*(y0-y1)  <=>
+        #2  = 4  + a*(-2/3)  + b*(-2/3)
+        assert num.allclose(a[0] + b[0], 3)
+        #From orthogonality (a*(y0-y1) + b*(x0-x1) == 0)
+        assert num.allclose(a[0] - b[0], 0)
+
+
+        #Right triangle (2) using two point gradient
+        #q2 = q1 + a*(x2-x1) + b*(y2-y1)  <=>
+        #6  = 4  + a*(4/3)  + b*(-2/3)
+        assert num.allclose(2*a[2] - b[2], 3)
+        #From orthogonality (a*(y1-y2) + b*(x2-x1) == 0)
+        assert num.allclose(a[2] + 2*b[2], 0)
+
+
+        #Top triangle (3) using two point gradient
+        #q3 = q1 + a*(x3-x1) + b*(y3-y1)  <=>
+        #2  = 4  + a*(-2/3)  + b*(4/3)
+        assert num.allclose(a[3] - 2*b[3], 3)
+        #From orthogonality (a*(y1-y3) + b*(x3-x1) == 0)
+        assert num.allclose(2*a[3] + b[3], 0)
+
+
+
+        #print a, b
+        quantity.extrapolate_second_order()
+
+        #Apply q(x,y) = qc + a*(x-xc) + b*(y-yc)
+        assert num.allclose(quantity.vertex_values[0,:], [3., 0.,  3.])
+        assert num.allclose(quantity.vertex_values[1,:], [4./3, 16./3,  16./3])
+
+
+        #a = 1.2, b=-0.6
+        #q(4,0) = 6 + a*(4 - 8/3) + b*(-2/3)
+        assert num.allclose(quantity.vertex_values[2,2], 8)
+
+    def test_get_gradients(self):
+        quantity = Quantity(self.mesh4)
+
+        #Set up for a gradient of (2,0) at mid triangle
+        quantity.set_values([2.0, 4.0, 6.0, 2.0],
+                            location = 'centroids')
+
+
+        #Gradients
+        quantity.compute_gradients()
+
+        a, b = quantity.get_gradients()
+        #print self.mesh4.centroid_coordinates
+        #print a, b
+
+        #The central triangle (1)
+        #(using standard gradient based on neigbours controid values)
+        assert num.allclose(a[1], 2.0)
+        assert num.allclose(b[1], 0.0)
+
+
+        #Left triangle (0) using two point gradient
+        #q0 = q1 + a*(x0-x1) + b*(y0-y1)  <=>
+        #2  = 4  + a*(-2/3)  + b*(-2/3)
+        assert num.allclose(a[0] + b[0], 3)
+        #From orthogonality (a*(y0-y1) + b*(x0-x1) == 0)
+        assert num.allclose(a[0] - b[0], 0)
+
+
+        #Right triangle (2) using two point gradient
+        #q2 = q1 + a*(x2-x1) + b*(y2-y1)  <=>
+        #6  = 4  + a*(4/3)  + b*(-2/3)
+        assert num.allclose(2*a[2] - b[2], 3)
+        #From orthogonality (a*(y1-y2) + b*(x2-x1) == 0)
+        assert num.allclose(a[2] + 2*b[2], 0)
+
+
+        #Top triangle (3) using two point gradient
+        #q3 = q1 + a*(x3-x1) + b*(y3-y1)  <=>
+        #2  = 4  + a*(-2/3)  + b*(4/3)
+        assert num.allclose(a[3] - 2*b[3], 3)
+        #From orthogonality (a*(y1-y3) + b*(x3-x1) == 0)
+        assert num.allclose(2*a[3] + b[3], 0)
+
+
+    def test_second_order_extrapolation2(self):
+        quantity = Quantity(self.mesh4)
+
+        #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.x_gradient
+        b = quantity.y_gradient
+        
+        #print a, b
+
+        assert num.allclose(a[1], 3.0)
+        assert num.allclose(b[1], 1.0)
+
+        #Work out the others
+
+        quantity.extrapolate_second_order()
+
+        #print quantity.vertex_values
+        assert num.allclose(quantity.vertex_values[1,0], 2.0)
+        assert num.allclose(quantity.vertex_values[1,1], 6.0)
+        assert num.allclose(quantity.vertex_values[1,2], 8.0)
+
+
+
+    def test_backup_saxpy_centroid_values(self):
+        quantity = Quantity(self.mesh4)
+
+        #Set up for a gradient of (3,1), f(x) = 3x+y
+        c_values = num.array([2.0+2.0/3, 4.0+4.0/3, 8.0+2.0/3, 2.0+8.0/3])
+        d_values = num.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 num.allclose(quantity.centroid_values, quantity.centroid_backup_values)
+
+
+        quantity.set_values(d_values, location = 'centroids')
+
+        quantity.saxpy_centroid_values(2.0, 3.0)
+
+        assert num.allclose(quantity.centroid_values, 2.0*d_values + 3.0*c_values)
+
+
+
+    def test_first_order_extrapolator(self):
+        quantity = Quantity(self.mesh4)
+
+        #Test centroids
+        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
+
+        #Extrapolate
+        quantity.extrapolate_first_order()
+
+        #Check that gradient is zero
+        a,b = quantity.get_gradients()
+        assert num.allclose(a, [0,0,0,0])
+        assert num.allclose(b, [0,0,0,0])
+
+        #Check vertices but not edge values
+        assert num.allclose(quantity.vertex_values,
+                            [[1,1,1], [2,2,2], [3,3,3], [4, 4, 4]])
+
+
+    def test_second_order_extrapolator(self):
+        quantity = Quantity(self.mesh4)
+
+        #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()
+        quantity.limit()
+
+
+        #Assert that central triangle is limited by neighbours
+        assert quantity.vertex_values[1,0] >= quantity.vertex_values[0,0]
+        assert quantity.vertex_values[1,0] >= quantity.vertex_values[3,1]
+
+        assert quantity.vertex_values[1,1] <= quantity.vertex_values[2,1]
+        assert quantity.vertex_values[1,1] >= quantity.vertex_values[0,2]
+
+        assert quantity.vertex_values[1,2] <= quantity.vertex_values[2,0]
+        assert quantity.vertex_values[1,2] >= quantity.vertex_values[3,1]
+
+
+        #Assert that quantities are conserved
+        for k in range(quantity.centroid_values.shape[0]):
+            assert num.allclose (quantity.centroid_values[k],
+                             num.sum(quantity.vertex_values[k,:])/3)
+
+
+
+
+
+    def test_limit_vertices_by_all_neighbours(self):
+        quantity = Quantity(self.mesh4)
+
+        #Create a deliberate overshoot (e.g. from gradient computation)
+        quantity.set_values([[3,0,3], [2,2,6], [5,3,8], [8,3,5]])
+
+
+        #Limit
+        quantity.limit_vertices_by_all_neighbours()
+
+        #Assert that central triangle is limited by neighbours
+        assert quantity.vertex_values[1,0] >= quantity.vertex_values[0,0]
+        assert quantity.vertex_values[1,0] <= quantity.vertex_values[3,1]
+
+        assert quantity.vertex_values[1,1] <= quantity.vertex_values[2,1]
+        assert quantity.vertex_values[1,1] >= quantity.vertex_values[0,2]
+
+        assert quantity.vertex_values[1,2] <= quantity.vertex_values[2,0]
+        assert quantity.vertex_values[1,2] <= quantity.vertex_values[3,1]
+
+
+
+        #Assert that quantities are conserved
+        for k in range(quantity.centroid_values.shape[0]):
+            assert num.allclose (quantity.centroid_values[k],
+                                 num.sum(quantity.vertex_values[k,:])/3)
+
+
+
+    def test_limit_edges_by_all_neighbours(self):
+        quantity = Quantity(self.mesh4)
+
+        #Create a deliberate overshoot (e.g. from gradient computation)
+        quantity.set_values([[3,0,3], [2,2,6], [5,3,8], [8,3,5]])
+
+
+        #Limit
+        quantity.limit_edges_by_all_neighbours()
+
+        #Assert that central triangle is limited by neighbours
+        assert quantity.edge_values[1,0] <= quantity.centroid_values[2]
+        assert quantity.edge_values[1,0] >= quantity.centroid_values[0]
+
+        assert quantity.edge_values[1,1] <= quantity.centroid_values[2]
+        assert quantity.edge_values[1,1] >= quantity.centroid_values[0]
+
+        assert quantity.edge_values[1,2] <= quantity.centroid_values[2]
+        assert quantity.edge_values[1,2] >= quantity.centroid_values[0]
+
+
+
+        #Assert that quantities are conserved
+        for k in range(quantity.centroid_values.shape[0]):
+            assert num.allclose (quantity.centroid_values[k],
+                                 num.sum(quantity.vertex_values[k,:])/3)
+
+
+    def test_limit_edges_by_neighbour(self):
+        quantity = Quantity(self.mesh4)
+
+        #Create a deliberate overshoot (e.g. from gradient computation)
+        quantity.set_values([[3,0,3], [2,2,6], [5,3,8], [8,3,5]])
+
+
+        #Limit
+        quantity.limit_edges_by_neighbour()
+
+        #Assert that central triangle is limited by neighbours
+        assert quantity.edge_values[1,0] <= quantity.centroid_values[3]
+        assert quantity.edge_values[1,0] >= quantity.centroid_values[1]
+
+        assert quantity.edge_values[1,1] <= quantity.centroid_values[2]
+        assert quantity.edge_values[1,1] >= quantity.centroid_values[1]
+
+        assert quantity.edge_values[1,2] <= quantity.centroid_values[1]
+        assert quantity.edge_values[1,2] >= quantity.centroid_values[0]
+
+
+
+        #Assert that quantities are conserved
+        for k in range(quantity.centroid_values.shape[0]):
+            assert num.allclose (quantity.centroid_values[k],
+                                 num.sum(quantity.vertex_values[k,:])/3)
+
+    def test_limiter2(self):
+        """Taken from test_shallow_water
+        """
+        quantity = Quantity(self.mesh4)
+        quantity.domain.beta_w = 0.9
+        
+        #Test centroids
+        quantity.set_values([2.,4.,8.,2.], location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [2, 4, 8, 2]) #Centroid
+
+
+        #Extrapolate
+        quantity.extrapolate_second_order()
+
+        assert num.allclose(quantity.vertex_values[1,:], [0.0, 6, 6])
+
+        #Limit
+        quantity.limit()
+
+        # limited value for beta_w = 0.9
+        
+        assert num.allclose(quantity.vertex_values[1,:], [2.2, 4.9, 4.9])
+        # limited values for beta_w = 0.5
+        #assert allclose(quantity.vertex_values[1,:], [3.0, 4.5, 4.5])
+
+
+        #Assert that quantities are conserved
+        for k in range(quantity.centroid_values.shape[0]):
+            assert num.allclose (quantity.centroid_values[k],
+                                 num.sum(quantity.vertex_values[k,:])/3)
+
+
+
+
+
+    def test_distribute_first_order(self):
+        quantity = Quantity(self.mesh4)
+
+        #Test centroids
+        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
+
+
+        #Extrapolate from centroid to vertices and edges
+        quantity.extrapolate_first_order()
+
+        #Interpolate
+        #quantity.interpolate_from_vertices_to_edges()
+
+        assert num.allclose(quantity.vertex_values,
+                            [[1,1,1], [2,2,2], [3,3,3], [4, 4, 4]])
+        assert num.allclose(quantity.edge_values, [[1,1,1], [2,2,2],
+                                                   [3,3,3], [4, 4, 4]])
+
+
+    def test_interpolate_from_vertices_to_edges(self):
+        quantity = Quantity(self.mesh4)
+
+        quantity.vertex_values = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.float)
+
+        quantity.interpolate_from_vertices_to_edges()
+
+        assert num.allclose(quantity.edge_values, [[1., 1.5, 0.5],
+                                                   [3., 2.5, 1.5],
+                                                   [3.5, 4.5, 3.],
+                                                   [2.5, 3.5, 2]])
+
+
+    def test_interpolate_from_edges_to_vertices(self):
+        quantity = Quantity(self.mesh4)
+
+        quantity.edge_values = num.array([[1., 1.5, 0.5],
+                                          [3., 2.5, 1.5],
+                                          [3.5, 4.5, 3.],
+                                          [2.5, 3.5, 2]], num.float)
+
+        quantity.interpolate_from_edges_to_vertices()
+
+        assert num.allclose(quantity.vertex_values,
+                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
+
+
+
+    def test_distribute_second_order(self):
+        quantity = Quantity(self.mesh4)
+
+        #Test centroids
+        quantity.set_values([2.,4.,8.,2.], location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [2, 4, 8, 2]) #Centroid
+
+
+        #Extrapolate
+        quantity.extrapolate_second_order()
+
+        assert num.allclose(quantity.vertex_values[1,:], [0.0, 6, 6])
+
+
+    def test_update_explicit(self):
+        quantity = Quantity(self.mesh4)
+
+        #Test centroids
+        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
+
+        #Set explicit_update
+        quantity.explicit_update = num.array( [1.,1.,1.,1.] )
+
+        #Update with given timestep
+        quantity.update(0.1)
+
+        x = num.array([1, 2, 3, 4]) + num.array( [.1,.1,.1,.1] )
+        assert num.allclose( quantity.centroid_values, x)
+
+    def test_update_semi_implicit(self):
+        quantity = Quantity(self.mesh4)
+
+        #Test centroids
+        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
+
+        #Set semi implicit update
+        quantity.semi_implicit_update = num.array([1.,1.,1.,1.])
+
+        #Update with given timestep
+        timestep = 0.1
+        quantity.update(timestep)
+
+        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
+        denom = num.ones(4, num.float)-timestep*sem
+
+        x = num.array([1, 2, 3, 4])/denom
+        assert num.allclose( quantity.centroid_values, x)
+
+
+    def test_both_updates(self):
+        quantity = Quantity(self.mesh4)
+
+        #Test centroids
+        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
+        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
+
+        #Set explicit_update
+        quantity.explicit_update = num.array( [4.,3.,2.,1.] )
+
+        #Set semi implicit update
+        quantity.semi_implicit_update = num.array( [1.,1.,1.,1.] )
+
+        #Update with given timestep
+        timestep = 0.1
+        quantity.update(0.1)
+
+        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
+        denom = num.ones(4, num.float)-timestep*sem
+
+        x = num.array([1., 2., 3., 4.])
+        x += timestep*num.array( [4.0, 3.0, 2.0, 1.0] )        
+        x /= denom
+
+
+        assert num.allclose( quantity.centroid_values, x)
+
+
+
+    def set_array_values_by_index(self):
+
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 1)
+
+        #Create shallow water domain
+        domain = Generic_Domain(points, vertices, boundary)
+        #print "domain.number_of_elements ",domain.number_of_elements
+        quantity = Quantity(domain,[[1,1,1],[2,2,2]])
+        value = [7]
+        indices = [1]
+        quantity.set_array_values_by_index(value,
+                                           location = 'centroids',
+                                           indices = indices)
+        #print "quantity.centroid_values",quantity.centroid_values
+
+        assert num.allclose(quantity.centroid_values, [1,7])
+
+        quantity.set_array_values([15,20,25], indices = indices)
+        assert num.allclose(quantity.centroid_values, [1,20])
+
+        quantity.set_array_values([15,20,25], indices = indices)
+        assert num.allclose(quantity.centroid_values, [1,20])
+
+    def test_setting_some_vertex_values(self):
+        """
+        set values based on triangle lists.
+        """
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+        #print "vertices",vertices
+        #Create shallow water domain
+        domain = Generic_Domain(points, vertices, boundary)
+        #print "domain.number_of_elements ",domain.number_of_elements
+        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5],[6,6,6]])
+
+
+        # Check that constants work
+        value = 7
+        indices = [1]
+        quantity.set_values(value,
+                            location = 'centroids',
+                            indices = indices)
+        #print "quantity.centroid_values",quantity.centroid_values
+        assert num.allclose(quantity.centroid_values, [1,7,3,4,5,6])
+        
+        value = [7]
+        indices = [1]
+        quantity.set_values(value,
+                            location = 'centroids',
+                            indices = indices)
+        #print "quantity.centroid_values",quantity.centroid_values
+        assert num.allclose(quantity.centroid_values, [1,7,3,4,5,6])
+
+        value = [[15,20,25]]
+        quantity.set_values(value, indices = indices)
+        #print "1 quantity.vertex_values",quantity.vertex_values
+        assert num.allclose(quantity.vertex_values[1], value[0])
+
+
+        #print "quantity",quantity.vertex_values
+        values = [10,100,50]
+        quantity.set_values(values, indices = [0,1,5], location = 'centroids')
+        #print "2 quantity.vertex_values",quantity.vertex_values
+        assert num.allclose(quantity.vertex_values[0], [10,10,10])
+        assert num.allclose(quantity.vertex_values[5], [50,50,50])
+        #quantity.interpolate()
+        #print "quantity.centroid_values",quantity.centroid_values
+        assert num.allclose(quantity.centroid_values, [10,100,3,4,5,50])
+
+
+        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5],[6,6,6]])
+        values = [10,100,50]
+        #this will be per unique vertex, indexing the vertices
+        #print "quantity.vertex_values",quantity.vertex_values
+        quantity.set_values(values, indices = [0,1,5])
+        #print "quantity.vertex_values",quantity.vertex_values
+        assert num.allclose(quantity.vertex_values[0], [1,50,10])
+        assert num.allclose(quantity.vertex_values[5], [6,6,6])
+        assert num.allclose(quantity.vertex_values[1], [100,10,50])
+
+        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5],[6,6,6]])
+        values = [[31,30,29],[400,400,400],[1000,999,998]]
+        quantity.set_values(values, indices = [3,3,5])
+        quantity.interpolate()
+        assert num.allclose(quantity.centroid_values, [1,2,3,400,5,999])
+
+        values = [[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5],[6,6,6]]
+        quantity.set_values(values)
+
+        # testing the standard set values by vertex
+        # indexed by vertex_id in general_mesh.coordinates
+        values = [0,1,2,3,4,5,6,7]
+
+        quantity.set_values(values)
+        #print "1 quantity.vertex_values",quantity.vertex_values
+        assert num.allclose(quantity.vertex_values,[[ 4.,  5.,  0.],
+                                                    [ 1.,  0.,  5.],
+                                                    [ 5.,  6.,  1.],
+                                                    [ 2.,  1.,  6.],
+                                                    [ 6.,  7.,  2.],
+                                                    [ 3.,  2.,  7.]])
+
+    def test_setting_unique_vertex_values(self):
+        """
+        set values based on unique_vertex lists.
+        """
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+        #print "vertices",vertices
+        #Create shallow water domain
+        domain = Generic_Domain(points, vertices, boundary)
+        #print "domain.number_of_elements ",domain.number_of_elements
+        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5]])
+        value = 7
+        indices = [1,5]
+        quantity.set_values(value,
+                            location='unique vertices',
+                            indices=indices)
+        #print "quantity.centroid_values",quantity.centroid_values
+        assert num.allclose(quantity.vertex_values[0], [0,7,0])
+        assert num.allclose(quantity.vertex_values[1], [7,1,7])
+        assert num.allclose(quantity.vertex_values[2], [7,2,7])
+
+
+    def test_get_values(self):
+        """
+        get values based on triangle lists.
+        """
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #print "points",points
+        #print "vertices",vertices
+        #print "boundary",boundary
+
+        #Create shallow water domain
+        domain = Generic_Domain(points, vertices, boundary)
+        #print "domain.number_of_elements ",domain.number_of_elements
+        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5]])
+
+        #print "quantity.get_values(location = 'unique vertices')", \
+        #      quantity.get_values(location = 'unique vertices')
+
+        #print "quantity.get_values(location = 'unique vertices')", \
+        #      quantity.get_values(indices=[0,1,2,3,4,5,6,7], \
+        #                          location = 'unique vertices')
+
+        answer = [0.5,2,4,5,0,1,3,4.5]
+        assert num.allclose(answer,
+                            quantity.get_values(location='unique vertices'))
+
+        indices = [0,5,3]
+        answer = [0.5,1,5]
+        assert num.allclose(answer,
+                            quantity.get_values(indices=indices,
+                                                location='unique vertices'))
+        #print "quantity.centroid_values",quantity.centroid_values
+        #print "quantity.get_values(location = 'centroids') ",\
+        #      quantity.get_values(location = 'centroids')
+
+
+
+
+    def test_get_values_2(self):
+        """Different mesh (working with domain object) - also check centroids.
+        """
+
+        
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        domain = Generic_Domain(points, vertices)
+
+        quantity = Quantity(domain)
+        quantity.set_values(lambda x, y: x+2*y) #2 4 4 6
+        
+        assert num.allclose(quantity.get_values(location='centroids'), 
+                            [2,4,4,6])
+                            
+        assert num.allclose(quantity.get_values(location='centroids', 
+                                                indices=[1,3]), [4,6])
+
+
+        assert num.allclose(quantity.get_values(location='vertices'), 
+                            [[4,0,2],
+                             [4,2,6],
+                             [6,2,4],
+                             [8,4,6]])
+        
+        assert num.allclose(quantity.get_values(location='vertices', 
+                                                indices=[1,3]), [[4,2,6],
+                                                                 [8,4,6]])
+
+
+        assert num.allclose(quantity.get_values(location='edges'), 
+                            [[1,3,2],
+                             [4,5,3],
+                             [3,5,4],
+                             [5,7,6]])
+        assert num.allclose(quantity.get_values(location='edges', 
+                                                indices=[1,3]),
+                            [[4,5,3],
+                             [5,7,6]])        
+
+        # Check averaging over vertices
+        #a: 0
+        #b: (4+4+4)/3
+        #c: (2+2+2)/3
+        #d: 8
+        #e: (6+6+6)/3        
+        #f: 4
+        assert num.allclose(quantity.get_values(location='unique vertices'), 
+                            [0, 4, 2, 8, 6, 4]) 
+
+
+
+    def test_get_interpolated_values(self):
+
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+        domain = Generic_Domain(points, vertices, boundary)
+
+        #Constant values
+        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5]])
+
+        
+
+        # Get interpolated values at centroids
+        interpolation_points = domain.get_centroid_coordinates()
+        answer = quantity.get_values(location='centroids')
+
+        
+        #print quantity.get_values(points=interpolation_points)
+        assert num.allclose(answer, quantity.get_values(interpolation_points=interpolation_points))
+
+
+        #Arbitrary values
+        quantity = Quantity(domain,[[0,1,2],[3,1,7],[2,1,2],[3,3,7],
+                                    [1,4,-9],[2,5,0]])
+
+
+        # Get interpolated values at centroids
+        interpolation_points = domain.get_centroid_coordinates()
+        answer = quantity.get_values(location='centroids')
+        #print answer
+        #print quantity.get_values(interpolation_points=interpolation_points)
+        assert num.allclose(answer, 
+                            quantity.get_values(interpolation_points=interpolation_points,
+                                                verbose=False))        
+                        
+
+        #FIXME TODO
+        #indices = [0,5,3]
+        #answer = [0.5,1,5]
+        #assert allclose(answer,
+        #                quantity.get_values(indices=indices, \
+        #                                    location = 'unique vertices'))
+
+
+
+
+    def test_get_interpolated_values_2(self):
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        domain = Generic_Domain(points, vertices)
+
+        quantity = Quantity(domain)
+        quantity.set_values(lambda x, y: x+2*y) #2 4 4 6
+
+        #First pick one point
+        x, y = 2.0/3, 8.0/3
+        v = quantity.get_values(interpolation_points = [[x,y]])
+        assert num.allclose(v, 6)        
+
+        # Then another to test that algorithm won't blindly
+        # reuse interpolation matrix
+        x, y = 4.0/3, 4.0/3
+        v = quantity.get_values(interpolation_points = [[x,y]])
+        assert num.allclose(v, 4)        
+
+
+
+    def test_get_interpolated_values_with_georef(self):
+    
+        zone = 56
+        xllcorner = 308500
+        yllcorner = 6189000
+        a = [0.0, 0.0]
+        b = [0.0, 2.0]
+        c = [2.0,0.0]
+        d = [0.0, 4.0]
+        e = [2.0, 2.0]
+        f = [4.0,0.0]
+
+        points = [a, b, c, d, e, f]
+        #bac, bce, ecf, dbe
+        vertices = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
+
+        domain = Generic_Domain(points, vertices,
+                        geo_reference=Geo_reference(zone,xllcorner,yllcorner))
+
+        quantity = Quantity(domain)
+        quantity.set_values(lambda x, y: x+2*y) #2 4 4 6
+
+        #First pick one point (and turn it into absolute coordinates)
+        x, y = 2.0/3, 8.0/3
+        v = quantity.get_values(interpolation_points = [[x+xllcorner,y+yllcorner]])
+        assert num.allclose(v, 6)
+        
+
+        # Then another to test that algorithm won't blindly
+        # reuse interpolation matrix 
+        x, y = 4.0/3, 4.0/3
+        v = quantity.get_values(interpolation_points = [[x+xllcorner,y+yllcorner]])
+        assert num.allclose(v, 4)        
+        
+        # Try two points
+        pts = [[2.0/3 + xllcorner, 8.0/3 + yllcorner], 
+               [4.0/3 + xllcorner, 4.0/3 + yllcorner]]         
+        v = quantity.get_values(interpolation_points=pts)
+        assert num.allclose(v, [6, 4])               
+        
+        # Test it using the geospatial data format with absolute input points and default georef
+        pts = Geospatial_data(data_points=pts)
+        v = quantity.get_values(interpolation_points=pts)
+        assert num.allclose(v, [6, 4])                                
+        
+        
+        # Test it using the geospatial data format with relative input points
+        pts = Geospatial_data(data_points=[[2.0/3, 8.0/3], [4.0/3, 4.0/3]], 
+                              geo_reference=Geo_reference(zone,xllcorner,yllcorner))
+        v = quantity.get_values(interpolation_points=pts)
+        assert num.allclose(v, [6, 4])                        
+        
+        
+        
+
+    def test_getting_some_vertex_values(self):
+        """
+        get values based on triangle lists.
+        """
+        from mesh_factory import rectangular
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #print "points",points
+        #print "vertices",vertices
+        #print "boundary",boundary
+
+        #Create shallow water domain
+        domain = Generic_Domain(points, vertices, boundary)
+        #print "domain.number_of_elements ",domain.number_of_elements
+        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5],[6,6,6]])
+        value = [7]
+        indices = [1]
+        quantity.set_values(value,
+                            location = 'centroids',
+                            indices = indices)
+        #print "quantity.centroid_values",quantity.centroid_values
+        #print "quantity.get_values(location = 'centroids') ",\
+        #      quantity.get_values(location = 'centroids')
+        assert num.allclose(quantity.centroid_values,
+                            quantity.get_values(location = 'centroids'))
+
+
+        value = [[15,20,25]]
+        quantity.set_values(value, indices = indices)
+        #print "1 quantity.vertex_values",quantity.vertex_values
+        assert num.allclose(quantity.vertex_values, quantity.get_values())
+
+        assert num.allclose(quantity.edge_values,
+                            quantity.get_values(location = 'edges'))
+
+        # get a subset of elements
+        subset = quantity.get_values(location='centroids', indices=[0,5])
+        answer = [quantity.centroid_values[0],quantity.centroid_values[5]]
+        assert num.allclose(subset, answer)
+
+
+        subset = quantity.get_values(location='edges', indices=[0,5])
+        answer = [quantity.edge_values[0],quantity.edge_values[5]]
+        #print "subset",subset
+        #print "answer",answer
+        assert num.allclose(subset, answer)
+
+        subset = quantity.get_values( indices=[1,5])
+        answer = [quantity.vertex_values[1],quantity.vertex_values[5]]
+        #print "subset",subset
+        #print "answer",answer
+        assert num.allclose(subset, answer)
+
+    def test_smooth_vertex_values(self):
+        """
+        get values based on triangle lists.
+        """
+        from mesh_factory import rectangular
+      #  from anuga.shallow_water.shallow_water_domain import Domain
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(2, 2)
+
+        #print "points",points
+        #print "vertices",vertices
+        #print "boundary",boundary
+
+        #Create shallow water domain
+        domain = Generic_Domain(points, vertices, boundary)
+        #print "domain.number_of_elements ",domain.number_of_elements
+        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
+                                    [4,4,4],[5,5,5],[6,6,6],[7,7,7]])
+
+        #print "quantity.get_values(location = 'unique vertices')", \
+        #      quantity.get_values(location = 'unique vertices')
+
+        #print "quantity.get_values(location = 'unique vertices')", \
+        #      quantity.get_values(indices=[0,1,2,3,4,5,6,7], \
+        #                          location = 'unique vertices')
+
+        #print quantity.get_values(location = 'unique vertices')
+        #print quantity.domain.number_of_triangles_per_node
+        #print quantity.vertex_values
+        
+        #answer = [0.5, 2, 3, 3, 3.5, 4, 4, 5, 6.5]
+        #assert allclose(answer,
+        #                quantity.get_values(location = 'unique vertices'))
+
+        quantity.smooth_vertex_values()
+
+        #print quantity.vertex_values
+
+
+        answer_vertex_values = [[3,3.5,0.5],[2,0.5,3.5],[3.5,4,2],[3,2,4],
+                                [4,5,3],[3.5,3,5],[5,6.5,3.5],[4,3.5,6.5]]
+        
+        assert num.allclose(answer_vertex_values,
+                            quantity.vertex_values)
+                            
+        # Just another (slightly larger) test of get_values
+
+        assert num.allclose(quantity.get_values(location='centroids'),
+                            quantity.centroid_values)
+                            
+                            
+        assert num.allclose(quantity.get_values(location='vertices'),
+                            quantity.vertex_values)                            
+                            
+        assert num.allclose(quantity.get_values(location='edges'),
+                            quantity.edge_values)
+                            
+
+    def test_maximum(self):
+        quantity = Quantity(self.mesh4)
+
+        # get referece to data arrays
+        centroid_values = quantity.centroid_values
+        vertex_values = quantity.vertex_values
+        edge_values = quantity.edge_values
+
+        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
+                            location = 'vertices')
+        assert num.allclose(quantity.vertex_values,
+                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+
+        assert id(vertex_values) == id(quantity.vertex_values)
+        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
+        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
+                                                   [5., 5., 5.],
+                                                   [4.5, 4.5, 0.],
+                                                   [3.0, -1.5, -1.5]])
+
+
+
+        other_quantity = Quantity(self.mesh4)
+
+        other_quantity.set_values([[0,0,0], [1,1,6], [10,10,10], [0,0,4]],
+                            location = 'vertices')
+
+ 
+        #===============================
+        quantity.maximum(other_quantity)
+        #===============================
+
+        exact_vertex_values = num.array([[  1.,   2.,   3.],
+                                         [  5.,   5.,  6.],
+                                         [ 10.,  10.,  10.],
+                                         [  0.,   3.,  4.]])
+        exact_centroid_values = num.array([  2.,  5., 10.,  1.33333333])
+        exact_edge_values = num.array([[  2.5,   2.,    1.5],
+                                       [  5.,   5.,   5., ],
+                                       [ 10.,   10.,  10. ],
+                                       [  3.,    2.,    0. ]])
+
+
+        
+        assert num.allclose(quantity.vertex_values,
+                            exact_vertex_values)
+        assert num.allclose(quantity.centroid_values, exact_centroid_values) #Centroid
+        assert num.allclose(quantity.edge_values, exact_edge_values)
+
+    def test_minimum(self):
+        quantity = Quantity(self.mesh4)
+
+        # get referece to data arrays
+        centroid_values = quantity.centroid_values
+        vertex_values = quantity.vertex_values
+        edge_values = quantity.edge_values
+
+        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
+                            location = 'vertices')
+        assert num.allclose(quantity.vertex_values,
+                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
+
+        assert id(vertex_values) == id(quantity.vertex_values)
+        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
+        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
+                                                   [5., 5., 5.],
+                                                   [4.5, 4.5, 0.],
+                                                   [3.0, -1.5, -1.5]])
+
+
+
+        other_quantity = Quantity(self.mesh4)
+
+        other_quantity.set_values([[0,0,0], [1,1,6], [10,10,10], [0,0,4]],
+                            location = 'vertices')
+
+
+        #===============================
+        quantity.minimum(other_quantity)
+        #===============================
+
+        exact_vertex_values = num.array([[  0.,   0.,   0.],
+                                         [  1.,   1.,  5.],
+                                         [  0.,   0.,  9.],
+                                         [ -6.,   0.,  3.]])
+        exact_centroid_values = num.array([  0.,  2.66666667, 3.,  0.])
+        exact_edge_values = num.array([[  0.,   0.,   0.],
+                                       [  3.5,   3.5,   1., ],
+                                       [  4.5,   4.5,   0. ],
+                                       [  2.,   -1.5,  -1.5 ]])
+
+
+        assert num.allclose(quantity.vertex_values,
+                            exact_vertex_values)
+        assert num.allclose(quantity.centroid_values, exact_centroid_values) #Centroid
+        assert num.allclose(quantity.edge_values, exact_edge_values)
+
+
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Quantity, 'test') #_set_values_from_asc')
+    runner = unittest.TextTestRunner(verbosity=1)
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_region.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_region.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_region.py	(revision 9460)
@@ -0,0 +1,99 @@
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt
+
+from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular
+from anuga.shallow_water.shallow_water_domain import Domain
+from anuga.abstract_2d_finite_volumes.generic_domain import Generic_Domain
+from anuga.abstract_2d_finite_volumes.region import *
+#from anuga.config import epsilon
+
+import numpy as num
+
+
+"""
+This is what the mesh in these tests look like;
+
+3---7
+|5 /|
+| /6|
+2---6
+|3 /|
+| /2|
+1---5
+|1 /|
+| /0|
+0---4
+"""
+
+def add_x_y(x, y):
+    return x+y
+
+def give_me_23(x, y):
+    return 23.0
+
+class Test_region(unittest.TestCase):
+    def setUp(self):
+        pass
+
+
+    def tearDown(self):
+        pass
+
+
+    def test_region_indices(self):
+        """create region based on triangle lists."""
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #Create shallow water domain
+        domain = Domain(points, vertices, boundary)
+        
+        region = Region(domain, indices=[0,2,3])
+
+        expected_indices = [0,2,3]  
+        assert num.allclose(region.indices, expected_indices)
+        
+
+    def test_region_polygon(self):
+        """create region based on triangle lists."""
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #Create shallow water domain
+        domain = Domain(points, vertices, boundary)
+        
+        poly = [[0.0,0.0], [0.5,0.0], [0.5,0.5]]
+        
+        #print poly
+        region = Region(domain, polygon=poly)
+        
+        expected_indices = [1]
+        assert num.allclose(region.indices, expected_indices)
+
+
+    def test_region_polygon_expanded(self):
+        """create region based on triangle lists."""
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #Create shallow water domain
+        domain = Domain(points, vertices, boundary)
+        
+        region = Region(domain, polygon=[[0.0,0.0], [0.5,0.0], [0.5,0.5]], expand_polygon=True)
+        
+        expected_indices = [0,1,2,3]
+        assert num.allclose(region.indices, expected_indices)
+
+        
+                  
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_region, 'test')    
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_tag_region.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_tag_region.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_tag_region.py	(revision 9460)
@@ -0,0 +1,258 @@
+#!/usr/bin/env python
+
+import unittest
+from math import sqrt
+
+from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular
+from anuga.shallow_water.shallow_water_domain import Domain
+from anuga.abstract_2d_finite_volumes.generic_domain import Generic_Domain
+from anuga.abstract_2d_finite_volumes.tag_region import *
+#from anuga.config import epsilon
+
+import numpy as num
+
+
+"""
+This is what the mesh in these tests look like;
+
+3---7
+|5 /|
+| /6|
+2---6
+|3 /|
+| /2|
+1---5
+|1 /|
+| /0|
+0---4
+"""
+
+def add_x_y(x, y):
+    return x+y
+
+def give_me_23(x, y):
+    return 23.0
+
+class Test_tag_region(unittest.TestCase):
+    def setUp(self):
+        pass
+
+
+    def tearDown(self):
+        pass
+
+
+    def test_region_tags(self):
+        """get values based on triangle lists."""
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #Create shallow water domain
+        domain = Domain(points, vertices, boundary)
+        domain.build_tagged_elements_dictionary({'bottom': [0,1],
+                                                 'top': [4,5],
+                                                 'all': [0,1,2,3,4,5]})
+
+        #Set friction
+        manning = 0.07
+        domain.set_quantity('friction', manning)
+
+        a = Set_tag_region('bottom', 'friction', 0.09)
+        b = Set_tag_region('top', 'friction', 1.0)
+        domain.set_tag_region([a, b])
+
+        expected = [[ 0.09,  0.09,  0.09],
+                    [ 0.09,  0.09,  0.09],
+                    [ 0.07,  0.07,  0.07],
+                    [ 0.07,  0.07,  0.07],
+                    [ 1.0,   1.0,   1.0],
+                    [ 1.0,   1.0,   1.0]]
+        msg = ("\ndomain.quantities['friction']=%s\nexpected value=%s"
+               % (str(domain.quantities['friction'].get_values()),
+                  str(expected)))
+        assert num.allclose(domain.quantities['friction'].get_values(),
+                            expected), msg
+
+        #c = Add_Value_To_region('all', 'friction', 10.0)
+        domain.set_tag_region(Add_value_to_region('all', 'friction', 10.0))
+        #print domain.quantities['friction'].get_values()
+        assert num.allclose(domain.quantities['friction'].get_values(),
+                            [[ 10.09, 10.09, 10.09],
+                             [ 10.09, 10.09, 10.09],
+                             [ 10.07, 10.07, 10.07],
+                             [ 10.07, 10.07, 10.07],
+                             [ 11.0,  11.0,  11.0],
+                             [ 11.0,  11.0,  11.0]])
+
+        # trying a function
+        domain.set_tag_region(Set_tag_region('top', 'friction', add_x_y))
+        #print domain.quantities['friction'].get_values()
+        assert num.allclose(domain.quantities['friction'].get_values(),
+                            [[ 10.09, 10.09, 10.09],
+                             [ 10.09, 10.09, 10.09],
+                             [ 10.07, 10.07, 10.07],
+                             [ 10.07, 10.07, 10.07],
+                             [ 5./3,  2.0,  2./3],
+                             [ 1.0,  2./3,  2.0]])
+
+        domain.set_quantity('elevation', 10.0)
+        domain.set_quantity('stage', 10.0)
+        domain.set_tag_region(Add_value_to_region('top', 'stage', 1.0,initial_quantity='elevation'))
+        #print domain.quantities['stage'].get_values()
+        assert num.allclose(domain.quantities['stage'].get_values(),
+                            [[ 10., 10., 10.],
+                             [ 10., 10., 10.],
+                             [ 10., 10., 10.],
+                             [ 10., 10., 10.],
+                             [ 11.0,  11.0,  11.0],
+                             [ 11.0,  11.0,  11.0]])
+
+        
+        domain.set_quantity('elevation', 10.0)
+        domain.set_quantity('stage', give_me_23)
+        #this works as well, (is cleaner, but doesn't work for regions)
+        #domain.set_quantity('stage',
+        #                    domain.quantities['stage'].vertex_values+ \
+        #                    domain.quantities['elevation'].vertex_values)
+        domain.set_tag_region(Add_quantities('top', 'elevation','stage'))
+        #print domain.quantities['stage'].get_values()
+        assert num.allclose(domain.quantities['elevation'].get_values(),
+                            [[ 10., 10., 10.],
+                             [ 10., 10., 10.],
+                             [ 10., 10., 10.],
+                             [ 10., 10., 10.],
+                             [ 33.,  33.0,  33.],
+                             [ 33.0,  33.,  33.]])
+        
+    def test_unique_vertices(self):
+        """get values based on triangle lists."""
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #Create shallow water domain
+        domain = Domain(points, vertices, boundary)
+        domain.build_tagged_elements_dictionary({'bottom':[0,1],
+                                                 'top':[4,5],
+                                                 'all':[0,1,2,3,4,5]})
+
+        #Set friction
+        manning = 0.07
+        domain.set_quantity('friction', manning)
+
+        a = Set_tag_region('bottom', 'friction', 0.09, location = 'unique vertices')
+        domain.set_tag_region(a)
+        assert num.allclose(domain.quantities['friction'].get_values(),
+                            [[ 0.09,  0.09,  0.09],
+                             [ 0.09,  0.09,  0.09],
+                             [ 0.09,  0.07,  0.09],
+                             [ 0.07,  0.09,  0.07],
+                             [ 0.07,  0.07,  0.07],
+                             [ 0.07,  0.07,  0.07]])
+
+
+    def test_unique_verticesII(self):
+        """
+        get values based on triangle lists.
+        """
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #Create shallow water domain
+        domain = Domain(points, vertices, boundary)
+        domain.build_tagged_elements_dictionary({'bottom':[0,1],
+                                                 'top':[4,5],
+                                                 'all':[0,1,2,3,4,5]})
+
+        #Set friction
+        manning = 0.07
+        domain.set_quantity('friction', manning)
+
+        domain.set_tag_region(Add_value_to_region('bottom', 'friction', 1.0,initial_quantity='friction', location = 'unique vertices'))
+
+        #print domain.quantities['friction'].get_values()
+        assert num.allclose(domain.quantities['friction'].get_values(),\
+                            [[ 1.07,  1.07,  1.07],
+                             [ 1.07,  1.07,  1.07],
+                             [ 1.07,  0.07,  1.07],
+                             [ 0.07,  1.07,  0.07],
+                             [ 0.07,  0.07,  0.07],
+                             [ 0.07,  0.07,  0.07]])
+                         
+    def test_unique_vertices_average_loc_vert(self):
+        """Get values based on triangle lists."""
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+
+        #Create shallow water domain
+        domain = Domain(points, vertices, boundary)
+        domain.build_tagged_elements_dictionary({'bottom': [0, 1],
+                                                 'top': [4, 5],
+                                                 'not_bottom': [2, 3, 4, 5]})
+
+        #Set friction
+        domain.set_quantity('friction', add_x_y)
+        av_bottom = 2.0 / 3.0
+        add = 60.0
+        calc_frict = av_bottom + add
+        domain.set_tag_region(Add_value_to_region('bottom', 'friction', add,
+                                              initial_quantity='friction',
+                                              location='vertices',
+                                              average=True))
+
+        frict_points = domain.quantities['friction'].get_values()
+
+        expected = [calc_frict, calc_frict, calc_frict]
+        msg = ('frict_points[0]=%s\nexpected=%s'
+               % (str(frict_points[0]), str(expected)))
+        assert num.allclose(frict_points[0], expected), msg
+
+        msg = ('frict_points[1]=%s\nexpected=%s'
+               % (str(frict_points[1]), str(expected)))
+        assert num.allclose(frict_points[1], expected), msg
+  
+    def test_unique_vertices_average_loc_unique_vert(self):
+        """
+        get values based on triangle lists.
+        """
+
+        #Create basic mesh
+        points, vertices, boundary = rectangular(1, 3)
+        #Create shallow water domain
+        domain = Domain(points, vertices, boundary)
+        domain.build_tagged_elements_dictionary({'bottom':[0,1],
+                                                 'top':[4,5],
+                                                 'not_bottom':[2,3,4,5]})
+
+        #Set friction
+        domain.set_quantity('friction', add_x_y)
+        av_bottom = 2.0/3.0
+        add = 60.0
+        calc_frict = av_bottom + add
+        domain.set_tag_region(Add_value_to_region('bottom', 'friction', add,
+                          initial_quantity='friction',
+                           location='unique vertices',
+                           average=True
+                          ))
+
+        #print domain.quantities['friction'].get_values()
+        frict_points = domain.quantities['friction'].get_values()
+        assert num.allclose(frict_points[0],\
+                            [ calc_frict, calc_frict, calc_frict])
+        assert num.allclose(frict_points[1],\
+                            [ calc_frict, calc_frict, calc_frict])
+        assert num.allclose(frict_points[2],\
+                            [ calc_frict, 1.0 + 2.0/3.0, calc_frict])
+        assert num.allclose(frict_points[3],\
+                            [ 2.0/3.0,calc_frict, 1.0 + 2.0/3.0])
+                                                
+                         
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_tag_region, 'test')    
+    runner = unittest.TextTestRunner()
+    runner.run(suite)
Index: /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_util.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_util.py	(revision 9460)
+++ /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test/test_util.py	(revision 9460)
@@ -0,0 +1,1624 @@
+#!/usr/bin/env python
+
+
+import unittest
+from math import sqrt, pi
+import tempfile, os
+from os import access, F_OK,sep, removedirs,remove,mkdir,getcwd
+
+from anuga.abstract_2d_finite_volumes.util import *
+from anuga.config import epsilon
+from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
+from anuga.file_conversion.file_conversion import timefile2netcdf
+from anuga.utilities.file_utils import del_dir
+
+from anuga.utilities.numerical_tools import NAN
+
+from sys import platform 
+
+from anuga.pmesh.mesh import Mesh
+import time
+from mesh_factory import rectangular
+from anuga.coordinate_transforms.geo_reference import Geo_reference
+from anuga.shallow_water.shallow_water_domain import Domain
+from generic_boundary_conditions import \
+                                Transmissive_boundary, Dirichlet_boundary
+from anuga.file.sww import SWW_file
+from csv import reader,writer
+import time
+import string
+
+import numpy as num
+
+
+def simple_function(x, y):
+    return x+y
+
+class Test_Util(unittest.TestCase):
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+
+
+
+    #Geometric
+    #def test_distance(self):
+    #    from anuga.abstract_2d_finite_volumes.util import distance#
+    #
+    #    self.failUnless( distance([4,2],[7,6]) == 5.0,
+    #                     'Distance is wrong!')
+    #    self.failUnless( allclose(distance([7,6],[9,8]), 2.82842712475),
+    #                    'distance is wrong!')
+    #    self.failUnless( allclose(distance([9,8],[4,2]), 7.81024967591),
+    #                    'distance is wrong!')
+    #
+    #    self.failUnless( distance([9,8],[4,2]) == distance([4,2],[9,8]),
+    #                    'distance is wrong!')
+
+
+    def test_file_function_time1(self):
+        """Test that File function interpolates correctly
+        between given times. No x,y dependency here.
+        """
+
+        #Write file
+        import os, time
+        from anuga.config import time_format
+        from math import sin, pi
+
+        #Typical ASCII file
+        finaltime = 1200
+        filename = 'test_file_function'
+        fid = open(filename + '.txt', 'w')
+        start = time.mktime(time.strptime('2000', '%Y'))
+        dt = 60  #One minute intervals
+        t = 0.0
+        while t <= finaltime:
+            t_string = time.strftime(time_format, time.gmtime(t+start))
+            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
+            t += dt
+
+        fid.close()
+
+        #Convert ASCII file to NetCDF (Which is what we really like!)
+        timefile2netcdf(filename+'.txt')
+
+
+        #Create file function from time series
+        F = file_function(filename + '.tms',
+                          quantities = ['Attribute0',
+                                        'Attribute1',
+                                        'Attribute2'])
+        
+        #Now try interpolation
+        for i in range(20):
+            t = i*10
+            q = F(t)
+
+            #Exact linear intpolation
+            assert num.allclose(q[0], 2*t)
+            if i%6 == 0:
+                assert num.allclose(q[1], t**2)
+                assert num.allclose(q[2], sin(t*pi/600))
+
+        #Check non-exact
+
+        t = 90 #Halfway between 60 and 120
+        q = F(t)
+        assert num.allclose( (120**2 + 60**2)/2, q[1] )
+        assert num.allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
+
+
+        t = 100 #Two thirds of the way between between 60 and 120
+        q = F(t)
+        assert num.allclose( 2*120**2/3 + 60**2/3, q[1] )
+        assert num.allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
+
+        os.remove(filename + '.txt')
+        os.remove(filename + '.tms')        
+
+
+        
+    def test_spatio_temporal_file_function_basic(self):
+        """Test that spatio temporal file function performs the correct
+        interpolations in both time and space
+        NetCDF version (x,y,t dependency)        
+        """
+        import time
+
+        #Create sww file of simple propagation from left to right
+        #through rectangular domain
+
+        #Create basic mesh and shallow water domain
+        points, vertices, boundary = rectangular(3, 3)
+        domain1 = Domain(points, vertices, boundary)
+
+        from anuga.utilities.numerical_tools import mean
+        domain1.reduction = mean
+        domain1.smooth = True #NOTE: Mimic sww output where each vertex has
+                              # only one value.
+
+        domain1.default_order = 2
+        domain1.store = True
+        domain1.set_datadir('.')
+        sww_file = 'spatio_temporal_boundary_source_%d' %(id(self))
+        domain1.set_name(sww_file)
+
+        #Bed-slope, friction and IC at vertices (and interpolated elsewhere)
+        domain1.set_quantity('elevation', 0)
+        domain1.set_quantity('friction', 0)
+        domain1.set_quantity('stage', 0)
+
+        # Boundary conditions
+        B0 = Dirichlet_boundary([0,0,0])
+        B6 = Dirichlet_boundary([0.6,0,0])
+        domain1.set_boundary({'left': B6, 'top': B6, 'right': B0, 'bottom': B0})
+        domain1.check_integrity()
+
+        finaltime = 8
+        #Evolution
+        t0 = -1
+        for t in domain1.evolve(yieldstep = 0.1, finaltime = finaltime):
+            #print 'Timesteps: %.16f, %.16f' %(t0, t)
+            #if t == t0:
+            #    msg = 'Duplicate timestep found: %f, %f' %(t0, t)
+            #   raise Exception(msg)
+            t0 = t
+             
+            #domain1.write_time()
+
+
+        #Now read data from sww and check
+        from anuga.file.netcdf import NetCDFFile
+        filename = domain1.get_name() + '.sww'
+        fid = NetCDFFile(filename)
+
+        x = fid.variables['x'][:]
+        y = fid.variables['y'][:]
+        stage = fid.variables['stage'][:]
+        xmomentum = fid.variables['xmomentum'][:]
+        ymomentum = fid.variables['ymomentum'][:]
+        time = fid.variables['time'][:]
+
+        #Take stage vertex values at last timestep on diagonal
+        #Diagonal is identified by vertices: 0, 5, 10, 15
+
+        last_time_index = len(time)-1 #Last last_time_index
+        d_stage = num.reshape(num.take(stage[last_time_index, :],
+                                       [0,5,10,15],
+                                       axis=0),
+                              (4,1))
+        d_uh = num.reshape(num.take(xmomentum[last_time_index, :],
+                                    [0,5,10,15],
+                                   axis=0),
+                           (4,1))
+        d_vh = num.reshape(num.take(ymomentum[last_time_index, :],
+                                    [0,5,10,15],
+                                   axis=0),
+                           (4,1))
+        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0 = (D[0] + D[1])/2
+        r1 = (D[1] + D[2])/2
+        r2 = (D[2] + D[3])/2
+
+        #And the midpoints are found now
+        Dx = num.take(num.reshape(x, (16,1)), [0,5,10,15], axis=0)
+        Dy = num.take(num.reshape(y, (16,1)), [0,5,10,15], axis=0)
+
+        diag = num.concatenate( (Dx, Dy), axis=1)
+        d_midpoints = (diag[1:] + diag[:-1])/2
+
+        #Let us see if the file function can find the correct
+        #values at the midpoints at the last timestep:
+        f = file_function(filename, domain1,
+                          interpolation_points = d_midpoints)
+
+        T = f.get_time()
+        msg = 'duplicate timesteps: %.16f and %.16f' %(T[-1], T[-2])
+        assert not T[-1] == T[-2], msg
+        t = time[last_time_index]
+        q = f(t, point_id=0); assert num.allclose(r0, q)
+        q = f(t, point_id=1); assert num.allclose(r1, q)
+        q = f(t, point_id=2); assert num.allclose(r2, q)
+
+
+        ##################
+        #Now do the same for the first timestep
+
+        timestep = 0 #First timestep
+        d_stage = num.reshape(num.take(stage[timestep, :], [0,5,10,15], axis=0), (4,1))
+        d_uh = num.reshape(num.take(xmomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
+        d_vh = num.reshape(num.take(ymomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
+        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0 = (D[0] + D[1])/2
+        r1 = (D[1] + D[2])/2
+        r2 = (D[2] + D[3])/2
+
+        #Let us see if the file function can find the correct
+        #values
+        q = f(0, point_id=0); assert num.allclose(r0, q)
+        q = f(0, point_id=1); assert num.allclose(r1, q)
+        q = f(0, point_id=2); assert num.allclose(r2, q)
+
+
+        ##################
+        #Now do it again for a timestep in the middle
+
+        timestep = 33
+        d_stage = num.reshape(num.take(stage[timestep, :], [0,5,10,15], axis=0), (4,1))
+        d_uh = num.reshape(num.take(xmomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
+        d_vh = num.reshape(num.take(ymomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
+        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0 = (D[0] + D[1])/2
+        r1 = (D[1] + D[2])/2
+        r2 = (D[2] + D[3])/2
+
+        q = f(timestep/10., point_id=0); assert num.allclose(r0, q)
+        q = f(timestep/10., point_id=1); assert num.allclose(r1, q)
+        q = f(timestep/10., point_id=2); assert num.allclose(r2, q)
+
+
+        ##################
+        #Now check temporal interpolation
+        #Halfway between timestep 15 and 16
+
+        timestep = 15
+        d_stage = num.reshape(num.take(stage[timestep, :], [0,5,10,15], axis=0), (4,1))
+        d_uh = num.reshape(num.take(xmomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
+        d_vh = num.reshape(num.take(ymomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
+        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0_0 = (D[0] + D[1])/2
+        r1_0 = (D[1] + D[2])/2
+        r2_0 = (D[2] + D[3])/2
+
+        #
+        timestep = 16
+        d_stage = num.reshape(num.take(stage[timestep, :], [0,5,10,15], axis=0), (4,1))
+        d_uh = num.reshape(num.take(xmomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
+        d_vh = num.reshape(num.take(ymomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
+        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0_1 = (D[0] + D[1])/2
+        r1_1 = (D[1] + D[2])/2
+        r2_1 = (D[2] + D[3])/2
+
+        # The reference values are
+        r0 = (r0_0 + r0_1)/2
+        r1 = (r1_0 + r1_1)/2
+        r2 = (r2_0 + r2_1)/2
+
+        q = f((timestep - 0.5)/10., point_id=0); assert num.allclose(r0, q)
+        q = f((timestep - 0.5)/10., point_id=1); assert num.allclose(r1, q)
+        q = f((timestep - 0.5)/10., point_id=2); assert num.allclose(r2, q)
+
+        ##################
+        #Finally check interpolation 2 thirds of the way
+        #between timestep 15 and 16
+
+        # The reference values are
+        r0 = (r0_0 + 2*r0_1)/3
+        r1 = (r1_0 + 2*r1_1)/3
+        r2 = (r2_0 + 2*r2_1)/3
+
+        #And the file function gives
+        q = f((timestep - 1.0/3)/10., point_id=0); assert num.allclose(r0, q)
+        q = f((timestep - 1.0/3)/10., point_id=1); assert num.allclose(r1, q)
+        q = f((timestep - 1.0/3)/10., point_id=2); assert num.allclose(r2, q)
+
+        fid.close()
+        import os
+        os.remove(filename)
+
+
+
+    def test_spatio_temporal_file_function_different_origin(self):
+        """Test that spatio temporal file function performs the correct
+        interpolations in both time and space where space is offset by
+        xllcorner and yllcorner
+        NetCDF version (x,y,t dependency)        
+        """
+        xllcorner = 2048
+        yllcorner = 11000
+        zone = 2
+
+        #Create basic mesh and shallow water domain
+        points, vertices, boundary = rectangular(3, 3)
+        domain1 = Domain(points, vertices, boundary,
+                         geo_reference = Geo_reference(xllcorner = xllcorner,
+                                                       yllcorner = yllcorner))
+        
+
+        from anuga.utilities.numerical_tools import mean        
+        domain1.reduction = mean
+        domain1.smooth = True #NOTE: Mimic sww output where each vertex has
+                              # only one value.
+
+        domain1.default_order = 2
+        domain1.store = True
+        domain1.set_datadir('.')
+        domain1.set_name('spatio_temporal_boundary_source_%d' %(id(self)))
+
+        #Bed-slope, friction and IC at vertices (and interpolated elsewhere)
+        domain1.set_quantity('elevation', 0)
+        domain1.set_quantity('friction', 0)
+        domain1.set_quantity('stage', 0)
+
+        # Boundary conditions
+        B0 = Dirichlet_boundary([0,0,0])
+        B6 = Dirichlet_boundary([0.6,0,0])
+        domain1.set_boundary({'left': B6, 'top': B6, 'right': B0, 'bottom': B0})
+        domain1.check_integrity()
+
+        finaltime = 8
+        #Evolution
+        for t in domain1.evolve(yieldstep = 0.1, finaltime = finaltime):
+            pass
+            #domain1.write_time()
+
+
+        #Now read data from sww and check
+        from anuga.file.netcdf import NetCDFFile
+        filename = domain1.get_name() + '.sww'
+        fid = NetCDFFile(filename)
+
+        x = fid.variables['x'][:]
+        y = fid.variables['y'][:]
+        # we 'cast' to 64 bit floats to pass this test
+        # SWW file quantities are stored as 32 bits
+        x = num.array(x, num.float)
+        y = num.array(y, num.float)
+
+        stage = fid.variables['stage'][:]
+        xmomentum = fid.variables['xmomentum'][:]
+        ymomentum = fid.variables['ymomentum'][:]
+        time = fid.variables['time'][:]
+
+        #Take stage vertex values at last timestep on diagonal
+        #Diagonal is identified by vertices: 0, 5, 10, 15
+
+        last_time_index = len(time)-1 #Last last_time_index     
+        d_stage = num.reshape(num.take(stage[last_time_index, :],
+                                       [0,5,10,15],
+                                       axis=0),
+                              (4,1))
+        d_uh = num.reshape(num.take(xmomentum[last_time_index, :],
+                                    [0,5,10,15],
+                                   axis=0),
+                           (4,1))
+        d_vh = num.reshape(num.take(ymomentum[last_time_index, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0 = (D[0] + D[1])/2
+        r1 = (D[1] + D[2])/2
+        r2 = (D[2] + D[3])/2
+
+        #And the midpoints are found now
+        Dx = num.take(num.reshape(x, (16,1)), [0,5,10,15], axis=0)
+        Dy = num.take(num.reshape(y, (16,1)), [0,5,10,15], axis=0)
+
+        diag = num.concatenate((Dx, Dy), axis=1)
+        d_midpoints = (diag[1:] + diag[:-1])/2
+
+
+        #Adjust for georef - make interpolation points absolute
+        d_midpoints[:,0] += xllcorner
+        d_midpoints[:,1] += yllcorner                
+
+        #Let us see if the file function can find the correct
+        #values at the midpoints at the last timestep:
+        f = file_function(filename, domain1,
+                          interpolation_points = d_midpoints)
+
+        t = time[last_time_index]                         
+
+        q = f(t, point_id=0)
+        msg = '\nr0=%s\nq=%s' % (str(r0), str(q))
+        assert num.allclose(r0, q), msg
+
+        q = f(t, point_id=1)
+        msg = '\nr1=%s\nq=%s' % (str(r1), str(q))
+        assert num.allclose(r1, q), msg
+
+        q = f(t, point_id=2)
+        msg = '\nr2=%s\nq=%s' % (str(r2), str(q))
+        assert num.allclose(r2, q), msg
+
+
+        ##################
+        #Now do the same for the first timestep
+
+        timestep = 0 #First timestep
+        d_stage = num.reshape(num.take(stage[timestep, :],
+                                       [0,5,10,15],
+                                       axis=0),
+                              (4,1))
+        d_uh = num.reshape(num.take(xmomentum[timestep, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        d_vh = num.reshape(num.take(ymomentum[timestep, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        D = num.concatenate( (d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0 = (D[0] + D[1])/2
+        r1 = (D[1] + D[2])/2
+        r2 = (D[2] + D[3])/2
+
+        #Let us see if the file function can find the correct
+        #values
+        q = f(0, point_id=0); assert num.allclose(r0, q)
+        q = f(0, point_id=1); assert num.allclose(r1, q)
+        q = f(0, point_id=2); assert num.allclose(r2, q)
+
+
+        ##################
+        #Now do it again for a timestep in the middle
+
+        timestep = 33
+        d_stage = num.reshape(num.take(stage[timestep, :],
+                                       [0,5,10,15],
+                                       axis=0),
+                              (4,1))
+        d_uh = num.reshape(num.take(xmomentum[timestep, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        d_vh = num.reshape(num.take(ymomentum[timestep, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        D = num.concatenate( (d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0 = (D[0] + D[1])/2
+        r1 = (D[1] + D[2])/2
+        r2 = (D[2] + D[3])/2
+
+        q = f(timestep/10., point_id=0); assert num.allclose(r0, q)
+        q = f(timestep/10., point_id=1); assert num.allclose(r1, q)
+        q = f(timestep/10., point_id=2); assert num.allclose(r2, q)
+
+
+        ##################
+        #Now check temporal interpolation
+        #Halfway between timestep 15 and 16
+
+        timestep = 15
+        d_stage = num.reshape(num.take(stage[timestep, :],
+                                       [0,5,10,15],
+                                       axis=0),
+                              (4,1))
+        d_uh = num.reshape(num.take(xmomentum[timestep, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        d_vh = num.reshape(num.take(ymomentum[timestep, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        D = num.concatenate( (d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0_0 = (D[0] + D[1])/2
+        r1_0 = (D[1] + D[2])/2
+        r2_0 = (D[2] + D[3])/2
+
+        #
+        timestep = 16
+        d_stage = num.reshape(num.take(stage[timestep, :],
+                                       [0,5,10,15],
+                                       axis=0),
+                              (4,1))
+        d_uh = num.reshape(num.take(xmomentum[timestep, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        d_vh = num.reshape(num.take(ymomentum[timestep, :],
+                                    [0,5,10,15],
+                                    axis=0),
+                           (4,1))
+        D = num.concatenate( (d_stage, d_uh, d_vh), axis=1)
+
+        #Reference interpolated values at midpoints on diagonal at
+        #this timestep are
+        r0_1 = (D[0] + D[1])/2
+        r1_1 = (D[1] + D[2])/2
+        r2_1 = (D[2] + D[3])/2
+
+        # The reference values are
+        r0 = (r0_0 + r0_1)/2
+        r1 = (r1_0 + r1_1)/2
+        r2 = (r2_0 + r2_1)/2
+
+        q = f((timestep - 0.5)/10., point_id=0); assert num.allclose(r0, q)
+        q = f((timestep - 0.5)/10., point_id=1); assert num.allclose(r1, q)
+        q = f((timestep - 0.5)/10., point_id=2); assert num.allclose(r2, q)
+
+        ##################
+        #Finally check interpolation 2 thirds of the way
+        #between timestep 15 and 16
+
+        # The reference values are
+        r0 = (r0_0 + 2*r0_1)/3
+        r1 = (r1_0 + 2*r1_1)/3
+        r2 = (r2_0 + 2*r2_1)/3
+
+        #And the file function gives
+        q = f((timestep - 1.0/3)/10., point_id=0); assert num.allclose(r0, q)
+        q = f((timestep - 1.0/3)/10., point_id=1); assert num.allclose(r1, q)
+        q = f((timestep - 1.0/3)/10., point_id=2); assert num.allclose(r2, q)
+
+        fid.close()
+        import os
+        os.remove(filename)
+
+        
+
+
+    def test_spatio_temporal_file_function_time(self):
+        """Test that File function interpolates correctly
+        between given times.
+        NetCDF version (x,y,t dependency)
+        """
+
+        #Create NetCDF (sww) file to be read
+        # x: 0, 5, 10, 15
+        # y: -20, -10, 0, 10
+        # t: 0, 60, 120, ...., 1200
+        #
+        # test quantities (arbitrary but non-trivial expressions):
+        #
+        #   stage     = 3*x - y**2 + 2*t
+        #   xmomentum = exp( -((x-7)**2 + (y+5)**2)/20 ) * t**2
+        #   ymomentum = x**2 + y**2 * sin(t*pi/600)
+
+        #NOTE: Nice test that may render some of the others redundant.
+
+        import os, time
+        from anuga.config import time_format
+        from mesh_factory import rectangular
+        from anuga.shallow_water.shallow_water_domain import Domain
+
+        finaltime = 1200
+        filename = 'test_file_function'
+
+        #Create a domain to hold test grid
+        #(0:15, -20:10)
+        points, vertices, boundary =\
+                rectangular(4, 4, 15, 30, origin = (0, -20))
+        #print "points", points
+
+        #print 'Number of elements', len(vertices)
+        domain = Domain(points, vertices, boundary)
+        domain.smooth = False
+        domain.default_order = 2
+        domain.set_datadir('.')
+        domain.set_name(filename)
+        domain.store = True
+
+        #print points
+        start = time.mktime(time.strptime('2000', '%Y'))
+        domain.starttime = start
+
+
+        #Store structure
+        domain.initialise_storage()
+
+        #Compute artificial time steps and store
+        dt = 60  #One minute intervals
+        t = 0.0
+        while t <= finaltime:
+            #Compute quantities
+            f1 = lambda x,y: 3*x - y**2 + 2*t + 4
+            domain.set_quantity('stage', f1)
+
+            f2 = lambda x,y: x+y+t**2
+            domain.set_quantity('xmomentum', f2)
+
+            f3 = lambda x,y: x**2 + y**2 * num.sin(t*num.pi/600)
+            domain.set_quantity('ymomentum', f3)
+
+            #Store and advance time
+            domain.time = t
+            domain.store_timestep()
+            t += dt
+
+
+        interpolation_points = [[0,-20], [1,0], [0,1], [1.1, 3.14], [10,-12.5]]
+      
+        #Deliberately set domain.starttime to too early
+        domain.starttime = start - 1
+
+        #Create file function
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)
+
+        #Check that FF updates fixes domain starttime
+        assert num.allclose(domain.starttime, start)
+
+        #Check that domain.starttime isn't updated if later
+        domain.starttime = start + 1
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)
+        assert num.allclose(domain.starttime, start+1)
+        domain.starttime = start
+
+
+        #Check linear interpolation in time
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)                
+        for id in range(len(interpolation_points)):
+            x = interpolation_points[id][0]
+            y = interpolation_points[id][1]
+
+            for i in range(20):
+                t = i*10
+                k = i%6
+
+                if k == 0:
+                    q0 = F(t, point_id=id)
+                    q1 = F(t+60, point_id=id)
+
+                if num.alltrue(q0 == NAN):
+                    actual = q0
+                else:
+                    actual = (k*q1 + (6-k)*q0)/6
+                q = F(t, point_id=id)
+                #print i, k, t, q
+                #print ' ', q0
+                #print ' ', q1
+                #print "q",q
+                #print "actual", actual
+                #print
+                if num.alltrue(q0 == NAN):
+                     self.failUnless(num.alltrue(q == actual), 'Fail!')
+                else:
+                    assert num.allclose(q, actual)
+
+
+        #Another check of linear interpolation in time
+        for id in range(len(interpolation_points)):
+            q60 = F(60, point_id=id)
+            q120 = F(120, point_id=id)
+
+            t = 90 #Halfway between 60 and 120
+            q = F(t, point_id=id)
+            assert num.allclose( (q120+q60)/2, q )
+
+            t = 100 #Two thirds of the way between between 60 and 120
+            q = F(t, point_id=id)
+            assert num.allclose(q60/3 + 2*q120/3, q)
+
+
+
+        #Check that domain.starttime isn't updated if later than file starttime but earlier
+        #than file end time
+        delta = 23
+        domain.starttime = start + delta
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)
+        assert num.allclose(domain.starttime, start+delta)
+
+
+
+
+        #Now try interpolation with delta offset
+        for id in range(len(interpolation_points)):            
+            x = interpolation_points[id][0]
+            y = interpolation_points[id][1]
+
+            for i in range(20):
+                t = i*10
+                k = i%6
+
+                if k == 0:
+                    q0 = F(t-delta, point_id=id)
+                    q1 = F(t+60-delta, point_id=id)
+
+                q = F(t-delta, point_id=id)
+                assert num.allclose(q, (k*q1 + (6-k)*q0)/6)
+
+
+        os.remove(filename + '.sww')
+
+
+
+    def Xtest_spatio_temporal_file_function_time(self):
+        # FIXME: This passes but needs some TLC
+        # Test that File function interpolates correctly
+        # When some points are outside the mesh
+
+        import os, time
+        from anuga.config import time_format
+        from mesh_factory import rectangular
+        from shallow_water import Domain
+        import anuga.shallow_water.data_manager 
+        from anuga.pmesh.mesh_interface import create_mesh_from_regions
+        finaltime = 1200
+        
+        filename = tempfile.mktemp()
+        #print "filename",filename 
+        filename = 'test_file_function'
+
+        meshfilename = tempfile.mktemp(".tsh")
+
+        boundary_tags = {'walls':[0,1],'bom':[2]}
+        
+        polygon_absolute = [[0,-20],[10,-20],[10,15],[-20,15]]
+        
+        create_mesh_from_regions(polygon_absolute,
+                                 boundary_tags,
+                                 10000000,
+                                 filename=meshfilename)
+        domain = Domain(mesh_filename=meshfilename)
+        domain.smooth = False
+        domain.default_order = 2
+        domain.set_datadir('.')
+        domain.set_name(filename)
+        domain.store = True
+
+        #print points
+        start = time.mktime(time.strptime('2000', '%Y'))
+        domain.starttime = start
+        
+
+        #Store structure
+        domain.initialise_storage()
+
+        #Compute artificial time steps and store
+        dt = 60  #One minute intervals
+        t = 0.0
+        while t <= finaltime:
+            #Compute quantities
+            f1 = lambda x,y: 3*x - y**2 + 2*t + 4
+            domain.set_quantity('stage', f1)
+
+            f2 = lambda x,y: x+y+t**2
+            domain.set_quantity('xmomentum', f2)
+
+            f3 = lambda x,y: x**2 + y**2 * num.sin(t*num.pi/600)
+            domain.set_quantity('ymomentum', f3)
+
+            #Store and advance time
+            domain.time = t
+            domain.store_timestep()
+            t += dt
+
+        interpolation_points = [[1,0]]
+        interpolation_points = [[100,1000]]
+        
+        interpolation_points = [[0,-20], [1,0], [0,1], [1.1, 3.14], [10,-12.5],
+                                [78787,78787],[7878,3432]]
+            
+        #Deliberately set domain.starttime to too early
+        domain.starttime = start - 1
+
+        #Create file function
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)
+
+        #Check that FF updates fixes domain starttime
+        assert num.allclose(domain.starttime, start)
+
+        #Check that domain.starttime isn't updated if later
+        domain.starttime = start + 1
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)
+        assert num.allclose(domain.starttime, start+1)
+        domain.starttime = start
+
+
+        #Check linear interpolation in time
+        # checking points inside and outside the mesh
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)
+        
+        for id in range(len(interpolation_points)):
+            x = interpolation_points[id][0]
+            y = interpolation_points[id][1]
+
+            for i in range(20):
+                t = i*10
+                k = i%6
+
+                if k == 0:
+                    q0 = F(t, point_id=id)
+                    q1 = F(t+60, point_id=id)
+
+                if q0 == NAN:
+                    actual = q0
+                else:
+                    actual = (k*q1 + (6-k)*q0)/6
+                q = F(t, point_id=id)
+                #print i, k, t, q
+                #print ' ', q0
+                #print ' ', q1
+                #print "q",q
+                #print "actual", actual
+                #print
+                if q0 == NAN:
+                     self.failUnless( q == actual, 'Fail!')
+                else:
+                    assert num.allclose(q, actual)
+
+        # now lets check points inside the mesh
+        interpolation_points = [[0,-20], [1,0], [0,1], [1.1, 3.14]] #, [10,-12.5]] - this point doesn't work WHY?
+        interpolation_points = [[10,-12.5]]
+            
+        print "len(interpolation_points)",len(interpolation_points) 
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)
+
+        domain.starttime = start
+
+
+        #Check linear interpolation in time
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)                
+        for id in range(len(interpolation_points)):
+            x = interpolation_points[id][0]
+            y = interpolation_points[id][1]
+
+            for i in range(20):
+                t = i*10
+                k = i%6
+
+                if k == 0:
+                    q0 = F(t, point_id=id)
+                    q1 = F(t+60, point_id=id)
+
+                if q0 == NAN:
+                    actual = q0
+                else:
+                    actual = (k*q1 + (6-k)*q0)/6
+                q = F(t, point_id=id)
+                print "############"
+                print "id, x, y ", id, x, y #k, t, q
+                print "t", t
+                #print ' ', q0
+                #print ' ', q1
+                print "q",q
+                print "actual", actual
+                #print
+                if q0 == NAN:
+                     self.failUnless( q == actual, 'Fail!')
+                else:
+                    assert num.allclose(q, actual)
+
+
+        #Another check of linear interpolation in time
+        for id in range(len(interpolation_points)):
+            q60 = F(60, point_id=id)
+            q120 = F(120, point_id=id)
+
+            t = 90 #Halfway between 60 and 120
+            q = F(t, point_id=id)
+            assert num.allclose( (q120+q60)/2, q )
+
+            t = 100 #Two thirds of the way between between 60 and 120
+            q = F(t, point_id=id)
+            assert num.allclose(q60/3 + 2*q120/3, q)
+
+
+
+        #Check that domain.starttime isn't updated if later than file starttime but earlier
+        #than file end time
+        delta = 23
+        domain.starttime = start + delta
+        F = file_function(filename + '.sww', domain,
+                          quantities = domain.conserved_quantities,
+                          interpolation_points = interpolation_points)
+        assert num.allclose(domain.starttime, start+delta)
+
+
+
+
+        #Now try interpolation with delta offset
+        for id in range(len(interpolation_points)):            
+            x = interpolation_points[id][0]
+            y = interpolation_points[id][1]
+
+            for i in range(20):
+                t = i*10
+                k = i%6
+
+                if k == 0:
+                    q0 = F(t-delta, point_id=id)
+                    q1 = F(t+60-delta, point_id=id)
+
+                q = F(t-delta, point_id=id)
+                assert num.allclose(q, (k*q1 + (6-k)*q0)/6)
+
+
+        os.remove(filename + '.sww')
+
+    def test_file_function_time_with_domain(self):
+        """Test that File function interpolates correctly
+        between given times. No x,y dependency here.
+        Use domain with starttime
+        """
+
+        #Write file
+        import os, time, calendar
+        from anuga.config import time_format
+        from math import sin, pi
+
+        finaltime = 1200
+        filename = 'test_file_function'
+        fid = open(filename + '.txt', 'w')
+        start = time.mktime(time.strptime('2000', '%Y'))
+        
+        #print 'start ',start
+        
+        dt = 60  #One minute intervals
+        t = 0.0
+        while t <= finaltime:
+            t_string = time.strftime(time_format, time.gmtime(t+start))
+            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
+            t += dt
+
+        fid.close()
+
+
+        #Convert ASCII file to NetCDF (Which is what we really like!)
+        timefile2netcdf(filename+'.txt')
+
+
+
+        a = [0.0, 0.0]
+        b = [4.0, 0.0]
+        c = [0.0, 3.0]
+
+        points = [a, b, c]
+        vertices = [[0,1,2]]
+        domain = Domain(points, vertices)
+        #print domain.starttime, start
+		
+        # Check that domain.starttime is updated if non-existing
+        F = file_function(filename + '.tms',
+                          domain,
+                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'])  
+                          
+                          
+        #print domain.starttime, start
+        assert num.allclose(domain.starttime, start)
+
+        # Check that domain.starttime is updated if too early
+        domain.starttime = start - 1
+        F = file_function(filename + '.tms',
+                          domain,
+                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'])
+        assert num.allclose(domain.starttime, start)
+
+        # Check that domain.starttime isn't updated if later
+        domain.starttime = start + 1
+        F = file_function(filename + '.tms',
+                          domain,
+                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'])
+        assert num.allclose(domain.starttime, start+1)
+
+        domain.starttime = start
+        F = file_function(filename + '.tms',
+                          domain,
+                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'],
+                          use_cache=True)
+        
+
+        #print F.precomputed_values
+        #print 'F(60)', F(60)
+        
+        #Now try interpolation
+        for i in range(20):
+            t = i*10
+            q = F(t)
+
+            #Exact linear intpolation
+            assert num.allclose(q[0], 2*t)
+            if i%6 == 0:
+                assert num.allclose(q[1], t**2)
+                assert num.allclose(q[2], sin(t*pi/600))
+
+        #Check non-exact
+
+        t = 90 #Halfway between 60 and 120
+        q = F(t)
+        assert num.allclose( (120**2 + 60**2)/2, q[1] )
+        assert num.allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
+
+
+        t = 100 #Two thirds of the way between between 60 and 120
+        q = F(t)
+        assert num.allclose( 2*120**2/3 + 60**2/3, q[1] )
+        assert num.allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
+
+        os.remove(filename + '.tms')
+        os.remove(filename + '.txt')        
+
+    def test_file_function_time_with_domain_different_start(self):
+        """Test that File function interpolates correctly
+        between given times. No x,y dependency here.
+        Use domain with a starttime later than that of file
+
+        ASCII version
+        """
+
+        #Write file
+        import os, time, calendar
+        from anuga.config import time_format
+        from math import sin, pi
+
+        finaltime = 1200
+        filename = 'test_file_function'
+        fid = open(filename + '.txt', 'w')
+        start = time.mktime(time.strptime('2000', '%Y'))
+        dt = 60  #One minute intervals
+        t = 0.0
+        while t <= finaltime:
+            t_string = time.strftime(time_format, time.gmtime(t+start))
+            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
+            t += dt
+
+        fid.close()
+
+        #Convert ASCII file to NetCDF (Which is what we really like!)
+        timefile2netcdf(filename+'.txt')        
+
+        a = [0.0, 0.0]
+        b = [4.0, 0.0]
+        c = [0.0, 3.0]
+
+        points = [a, b, c]
+        vertices = [[0,1,2]]
+        domain = Domain(points, vertices)
+
+        #Check that domain.starttime isn't updated if later than file starttime but earlier
+        #than file end time
+        delta = 23
+        domain.starttime = start + delta
+        F = file_function(filename + '.tms', domain,
+                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'])        
+        assert num.allclose(domain.starttime, start+delta)
+
+        assert num.allclose(F.get_time(), [-23., 37., 97., 157., 217.,
+                                            277., 337., 397., 457., 517.,
+                                            577., 637., 697., 757., 817.,
+                                            877., 937., 997., 1057., 1117.,
+                                            1177.])
+
+
+        #Now try interpolation with delta offset
+        for i in range(20):
+            t = i*10
+            q = F(t-delta)
+
+            #Exact linear intpolation
+            assert num.allclose(q[0], 2*t)
+            if i%6 == 0:
+                assert num.allclose(q[1], t**2)
+                assert num.allclose(q[2], sin(t*pi/600))
+
+        #Check non-exact
+
+        t = 90 #Halfway between 60 and 120
+        q = F(t-delta)
+        assert num.allclose( (120**2 + 60**2)/2, q[1] )
+        assert num.allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
+
+
+        t = 100 #Two thirds of the way between between 60 and 120
+        q = F(t-delta)
+        assert num.allclose( 2*120**2/3 + 60**2/3, q[1] )
+        assert num.allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
+
+
+        os.remove(filename + '.tms')
+        os.remove(filename + '.txt')                
+
+        
+
+    def test_file_function_time_with_domain_different_start_and_time_limit(self):
+        """Test that File function interpolates correctly
+        between given times. No x,y dependency here.
+        Use domain with a starttime later than that of file
+
+        ASCII version
+        
+        This test also tests that time can be truncated.
+        """
+
+        # Write file
+        import os, time, calendar
+        from anuga.config import time_format
+        from math import sin, pi
+
+        finaltime = 1200
+        filename = 'test_file_function'
+        fid = open(filename + '.txt', 'w')
+        start = time.mktime(time.strptime('2000', '%Y'))
+        dt = 60  #One minute intervals
+        t = 0.0
+        while t <= finaltime:
+            t_string = time.strftime(time_format, time.gmtime(t+start))
+            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
+            t += dt
+
+        fid.close()
+
+        # Convert ASCII file to NetCDF (Which is what we really like!)
+        timefile2netcdf(filename + '.txt')        
+
+        a = [0.0, 0.0]
+        b = [4.0, 0.0]
+        c = [0.0, 3.0]
+
+        points = [a, b, c]
+        vertices = [[0,1,2]]
+        domain = Domain(points, vertices)
+
+        # Check that domain.starttime isn't updated if later than file starttime but earlier
+        # than file end time
+        delta = 23
+        domain.starttime = start + delta
+        time_limit = domain.starttime + 600
+        F = file_function(filename + '.tms', domain,
+                          time_limit=time_limit,
+                          quantities=['Attribute0', 'Attribute1', 'Attribute2'])        
+        assert num.allclose(domain.starttime, start+delta)
+
+        assert num.allclose(F.get_time(), [-23., 37., 97., 157., 217.,
+                                            277., 337., 397., 457., 517.,
+                                            577.])        
+
+
+
+        # Now try interpolation with delta offset
+        for i in range(20):
+            t = i*10
+            q = F(t-delta)
+
+            #Exact linear intpolation
+            assert num.allclose(q[0], 2*t)
+            if i%6 == 0:
+                assert num.allclose(q[1], t**2)
+                assert num.allclose(q[2], sin(t*pi/600))
+
+        # Check non-exact
+        t = 90 #Halfway between 60 and 120
+        q = F(t-delta)
+        assert num.allclose( (120**2 + 60**2)/2, q[1] )
+        assert num.allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
+
+
+        t = 100 # Two thirds of the way between between 60 and 120
+        q = F(t-delta)
+        assert num.allclose( 2*120**2/3 + 60**2/3, q[1] )
+        assert num.allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
+
+
+        os.remove(filename + '.tms')
+        os.remove(filename + '.txt')                
+
+        
+        
+        
+
+
+    def test_apply_expression_to_dictionary(self):
+
+        #FIXME: Division is not expected to work for integers.
+        #This must be caught.
+        foo = num.array([[1,2,3], [4,5,6]], num.float)
+
+        bar = num.array([[-1,0,5], [6,1,1]], num.float)                  
+
+        D = {'X': foo, 'Y': bar}
+
+        Z = apply_expression_to_dictionary('X+Y', D)        
+        assert num.allclose(Z, foo+bar)
+
+        Z = apply_expression_to_dictionary('X*Y', D)        
+        assert num.allclose(Z, foo*bar)        
+
+        Z = apply_expression_to_dictionary('4*X+Y', D)        
+        assert num.allclose(Z, 4*foo+bar)        
+
+        # test zero division is OK
+        Z = apply_expression_to_dictionary('X/Y', D)
+        assert num.allclose(1/Z, 1/(foo/bar)) # can't compare inf to inf
+
+        # make an error for zero on zero
+        # this is really an error in numeric, SciPy core can handle it
+        # Z = apply_expression_to_dictionary('0/Y', D)
+
+        #Check exceptions
+        try:
+            #Wrong name
+            Z = apply_expression_to_dictionary('4*X+A', D)        
+        except NameError:
+            pass
+        else:
+            msg = 'Should have raised a NameError Exception'
+            raise Exception(msg)
+
+
+        try:
+            #Wrong order
+            Z = apply_expression_to_dictionary(D, '4*X+A')        
+        except AssertionError:
+            pass
+        else:
+            msg = 'Should have raised a AssertionError Exception'
+            raise Exception(msg)
+        
+
+    def test_multiple_replace(self):
+        """Hard test that checks a true word-by-word simultaneous replace
+        """
+        
+        D = {'x': 'xi', 'y': 'eta', 'xi':'lam'}
+        exp = '3*x+y + xi'
+        
+        new = multiple_replace(exp, D)
+        
+        assert new == '3*xi+eta + lam'
+                          
+   
+    def test_get_revision_number(self):
+        """test_get_revision_number(self):
+
+        Test that revision number can be retrieved.
+        """
+        if os.environ.has_key('USER') and os.environ['USER'] == 'dgray':
+            # I have a known snv incompatability issue,
+            # so I'm skipping this test.
+            # FIXME when SVN is upgraded on our clusters
+            pass
+        else:    
+            n = get_revision_number()
+            assert n>=0
+
+
+        
+    def test_add_directories(self):
+        
+        import tempfile
+        root_dir = tempfile.mkdtemp('_test_util', 'test_util_')
+        directories = ['ja','ne','ke']
+        kens_dir = add_directories(root_dir, directories)
+        assert kens_dir == root_dir + sep + 'ja' + sep + 'ne' + \
+               sep + 'ke'
+        assert access(root_dir,F_OK)
+
+        add_directories(root_dir, directories)
+        assert access(root_dir,F_OK)
+        
+        #clean up!
+        os.rmdir(kens_dir)
+        os.rmdir(root_dir + sep + 'ja' + sep + 'ne')
+        os.rmdir(root_dir + sep + 'ja')
+        os.rmdir(root_dir)
+
+    def test_add_directories_bad(self):
+        
+        import tempfile
+        root_dir = tempfile.mkdtemp('_test_util', 'test_util_')
+        directories = ['/\/!@#@#$%^%&*((*:*:','ne','ke']
+        
+        try:
+            kens_dir = add_directories(root_dir, directories)
+        except OSError:
+            pass
+        else:
+            msg = 'bad dir name should give OSError'
+            raise Exception(msg)    
+            
+        #clean up!
+        os.rmdir(root_dir)
+
+    def test_check_list(self):
+
+        check_list(['stage','xmomentum'])
+
+        
+    def test_add_directories(self):
+        
+        import tempfile
+        root_dir = tempfile.mkdtemp('_test_util', 'test_util_')
+        directories = ['ja','ne','ke']
+        kens_dir = add_directories(root_dir, directories)
+        assert kens_dir == root_dir + sep + 'ja' + sep + 'ne' + \
+               sep + 'ke'
+        assert access(root_dir,F_OK)
+
+        add_directories(root_dir, directories)
+        assert access(root_dir,F_OK)
+        
+        #clean up!
+        os.rmdir(kens_dir)
+        os.rmdir(root_dir + sep + 'ja' + sep + 'ne')
+        os.rmdir(root_dir + sep + 'ja')
+        os.rmdir(root_dir)
+
+    def test_add_directories_bad(self):
+        
+        import tempfile
+        root_dir = tempfile.mkdtemp('_test_util', 'test_util_')
+        directories = ['/\/!@#@#$%^%&*((*:*:','ne','ke']
+        
+        try:
+            kens_dir = add_directories(root_dir, directories)
+        except OSError:
+            pass
+        else:
+            msg = 'bad dir name should give OSError'
+            raise Exception(msg)    
+            
+        #clean up!
+        os.rmdir(root_dir)
+
+    def test_check_list(self):
+
+        check_list(['stage','xmomentum'])
+
+######
+# Test the remove_lone_verts() function
+######
+        
+    def test_remove_lone_verts_a(self):
+        verts = [[0,0],[1,0],[0,1]]
+        tris = [[0,1,2]]
+        new_verts, new_tris = remove_lone_verts(verts, tris)
+        self.failUnless(new_verts.tolist() == verts)
+        self.failUnless(new_tris.tolist() == tris)
+
+    def test_remove_lone_verts_b(self):
+        verts = [[0,0],[1,0],[0,1],[99,99]]
+        tris = [[0,1,2]]
+        new_verts, new_tris = remove_lone_verts(verts, tris)
+        self.failUnless(new_verts.tolist() == verts[0:3])
+        self.failUnless(new_tris.tolist() == tris)
+        
+    def test_remove_lone_verts_c(self):
+        verts = [[99,99],[0,0],[1,0],[99,99],[0,1],[99,99]]
+        tris = [[1,2,4]]
+        new_verts, new_tris = remove_lone_verts(verts, tris)
+        self.failUnless(new_verts.tolist() == [[0,0],[1,0],[0,1]])
+        self.failUnless(new_tris.tolist() == [[0,1,2]])
+     
+    def test_remove_lone_verts_d(self):
+        verts = [[0,0],[1,0],[99,99],[0,1]]
+        tris = [[0,1,3]]
+        new_verts, new_tris = remove_lone_verts(verts, tris)
+        self.failUnless(new_verts.tolist() == [[0,0],[1,0],[0,1]])
+        self.failUnless(new_tris.tolist() == [[0,1,2]])
+        
+    def test_remove_lone_verts_e(self):
+        verts = [[0,0],[1,0],[0,1],[99,99],[99,99],[99,99]]
+        tris = [[0,1,2]]
+        new_verts, new_tris = remove_lone_verts(verts, tris)
+        self.failUnless(new_verts.tolist() == verts[0:3])
+        self.failUnless(new_tris.tolist() == tris)
+     
+    def test_remove_lone_verts_f(self):
+        verts = [[0,0],[1,0],[99,99],[0,1],[99,99],[1,1],[99,99]]
+        tris = [[0,1,3],[0,1,5]]
+        new_verts, new_tris = remove_lone_verts(verts, tris)
+        self.failUnless(new_verts.tolist() == [[0,0],[1,0],[0,1],[1,1]])
+        self.failUnless(new_tris.tolist() == [[0,1,2],[0,1,3]])
+        
+######
+# 
+######
+        
+    def test_get_min_max_values(self):
+        
+        list=[8,9,6,1,4]
+        min1, max1 = get_min_max_values(list)
+        
+        assert min1==1 
+        assert max1==9
+        
+    def test_get_min_max_values1(self):
+        
+        list=[-8,-9,-6,-1,-4]
+        min1, max1 = get_min_max_values(list)
+        
+#        print 'min1,max1',min1,max1
+        assert min1==-9 
+        assert max1==-1
+
+#    def test_get_min_max_values2(self):
+#        '''
+#        The min and max supplied are greater than the ones in the 
+#        list and therefore are the ones returned
+#        '''
+#        list=[-8,-9,-6,-1,-4]
+#        min1, max1 = get_min_max_values(list,-10,10)
+#        
+##        print 'min1,max1',min1,max1
+#        assert min1==-10 
+#        assert max1==10
+        
+    def test_make_plots_from_csv_files(self):
+        
+        #if sys.platform == 'win32':  #Windows
+            try: 
+                import pylab
+            except ImportError:
+                #ANUGA don't need pylab to work so the system doesn't 
+                #rely on pylab being installed 
+                return
+            
+        
+            current_dir=getcwd()+sep+'abstract_2d_finite_volumes'
+            temp_dir = tempfile.mkdtemp('','figures')
+    #        print 'temp_dir',temp_dir
+            fileName = temp_dir+sep+'time_series_3.csv'
+            file = open(fileName,"w")
+            file.write("time,stage,speed,momentum,elevation\n\
+1.0, 0, 0, 0, 10 \n\
+2.0, 5, 2, 4, 10 \n\
+3.0, 3, 3, 5, 10 \n")
+            file.close()
+    
+            fileName1 = temp_dir+sep+'time_series_4.csv'
+            file1 = open(fileName1,"w")
+            file1.write("time,stage,speed,momentum,elevation\n\
+1.0, 0, 0, 0, 5 \n\
+2.0, -5, -2, -4, 5 \n\
+3.0, -4, -3, -5, 5 \n")
+            file1.close()
+    
+            fileName2 = temp_dir+sep+'time_series_5.csv'
+            file2 = open(fileName2,"w")
+            file2.write("time,stage,speed,momentum,elevation\n\
+1.0, 0, 0, 0, 7 \n\
+2.0, 4, -0.45, 57, 7 \n\
+3.0, 6, -0.5, 56, 7 \n")
+            file2.close()
+            
+            dir, name=os.path.split(fileName)
+            csv2timeseries_graphs(directories_dic={dir:['gauge', 0, 0]},
+                                  output_dir=temp_dir,
+                                  base_name='time_series_',
+                                  plot_numbers=['3-5'],
+                                  quantities=['speed','stage','momentum'],
+                                  assess_all_csv_files=True,
+                                  extra_plot_name='test')
+            
+            #print dir+sep+name[:-4]+'_stage_test.png'
+            assert(access(dir+sep+name[:-4]+'_stage_test.png',F_OK)==True)
+            assert(access(dir+sep+name[:-4]+'_speed_test.png',F_OK)==True)
+            assert(access(dir+sep+name[:-4]+'_momentum_test.png',F_OK)==True)
+    
+            dir1, name1=os.path.split(fileName1)
+            assert(access(dir+sep+name1[:-4]+'_stage_test.png',F_OK)==True)
+            assert(access(dir+sep+name1[:-4]+'_speed_test.png',F_OK)==True)
+            assert(access(dir+sep+name1[:-4]+'_momentum_test.png',F_OK)==True)
+    
+    
+            dir2, name2=os.path.split(fileName2)
+            assert(access(dir+sep+name2[:-4]+'_stage_test.png',F_OK)==True)
+            assert(access(dir+sep+name2[:-4]+'_speed_test.png',F_OK)==True)
+            assert(access(dir+sep+name2[:-4]+'_momentum_test.png',F_OK)==True)
+    
+            del_dir(temp_dir)
+        
+
+
+    def test_greens_law(self):
+
+        from math import sqrt
+        
+        d1 = 80.0
+        d2 = 20.0
+        h1 = 1.0
+        h2 = greens_law(d1,d2,h1)
+
+        assert h2==sqrt(2.0)
+        
+    def test_calc_bearings(self):
+ 
+        from math import atan, degrees
+        #Test East
+        uh = 1
+        vh = 1.e-15
+        angle = calc_bearing(uh, vh)
+        if 89 < angle < 91: v=1
+        assert v==1
+        #Test West
+        uh = -1
+        vh = 1.e-15
+        angle = calc_bearing(uh, vh)
+        if 269 < angle < 271: v=1
+        assert v==1
+        #Test North
+        uh = 1.e-15
+        vh = 1
+        angle = calc_bearing(uh, vh)
+        if -1 < angle < 1: v=1
+        assert v==1
+        #Test South
+        uh = 1.e-15
+        vh = -1
+        angle = calc_bearing(uh, vh)
+        if 179 < angle < 181: v=1
+        assert v==1
+        #Test South-East
+        uh = 1
+        vh = -1
+        angle = calc_bearing(uh, vh)
+        if 134 < angle < 136: v=1
+        assert v==1
+        #Test North-East
+        uh = 1
+        vh = 1
+        angle = calc_bearing(uh, vh)
+        if 44 < angle < 46: v=1
+        assert v==1
+        #Test South-West
+        uh = -1
+        vh = -1
+        angle = calc_bearing(uh, vh)
+        if 224 < angle < 226: v=1
+        assert v==1
+        #Test North-West
+        uh = -1
+        vh = 1
+        angle = calc_bearing(uh, vh)
+        if 314 < angle < 316: v=1
+        assert v==1
+       
+    def test_calc_bearings_zero_vector(self): 
+        from math import atan, degrees
+
+        uh = 0
+        vh = 0
+        angle = calc_bearing(uh, vh)
+
+        assert angle == NAN
+        
+#-------------------------------------------------------------
+
+if __name__ == "__main__":
+    suite = unittest.makeSuite(Test_Util, 'test')
+#    runner = unittest.TextTestRunner(verbosity=2)
+    runner = unittest.TextTestRunner(verbosity=1)
+    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_all.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_all.py	(revision 9459)
+++ 	(revision )
@@ -1,102 +1,0 @@
-"""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__':
-
-    from os import sep
-
-    #Attempt to compile all extensions
-    #execfile('..' + sep + 'utilities' + sep + 'compile.py')
-
-    #FIXME: Temporary measure
-    #os.chdir('..' + sep + 'utilities')
-    #execfile('compile.py')
-    #os.chdir('..' + sep + 'pyvolution')    
-    
-    #FIXME: Temporary measure
-    #os.chdir('..' + sep + 'triangle')
-    #execfile('compile.py')
-    #os.chdir('..' + sep + 'pyvolution')   
-    
-    #os.system('python compile.py') 
-
-    #print regressionTest()
-    #unittest.main(defaultTest='regressionTest')
-    
-    suite = regressionTest()
-    runner = unittest.TextTestRunner() #(verbosity=2)
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_ermapper.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_ermapper.py	(revision 9459)
+++ 	(revision )
@@ -1,189 +1,0 @@
-#!/usr/bin/env python
-
-import unittest
-
-
-import ermapper_grids
-from os import remove
-
-import numpy as num
-
-
-class Test_ERMapper(unittest.TestCase):
-    def setUp(self):
-        pass
-
-    def tearDown(self):
-        pass
-
-    def test_write_grid(self):
-        header_filename = 'test_write_ermapper_grid.ers'
-        data_filename = 'test_write_ermapper_grid'
-        
-        original_grid = num.array([[0.0, 0.1, 1.0], [2.0, 3.0, 4.0]])
-
-        # Check that the function works when passing the filename without
-        # a '.ers' extension
-        ermapper_grids.write_ermapper_grid(data_filename, original_grid)
-        new_grid = ermapper_grids.read_ermapper_grid(data_filename)
-        assert num.allclose(original_grid, new_grid)
-
-        # Check that the function works when passing the filename with
-        # a '.ers' extension
-        ermapper_grids.write_ermapper_grid(header_filename, original_grid)
-        new_grid = ermapper_grids.read_ermapper_grid(header_filename)
-        assert num.allclose(original_grid, new_grid)
-
-        # Clean up created files
-        remove(data_filename)
-        remove(header_filename)
-        
-    def test_basic_single_line_grid(self):
-        # Setup test data
-        filename = 'test_write_ermapper_grid'
-        original_grid = num.array([0.0, 0.1, 1.0, 2.0, 3.0, 4.0])
-
-        # Write test data
-        ermapper_grids.write_ermapper_data(original_grid, filename, num.float64)
-
-        # Read in the test data
-        new_grid = ermapper_grids.read_ermapper_data(filename, num.float64)
-
-        # Check that the test data that has been read in matches the original data
-        assert num.allclose(original_grid, new_grid)
-
-        # Clean up created files
-        remove(filename)
-        
-    def test_basic_single_line_grid_default_format(self):
-        # Setup test data
-        filename = 'test_write_ermapper_grid'
-        original_grid = num.array([0.0, 0.1, 1.0, 2.0, 3.0, 4.0])
-
-        # Write test data
-        ermapper_grids.write_ermapper_data(original_grid, filename)
-
-        # Read in the test data
-        new_grid = ermapper_grids.read_ermapper_data(filename)
-
-        # Check that the test data that has been read in matches the original data
-        assert num.allclose(original_grid, new_grid)
-
-        # Clean up created files
-        remove(filename)
-        
-    def test_write_default_header(self):
-        data_filename = 'test_write_ermapper_grid'
-
-        # setup test data
-        original_grid = num.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
-        # Write test data
-        ermapper_grids.write_ermapper_data(original_grid, data_filename)
-        # Write test header using all default values
-        header_filename = data_filename + '.ers'                              
-        ermapper_grids.write_ermapper_header(header_filename)
-
-        # Check that the read in values match the default values
-        header = ermapper_grids.read_ermapper_header(header_filename)
-
-        assert header['datum'] == '"GDA94"'
-        assert header['projection'] == '"GEOGRAPHIC"'  
-        assert header['coordinatetype'] == 'LL'
-        assert header['rotation'] == '0:0:0.0'
-        assert header['celltype'] == 'IEEE4ByteReal'
-        assert header['nullcellvalue'] == '-99999'
-        assert header['xdimension'] == '100'
-        assert header['registrationcellx'] == '0'
-        assert header['ydimension'] == '100'
-        assert header['registrationcelly'] == '2'
-        assert header['nroflines'] == '3'
-        assert header['nrofcellsperline'] == '4'
-        assert header['longitude'] == '0:0:0'
-        assert header['latitude'] == '0:0:0'
-        assert header['nrofbands'] == '1'
-        assert header['value'] == '"Default_Band"'
-
-        # Clean up created files
-        remove(data_filename)
-        remove(header_filename)
-        
-    def test_header_creation(self):
-        header = {}
-        # have some values that aren't defaults
-        header['nroflines'] = '2'
-        header['nrofcellsperline'] = '3'
-
-        header = ermapper_grids.create_default_header(header)
-
-
-        # default values
-        assert header['datum'] == '"GDA94"'
-        assert header['projection'] == '"GEOGRAPHIC"'  
-        assert header['coordinatetype'] == 'LL'
-        assert header['rotation'] == '0:0:0.0'
-        assert header['celltype'] == 'IEEE4ByteReal'
-        assert header['nullcellvalue'] == '-99999'
-        assert header['xdimension'] == '100'
-        assert header['registrationcellx'] == '0'
-        assert header['ydimension'] == '100'
-        assert header['longitude'] == '0:0:0'
-        assert header['latitude'] == '0:0:0'
-        assert header['nrofbands'] == '1'
-        assert header['value'] == '"Default_Band"'
-
-        # non-default values
-        assert header['nroflines'] == '2'
-        assert header['nrofcellsperline'] == '3'
-        assert header['registrationcelly'] == '1'
-
-
-    def test_write_non_default_header(self):
-        header_filename = 'test_write_ermapper_grid.ers'
-
-        # setup test data
-        header = {}
-        # have some values that aren't defaults
-        header['nroflines'] = '2'
-        header['nrofcellsperline'] = '3'
-        
-        # Write test header using non-default values                           
-        ermapper_grids.write_ermapper_header(header_filename, header)
-
-        # Check that the read in values match the default values
-        header = ermapper_grids.read_ermapper_header(header_filename)
-
-        # default values
-        assert header['datum'] == '"GDA94"'
-        assert header['projection'] == '"GEOGRAPHIC"'  
-        assert header['coordinatetype'] == 'LL'
-        assert header['rotation'] == '0:0:0.0'
-        assert header['celltype'] == 'IEEE4ByteReal'
-        assert header['nullcellvalue'] == '-99999'
-        assert header['xdimension'] == '100'
-        assert header['registrationcellx'] == '0'
-        assert header['ydimension'] == '100'
-        assert header['longitude'] == '0:0:0'
-        assert header['latitude'] == '0:0:0'
-        assert header['nrofbands'] == '1'
-        assert header['value'] == '"Default_Band"'
-
-        # non-default values
-        assert header['nroflines'] == '2'
-        assert header['nrofcellsperline'] == '3'
-        assert header['registrationcelly'] == '1'
-
-        # Clean up created files
-        remove(header_filename)        
-
-
-# def test_default_filenames
-# def test_write_header
-# def test_multi_band_grid
-
-       
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_ERMapper,'test')
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_gauge.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_gauge.py	(revision 9459)
+++ 	(revision )
@@ -1,549 +1,0 @@
-#!/usr/bin/env python
-
-
-import unittest
-from math import sqrt, pi
-import tempfile, os
-from os import access, F_OK,sep, removedirs,remove,mkdir,getcwd
-
-import anuga
-#from anuga.abstract_2d_finite_volumes.util import *
-from anuga.abstract_2d_finite_volumes.gauge import sww2csv_gauges
-from anuga.config import epsilon
-
-from anuga.utilities.numerical_tools import NAN,mean
-
-from sys import platform 
-
-from anuga.pmesh.mesh import Mesh
-
-from anuga.file.sww import SWW_file
-from anuga.file_conversion.file_conversion import timefile2netcdf
-from anuga.utilities.file_utils import del_dir
-from csv import reader, writer
-import time
-import string
-
-import numpy as num
-
-
-def test_function(x, y):
-    return x+y
-
-class Test_Gauge(unittest.TestCase):
-    def setUp(self):
-
-        def elevation_function(x, y):
-            return -x
-        
-        """ Setup for all tests. """
-        
-        mesh_file = tempfile.mktemp(".tsh")    
-        points = [[0.0,0.0],[6.0,0.0],[6.0,6.0],[0.0,6.0]]
-        m = Mesh()
-        m.add_vertices(points)
-        m.auto_segment()
-        m.generate_mesh(verbose=False)
-        m.export_mesh_file(mesh_file)
-        
-        # Create shallow water domain
-        domain = anuga.Domain(mesh_file)
-        os.remove(mesh_file)
- 
-        domain.default_order = 2
-
-        # This test was made before tight_slope_limiters were introduced
-        # Since were are testing interpolation values this is OK
-        domain.tight_slope_limiters = 0
-                
-        # Set some field values
-        domain.set_quantity('elevation', elevation_function)
-        domain.set_quantity('friction', 0.03)
-        domain.set_quantity('xmomentum', 3.0)
-        domain.set_quantity('ymomentum', 4.0)
-
-        ######################
-        # Boundary conditions
-        B = anuga.Transmissive_boundary(domain)
-        domain.set_boundary( {'exterior': B})
-
-        # This call mangles the stage values.
-        domain.distribute_to_vertices_and_edges()
-        domain.set_quantity('stage', 1.0)
-
-        domain.set_name('datatest' + str(time.time()))
-        domain.smooth = True
-        domain.reduction = mean
-        
-        self.domain = domain
-        
-        
-    def tearDown(self):
-        """Called at end of each test."""
-        if self.sww:
-            os.remove(self.sww.filename)
-
-    def _create_sww(self,stage=10.0, timestep=2.0):
-        self.sww = SWW_file(self.domain)
-        self.sww.store_connectivity()
-        self.sww.store_timestep()
-        self.domain.set_quantity('stage', stage) # This is automatically limited
-        # so it will not be less than the elevation
-        self.domain.set_time(self.domain.get_time()-self.domain.starttime+timestep)
-        self.sww.store_timestep()
-        
-        
-    def test_sww2csv_0(self):
-
-        """Most of this test was copied from test_interpolate
-        test_interpole_sww2csv
-        
-        This is testing the sww2csv_gauges function, by creating a sww file and
-        then exporting the gauges and checking the results.
-        """
-        
-        domain = self.domain
-        self._create_sww()
-        
-        # test the function
-        points = [[5.0,1.],[0.5,2.]]
-
-        points_file = tempfile.mktemp(".csv") 
-#        points_file = 'test_point.csv'
-        file_id = open(points_file,"w")
-        file_id.write("name, easting, northing, elevation \n\
-point1, 5.0, 1.0, 3.0\n\
-point2, 0.5, 2.0, 9.0\n")
-        file_id.close()
-
-        
-        sww2csv_gauges(self.sww.filename, 
-                       points_file,
-                       verbose=False,
-                       use_cache=False)
-
-#        point1_answers_array = [[0.0,1.0,-5.0,3.0,4.0], [2.0,10.0,-5.0,3.0,4.0]]
-        point1_answers_array = [[0.0,0.0,1.0,6.0,-5.0,3.0,4.0], [2.0,2.0/3600.,10.0,15.0,-5.0,3.0,4.0]]
-        point1_filename = 'gauge_point1.csv'
-        point1_handle = open(point1_filename)
-        point1_reader = reader(point1_handle)
-        point1_reader.next()
-
-        line=[]
-        for i,row in enumerate(point1_reader):
-            #print 'i',i,'row',row
-            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
-                         float(row[4]),float(row[5]),float(row[6])])
-            #print 'assert line',line[i],'point1',point1_answers_array[i]
-            assert num.allclose(line[i], point1_answers_array[i])
-
-        point2_answers_array = [[0.0,0.0,1.0,1.5,-0.5,3.0,4.0], [2.0,2.0/3600.,10.0,10.5,-0.5,3.0,4.0]]
-        point2_filename = 'gauge_point2.csv' 
-        point2_handle = open(point2_filename)
-        point2_reader = reader(point2_handle)
-        point2_reader.next()
-                        
-        line=[]
-        for i,row in enumerate(point2_reader):
-#            print 'i',i,'row',row
-            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
-                         float(row[4]),float(row[5]),float(row[6])])
-#            print 'assert line',line[i],'point1',point1_answers_array[i]
-            assert num.allclose(line[i], point2_answers_array[i])
-                         
-        # clean up
-        point1_handle.close()
-        point2_handle.close()
-        #os.remove(points_file)
-        #os.remove(point1_filename)
-        #os.remove(point2_filename)
-
-
-    def test_sww2csv_gauges1(self):
-        from anuga.pmesh.mesh import Mesh
-        from csv import reader,writer
-        import time
-        import string
-        
-        """Most of this test was copied from test_interpolate
-        test_interpole_sww2csv
-        
-        This is testing the sww2csv_gauges function, by creating a sww file and
-        then exporting the gauges and checking the results.
-        
-        This tests the ablity not to have elevation in the points file and 
-        not store xmomentum and ymomentum
-        """
-        
-        domain = self.domain
-        self._create_sww()
-        
-        # test the function
-        points = [[5.0,1.],[0.5,2.]]
-
-        points_file = tempfile.mktemp(".csv")
-#        points_file = 'test_point.csv'
-        file_id = open(points_file,"w")
-        file_id.write("name,easting,northing \n\
-point1, 5.0, 1.0\n\
-point2, 0.5, 2.0\n")
-        file_id.close()
-
-        sww2csv_gauges(self.sww.filename, 
-                            points_file,
-                            quantities=['stage', 'elevation'],
-                            use_cache=False,
-                            verbose=False)
-
-        point1_answers_array = [[0.0,1.0,-5.0], [2.0,10.0,-5.0]]
-        point1_filename = 'gauge_point1.csv'
-        point1_handle = file(point1_filename)
-        point1_reader = reader(point1_handle)
-        point1_reader.next()
-
-        line=[]
-        for i,row in enumerate(point1_reader):
-#            print 'i',i,'row',row
-            # note the 'hole' (element 1) below - skip the new 'hours' field
-            line.append([float(row[0]),float(row[2]),float(row[3])])
-            #print 'line',line[i],'point1',point1_answers_array[i]
-            assert num.allclose(line[i], point1_answers_array[i])
-
-        point2_answers_array = [[0.0,1.0,-0.5], [2.0,10.0,-0.5]]
-        point2_filename = 'gauge_point2.csv' 
-        point2_handle = file(point2_filename)
-        point2_reader = reader(point2_handle)
-        point2_reader.next()
-                        
-        line=[]
-        for i,row in enumerate(point2_reader):
-#            print 'i',i,'row',row
-            # note the 'hole' (element 1) below - skip the new 'hours' field
-            line.append([float(row[0]),float(row[2]),float(row[3])])
-#            print 'line',line[i],'point1',point1_answers_array[i]
-            assert num.allclose(line[i], point2_answers_array[i])
-                         
-        # clean up
-        point1_handle.close()
-        point2_handle.close() 
-        os.remove(points_file)
-        os.remove(point1_filename)
-        os.remove(point2_filename)        
-        
-
-    def test_sww2csv_gauges2(self):
-        
-        """Most of this test was copied from test_interpolate
-        test_interpole_sww2csv
-        
-        This is testing the sww2csv_gauges function, by creating a sww file and
-        then exporting the gauges and checking the results.
-        
-        This is the same as sww2csv_gauges except set domain.set_starttime to 5.
-        Therefore testing the storing of the absolute time in the csv files
-        """
-        
-        domain = self.domain
-        domain.set_starttime(1)
-        
-        self._create_sww(timestep=2)
-        
-        # test the function
-        points = [[5.0,1.],[0.5,2.]]
-
-        points_file = tempfile.mktemp(".csv")
-#        points_file = 'test_point.csv'
-        file_id = open(points_file,"w")
-        file_id.write("name, easting, northing, elevation \n\
-point1, 5.0, 1.0, 3.0\n\
-point2, 0.5, 2.0, 9.0\n")
-        file_id.close()
-        
-        sww2csv_gauges(self.sww.filename, 
-                            points_file,
-                            verbose=False,
-                            use_cache=False)
-
-#        point1_answers_array = [[0.0,1.0,-5.0,3.0,4.0], [2.0,10.0,-5.0,3.0,4.0]]
-        point1_answers_array = [[2.0,2.0/3600.,1.0,6.0,-5.0,3.0,4.0], [3.0,3.0/3600.,10.0,15.0,-5.0,3.0,4.0]]
-        point1_filename = 'gauge_point1.csv'
-        point1_handle = file(point1_filename)
-        point1_reader = reader(point1_handle)
-        point1_reader.next()
-
-        line=[]
-        for i,row in enumerate(point1_reader):
-            #print 'i',i,'row',row
-            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
-                         float(row[4]), float(row[5]), float(row[6])])
-            #print 'assert line',line[i],'answer',point1_answers_array[i]
-            assert num.allclose(line[i], point1_answers_array[i])
-
-        point2_answers_array = [[2.0,2.0/3600.,1.0,1.5,-0.5,3.0,4.0], [3.0,3.0/3600.,10.0,10.5,-0.5,3.0,4.0]]
-        point2_filename = 'gauge_point2.csv' 
-        point2_handle = file(point2_filename)
-        point2_reader = reader(point2_handle)
-        point2_reader.next()
-                        
-        line=[]
-        for i,row in enumerate(point2_reader):
-            #print 'i',i,'row',row
-            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
-                         float(row[4]),float(row[5]), float(row[6])])
-            #print 'assert line',line[i],'point1',point1_answers_array[i]
-            assert num.allclose(line[i], point2_answers_array[i])
-                         
-        # clean up
-        point1_handle.close()
-        point2_handle.close()
-        os.remove(points_file)
-        os.remove(point1_filename)
-        os.remove(point2_filename)
-
-
-       
-    def test_sww2csv_gauge_point_off_mesh(self):
-        from anuga.pmesh.mesh import Mesh
-        from csv import reader,writer
-        import time
-        import string
-        
-        """Most of this test was copied from test_interpolate
-        test_interpole_sww2csv
-        
-        This is testing the sww2csv_gauges function with one gauge off the mesh, by creating a sww file and
-        then exporting the gauges and checking the results.
-        
-        This tests the correct values for when a gauge is off the mesh, which is important for parallel.
-        """
-
-        domain = self.domain
-        sww = self._create_sww()
-     
-        # test the function
-        points = [[50.0,1.],[50.5,-20.25]]
-
-#        points_file = tempfile.mktemp(".csv")
-        points_file = 'test_point.csv'
-        file_id = open(points_file,"w")
-        file_id.write("name,easting,northing \n\
-offmesh1, 50.0, 1.0\n\
-offmesh2, 50.5, 20.25\n")
-        file_id.close()
-
-        points_files = ['offmesh1.csv', 'offmesh2.csv']        
-        
-        for point_filename in points_files:
-            if os.path.exists(point_filename): os.remove(point_filename)         
-        
-        sww2csv_gauges(self.sww.filename, 
-                            points_file,
-                            quantities=['stage', 'elevation', 'bearing'],
-                            use_cache=False,
-                            verbose=False)
-
-        for point_filename in points_files: 
-            assert not os.path.exists(point_filename)
-            
-        os.remove(points_file)
-        
-        
-    def test_sww2csv_centroid(self):
-        
-        """Check sww2csv timeseries at centroid.
-        
-        Test the ability to get a timeseries at the centroid of a triangle, rather
-        than the given gauge point.
-        """
-        
-        domain = self.domain
-        sww = self._create_sww()
-        
-        # create a csv file containing our gauge points
-        points_file = tempfile.mktemp(".csv")
-        file_id = open(points_file,"w")
-# These values are where the centroids should be        
-#        file_id.write("name, easting, northing, elevation \n\
-#point1, 2.0, 2.0, 3.0\n\
-#point2, 4.0, 4.0, 9.0\n")
- 
-# These values are slightly off the centroids - will it find the centroids?
-        file_id.write("name, easting, northing, elevation \n\
-point1, 2.0, 1.0, 3.0\n\
-point2, 4.5, 4.0, 9.0\n")
-
- 
-        file_id.close()
-
-        sww2csv_gauges(self.sww.filename, 
-                       points_file,
-                       verbose=False,
-                       use_cache=False,
-                       output_centroids=True)
-
-        point1_answers_array = [[0.0,0.0,1.0,3.0,-2.0,3.0,4.0], [2.0,2.0/3600.,10.0,12.0,-2.0,3.0,4.0]]
-        point1_filename = 'gauge_point1.csv'
-        point1_handle = open(point1_filename)
-        point1_reader = reader(point1_handle)
-        point1_reader.next()
-
-        line=[]
-        for i,row in enumerate(point1_reader):
-            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
-                         float(row[4]),float(row[5]),float(row[6])])
-#           print 'assert line',line[i],'point1',point1_answers_array[i]
-            assert num.allclose(line[i], point1_answers_array[i])
-
-        point2_answers_array = [[0.0,0.0,1.0,5.0,-4.0,3.0,4.0], [2.0,2.0/3600.,10.0,14.0,-4.0,3.0,4.0]]
-        point2_filename = 'gauge_point2.csv' 
-        point2_handle = open(point2_filename)
-        point2_reader = reader(point2_handle)
-        point2_reader.next()
-                        
-        line=[]
-        for i,row in enumerate(point2_reader):
-            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),
-                         float(row[4]),float(row[5]),float(row[6])])
-#           print i, 'assert line',line[i],'point2',point2_answers_array[i]
-            assert num.allclose(line[i], point2_answers_array[i])
-                         
-        # clean up
-        point1_handle.close()
-        point2_handle.close()
-        os.remove(points_file)
-        os.remove(point1_filename)
-        os.remove(point2_filename)
-
-
-    def test_sww2csv_output_centroid_attribute(self):
-        
-        """Check sww2csv timeseries at centroid, then output the centroid coordinates.
-        
-        Test the ability to get a timeseries at the centroid of a triangle, rather
-        than the given gauge point, then output the results.
-        """
-        
-        domain = self.domain        
-        self._create_sww()
-        
-        # create a csv file containing our gauge points
-        points_file = tempfile.mktemp(".csv")
-        file_id = open(points_file,"w")
- 
-# These values are slightly off the centroids - will it find the centroids?
-        file_id.write("name, easting, northing, elevation \n\
-point1, 2.5, 4.25, 3.0\n")
-
-        file_id.close()
-
-        sww2csv_gauges(self.sww.filename, 
-                       points_file,
-                       quantities=['stage', 'xcentroid', 'ycentroid'],
-                       verbose=False,
-                       use_cache=False,
-                       output_centroids=True)
-
-        point1_answers_array = [[0.0,0.0,1.0,4.0,4.0], [2.0,2.0/3600.,10.0,4.0,4.0]]
-        point1_filename = 'gauge_point1.csv'
-        point1_handle = file(point1_filename)
-        point1_reader = reader(point1_handle)
-        point1_reader.next()
-
-        line=[]
-        for i,row in enumerate(point1_reader):
-            line.append([float(row[0]),float(row[1]),float(row[2]),float(row[3]),float(row[4])])
-#            print 'assert line',line[i],'point1',point1_answers_array[i]
-            assert num.allclose(line[i], point1_answers_array[i])
-
-        # clean up
-        point1_handle.close()        
-        os.remove(points_file)
-        os.remove(point1_filename)
-
-    def test_sww2csv_multiple_files(self):
-        """
-        This is testing the sww2csv_gauges function, by creating multiple 
-        sww files and then exporting the gauges and checking the results.
-        """
-        timestep=2.0
-        domain = self.domain
-        domain.set_starttime(0.)
-        # Create two sww files with timestep at end. These are to be
-        # stored consecutively in the gauge csv files
-        basename='datatest1'
-        domain.set_name(basename) 
-        self._create_sww(stage=10.,timestep=timestep)
-
-        domain.set_name(basename+str(time.time())) 
-        domain.set_time(domain.get_time()+timestep)
-        self._create_sww(stage=20.,timestep=timestep)
-
-        points_file = tempfile.mktemp(".csv")
-        file_id = open(points_file,"w")
-
-        # test the function at these points
-        points = [[5.0,1.],[0.5,2.]]
-
-        # create a csv file containing our gauge points
-        points_file = tempfile.mktemp(".csv")
-        file_id = open(points_file,"w")
-        file_id.write("name,easting,northing \n\
-point1, 5.0, 1.0\n\
-point2, 0.5, 2.0\n")
-        file_id.close()
-
-
-        sww2csv_gauges(basename+".sww", 
-                       points_file,
-                       quantities=['stage', 'elevation'],
-                       use_cache=False,
-                       verbose=False)
-
-        point1_answers_array = [[0.0,1.0,-5.0], [2.0,10.0,-5.0],[4.0,10.0,-5.0],
-                                [6.0,20.0,-5.0], [0.0,1.0,-5.0]]
-        point1_filename = 'gauge_point1.csv'
-        point1_handle = file(point1_filename)
-        point1_reader = reader(point1_handle)
-        point1_reader.next()
-
-        line=[]
-        for i,row in enumerate(point1_reader):
-            # note the 'hole' (element 1) below - skip the new 'hours' field
-            line.append([float(row[0]),float(row[2]),float(row[3])])
-            #print 'i', i
-            #print 'row',row
-            #print 'line',line[i],'point1',point1_answers_array[i]
-            assert num.allclose(line[i], point1_answers_array[i])
-
-        point2_answers_array = [[0.0,1.0,-0.5], [2.0,10.0,-0.5],[4.0,10.0,-0.5],
-                                [6.0,20.0,-0.5], [0.0,1.0,-0.5]]
-        point2_filename = 'gauge_point2.csv' 
-        point2_handle = file(point2_filename)
-        point2_reader = reader(point2_handle)
-        point2_reader.next()
-                        
-        line=[]
-        for i,row in enumerate(point2_reader):
-            # note the 'hole' (element 1) below - skip the new 'hours' field
-            line.append([float(row[0]),float(row[2]),float(row[3])])
-            #print 'line',line[i],'point2',point2_answers_array[i]
-            assert num.allclose(line[i], point2_answers_array[i])
-                         
-        # clean up
-        point1_handle.close()
-        point2_handle.close() 
-        os.remove(points_file)
-        os.remove(point1_filename)
-        os.remove(point2_filename)       
-
-        #remove second swwfile not removed by tearDown
-        os.remove(basename+".sww")
-        #os.remove(basename+str(time.time())+".sww")
-
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_Gauge, 'test_')
-#    runner = unittest.TextTestRunner(verbosity=2)
-    runner = unittest.TextTestRunner(verbosity=1)
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_general_mesh.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_general_mesh.py	(revision 9459)
+++ 	(revision )
@@ -1,517 +1,0 @@
-#!/usr/bin/env python
-
-
-import unittest
-from math import sqrt, pi
-
-
-from anuga.config import epsilon
-from general_mesh import General_mesh
-from anuga.coordinate_transforms.geo_reference import Geo_reference
-from mesh_factory import rectangular
-from anuga.shallow_water.shallow_water_domain import Domain
-
-import numpy as num
-
-
-class Test_General_Mesh(unittest.TestCase):
-    def setUp(self):
-        pass
-
-    def tearDown(self):
-        pass
-
-
-    def test_get_vertex_coordinates(self):
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        nodes, triangles, _ = rectangular(1, 3)
-        domain = General_mesh(nodes, triangles)
-
-
-        assert num.allclose(domain.get_nodes(), nodes)
-
-
-        M = domain.number_of_triangles        
-
-        V = domain.get_vertex_coordinates()
-        assert V.shape[0] == 3*M
-
-        for i in range(M):
-            for j in range(3):
-                k = triangles[i,j]  #Index of vertex j in triangle i
-                assert num.allclose(V[3*i+j,:], nodes[k])
-
-    def test_get_vertex_coordinates_with_geo_ref(self):
-        x0 = 314036.58727982
-        y0 = 6224951.2960092
-        geo = Geo_reference(56, x0, y0)
-        
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-        nodes = num.array([a, b, c, d, e, f])
-
-        nodes_absolute = geo.get_absolute(nodes)
-        
-        #                        bac,     bce,     ecf,     dbe
-        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int)
-
-        domain = General_mesh(nodes, triangles, geo_reference=geo)
-
-        verts = domain.get_vertex_coordinates(triangle_id=0)    # bac
-        msg = ("num.array([b,a,c])=\n%s\nshould be close to 'verts'=\n%s"
-               % (str(num.array([b,a,c])), str(verts)))
-        self.failUnless(num.allclose(num.array([b,a,c]), verts), msg)
-
-        verts = domain.get_vertex_coordinates(triangle_id=0)       
-        msg = ("num.array([b,a,c])=\n%s\nshould be close to 'verts'=\n%s"
-               % (str(num.array([b,a,c])), str(verts)))
-        self.assert_(num.allclose(num.array([b,a,c]), verts), msg)
-
-        verts = domain.get_vertex_coordinates(triangle_id=0, absolute=True)
-        msg = ("num.array([...])=\n%s\nshould be close to 'verts'=\n%s"
-               % (str(num.array([nodes_absolute[1],
-                                 nodes_absolute[0],
-                                 nodes_absolute[2]])),
-                  str(verts)))
-        self.assert_(num.allclose(num.array([nodes_absolute[1],
-                                             nodes_absolute[0],
-                                             nodes_absolute[2]]),
-                                  verts), msg)
-
-        verts = domain.get_vertex_coordinates(triangle_id=0,
-                                              absolute=True)       
-        msg = ("num.array([...])=\n%s\nshould be close to 'verts'=\n%s"
-               % (str(num.array([nodes_absolute[1],
-                                 nodes_absolute[0],
-                                 nodes_absolute[2]])),
-                  str(verts)))
-        self.assert_(num.allclose(num.array([nodes_absolute[1],
-                                             nodes_absolute[0],
-                                             nodes_absolute[2]]),
-                                  verts), msg)
-
-    def test_get_vertex_coordinates_triangle_id(self):
-        """test_get_vertex_coordinates_triangle_id
-        Test that vertices for one triangle can be returned.
-        """
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        nodes, triangles, _ = rectangular(1, 3)
-        domain = General_mesh(nodes, triangles)
-
-
-        assert num.allclose(domain.get_nodes(), nodes)
-
-
-        M = domain.number_of_triangles        
-
-        for i in range(M):
-            V = domain.get_vertex_coordinates(triangle_id=i)
-            assert V.shape[0] == 3
-
-            for j in range(3):
-                k = triangles[i,j]  #Index of vertex j in triangle i
-                assert num.allclose(V[j,:], nodes[k])
-
-
-    def test_get_edge_midpoint_coordinates(self):
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        nodes, triangles, _ = rectangular(1, 3)
-        domain = General_mesh(nodes, triangles)
-
-
-        assert num.allclose(domain.get_nodes(), nodes)
-
-
-        M = domain.number_of_triangles        
-
-        E = domain.get_edge_midpoint_coordinates()
-        assert E.shape[0] == 3*M
-
-        for i in range(M):
-            k0 = triangles[i,0]  #Index of vertex 0 in triangle i
-            k1 = triangles[i,1]  #Index of vertex 1 in triangle i
-            k2 = triangles[i,2]  #Index of vertex 2 in triangle i
-
-            assert num.allclose(E[3*i+0,:], 0.5*(nodes[k1]+nodes[k2]) )
-            assert num.allclose(E[3*i+1,:], 0.5*(nodes[k0]+nodes[k2]) )
-            assert num.allclose(E[3*i+2,:], 0.5*(nodes[k1]+nodes[k0]) )
-
-    def test_get_edge_midpoint_coordinates_with_geo_ref(self):
-        x0 = 314036.58727982
-        y0 = 6224951.2960092
-        geo = Geo_reference(56, x0, y0)
-        
-        a = num.array([0.0, 0.0])
-        b = num.array([0.0, 2.0])
-        c = num.array([2.0, 0.0])
-        d = num.array([0.0, 4.0])
-        e = num.array([2.0, 2.0])
-        f = num.array([4.0, 0.0])
-        nodes = num.array([a, b, c, d, e, f])
-
-        nodes_absolute = geo.get_absolute(nodes)
-        
-        #                        bac,     bce,     ecf,     dbe
-        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int)
-
-        domain = General_mesh(nodes, triangles, geo_reference=geo)
-
-        verts = domain.get_edge_midpoint_coordinates(triangle_id=0)    # bac
-        msg = ("num.array(1/2[a+c,b+c,a+b])=\n%s\nshould be close to 'verts'=\n%s"
-               % (str(num.array([0.5*(a+c),0.5*(b+c),0.5*(a+b)])), str(verts)))
-        self.failUnless(num.allclose(num.array([0.5*(a+c),0.5*(b+c),0.5*(a+b)]), verts), msg)
-
-
-        verts = domain.get_edge_midpoint_coordinates(triangle_id=0, absolute=True)
-        msg = ("num.array([...])=\n%s\nshould be close to 'verts'=\n%s"
-               % (str(0.5*num.array([nodes_absolute[0]+nodes_absolute[2],
-                                     nodes_absolute[1]+nodes_absolute[2],
-                                     nodes_absolute[1]+nodes_absolute[0]])),
-                  str(verts)))
-        self.assert_(num.allclose(0.5*num.array([nodes_absolute[0]+nodes_absolute[2],
-                                                 nodes_absolute[1]+nodes_absolute[2],
-                                                 nodes_absolute[1]+nodes_absolute[0]]),
-                                  verts), msg)
-
-    def test_get_edge_midpoint_coordinates_triangle_id(self):
-        """test_get_vertex_coordinates_triangle_id
-        Test that vertices for one triangle can be returned.
-        """
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        nodes, triangles, _ = rectangular(1, 3)
-        domain = General_mesh(nodes, triangles)
-
-
-        assert num.allclose(domain.get_nodes(), nodes)
-
-
-        M = domain.number_of_triangles        
-
-        for i in range(M):
-            E = domain.get_edge_midpoint_coordinates(triangle_id=i)
-            assert E.shape[0] == 3
-
-
-            k0 = triangles[i,0]  #Index of vertex 0 in triangle i
-            k1 = triangles[i,1]  #Index of vertex 0 in triangle i
-            k2 = triangles[i,2]  #Index of vertex 0 in triangle i
-
-            assert num.allclose(E[0,:], 0.5*(nodes[k1]+nodes[k2]))
-            assert num.allclose(E[1,:], 0.5*(nodes[k0]+nodes[k2]))
-            assert num.allclose(E[2,:], 0.5*(nodes[k1]+nodes[k0]))
-
-            E0 = domain.get_edge_midpoint_coordinate(i, 0 )
-            E1 = domain.get_edge_midpoint_coordinate(i, 1 )
-            E2 = domain.get_edge_midpoint_coordinate(i, 2 )
-
-            assert num.allclose(E0, 0.5*(nodes[k1]+nodes[k2]))
-            assert num.allclose(E1, 0.5*(nodes[k0]+nodes[k2]))
-            assert num.allclose(E2, 0.5*(nodes[k1]+nodes[k0]))
-            
-
-
-        
-        
-
-    def test_get_vertex_values(self):
-        """Get connectivity based on triangle lists.
-        """
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        nodes, triangles, _ = rectangular(1, 3)
-        domain = General_mesh(nodes, triangles)
-
-        msg = ("domain.get_triangles()=\n%s\nshould be the same as "
-               "'triangles'=\n%s"
-               % (str(domain.get_triangles()), str(triangles)))
-        assert num.allclose(domain.get_triangles(), triangles), msg
-        msg = ("domain.get_triangles([0,4])=\n%s\nshould be the same as "
-               "'[triangles[0], triangles[4]]' which is\n%s"
-               % (str(domain.get_triangles([0,4])),
-                  str([triangles[0], triangles[4]])))
-        assert num.allclose(domain.get_triangles([0,4]),
-                            [triangles[0], triangles[4]]), msg
-        
-
-    def test_vertex_value_indices(self):
-        """Check that structures are correct.
-        """
-        from mesh_factory import rectangular
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        nodes = num.array([a, b, c, d, e, f])
-        #bac, bce, ecf, dbe, daf, dae
-        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-        domain1 = General_mesh(nodes, triangles)
-        
-        #Create larger mesh
-        nodes, triangles, _ = rectangular(3, 6)
-        domain2 = General_mesh(nodes, triangles)
-
-        # Test both meshes
-        for domain in [domain1, domain2]:
-            assert sum(domain.number_of_triangles_per_node) ==\
-                   len(domain.vertex_value_indices)
-
-            # Check number of triangles per node
-            count = [0]*domain.number_of_nodes
-            for triangle in domain.triangles:
-                for i in triangle:
-                    count[i] += 1
-
-            #print count
-            #
-            assert num.allclose(count, domain.number_of_triangles_per_node)
-            
-            # Check indices
-            current_node = 0
-            k = 0 # Track triangles touching on node
-            for index in domain.vertex_value_indices:
-                k += 1
-                
-                triangle = index / 3
-                vertex = index % 3
-
-                assert domain.triangles[triangle, vertex] == current_node
-
-                if domain.number_of_triangles_per_node[current_node] == k:
-                    # Move on to next node
-                    k = 0
-                    current_node += 1
-                
-
-    def test_get_triangles_and_vertices_per_node(self):
-        """test_get_triangles_and_vertices_per_node -
-
-        Test that tuples of triangle, vertex can be extracted
-        from inverted triangles structure
-
-        """
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        nodes = num.array([a, b, c, d, e, f])
-        #bac, bce, ecf, dbe, daf, dae
-        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-        domain = General_mesh(nodes, triangles)
-
-        # One node
-        L = domain.get_triangles_and_vertices_per_node(node=2)
-        assert num.allclose(L[0], [0, 2])
-        assert num.allclose(L[1], [1, 1])
-        assert num.allclose(L[2], [2, 1])
-
-        # All nodes
-        ALL = domain.get_triangles_and_vertices_per_node()
-        assert len(ALL) == 6
-        for i, Lref in enumerate(ALL):
-            L = domain.get_triangles_and_vertices_per_node(node=i)
-            assert num.allclose(L, Lref)
-            
-
-        
-
-        
-
-
-    def test_areas(self):
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-        domain = General_mesh(points, vertices)        
-
-        assert domain.get_area() == 1.0
-        
-        
-        
-    def test_one_degenerate_triangles(self):
-
-        
-        a = num.array([1.0, 1.0])
-        b = num.array([0.0, 2.0])
-        c = num.array([2.0, 0.0])
-        d = num.array([0.0, 4.0])
-        e = num.array([2.0, 2.0])
-        f = num.array([4.0, 0.0])
-        nodes = num.array([a, b, c, d, e, f])
-
-        
-        #                        bac,     bce,     ecf,     dbe
-        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int)
-
-        try:
-            domain = General_mesh(nodes, triangles)
-        except AssertionError:
-            #print 'excepted assertion error'
-            pass
-            
-            
-
-    def test_two_degenerate_triangles(self):
-
-        
-        a = num.array([1.0, 1.0])
-        b = num.array([0.0, 2.0])
-        c = num.array([2.0, 0.0])
-        d = num.array([1.0, 2.0])
-        e = num.array([2.0, 2.0])
-        f = num.array([4.0, 0.0])
-        nodes = num.array([a, b, c, d, e, f])
-
-        #                        bac,     bce,     ecf,     dbe
-        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int)
-
-        
-        try:
-            domain = General_mesh(nodes, triangles)
-        except AssertionError:
-            #print 'excepted assertion error'
-            pass
-
-
-
-
-    def test_get_unique_vertex_values(self):
-        """
-        get unique_vertex based on triangle lists.
-        """
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-        domain = General_mesh(points, vertices)                
-
-        assert  domain.get_unique_vertices() == [0,1,2,3,4,5,6,7]
-        unique_vertices = domain.get_unique_vertices([0,1,4])
-        unique_vertices.sort()
-        assert unique_vertices == [0,1,2,4,5,6,7]
-
-        unique_vertices = domain.get_unique_vertices([0,4])
-        unique_vertices.sort()
-        assert unique_vertices == [0,2,4,5,6,7]
-
-    def test_get_node(self):
-        """test_get_triangles_and_vertices_per_node -
-
-        Test that tuples of triangle, vertex can be extracted
-        from inverted triangles structure
-
-        """
-        
-        x0 = 314036.58727982
-        y0 = 6224951.2960092
-        geo = Geo_reference(56, x0, y0)
-        
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        nodes = num.array([a, b, c, d, e, f])
-
-        nodes_absolute = geo.get_absolute(nodes)
-        
-        #                        bac,     bce,     ecf,     dbe
-        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-        domain = General_mesh(nodes, triangles, geo_reference = geo)
-        node = domain.get_node(2)        
-        msg = ('\nc=%s\nnode=%s' % (str(c), str(node)))
-        self.failUnless(num.alltrue(c == node), msg)
-
-        # repeat get_node(), see if result same
-        node = domain.get_node(2)        
-        msg = ('\nc=%s\nnode=%s' % (str(c), str(node)))
-        self.failUnless(num.alltrue(c == node), msg)
-        
-        node = domain.get_node(2, absolute=True)     
-        msg = ('\nnodes_absolute[2]=%s\nnode=%s'
-               % (str(nodes_absolute[2]), str(node)))
-        self.failUnless(num.alltrue(nodes_absolute[2] == node), msg)
-       
-        # repeat get_node(2, absolute=True), see if result same
-        node = domain.get_node(2, absolute=True)     
-        msg = ('\nnodes_absolute[2]=%s\nnode=%s'
-               % (str(nodes_absolute[2]), str(node)))
-        self.failUnless(num.alltrue(nodes_absolute[2] == node), msg)
-        
-
-    def test_assert_index_in_nodes(self):
-        """test_assert_index_in_nodes -
-
-        Test that node indices in triangles are within nodes array.
-
-        """
-        
-        x0 = 314036.58727982
-        y0 = 6224951.2960092
-        geo = Geo_reference(56, x0, y0)
-        
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        nodes = num.array([a, b, c, d, e, f])
-
-        nodes_absolute = geo.get_absolute(nodes)
-        
-        # max index is 5, use 5, expect success
-        triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-        General_mesh(nodes, triangles, geo_reference=geo)
-        
-        
-        # should fail with negative area
-        triangles = num.array([[0,1,2], [1,2,4], [4,2,5], [3,1,4]])
-        self.failUnlessRaises(AssertionError, General_mesh, 
-                              nodes, triangles, geo_reference=geo)
-
-        
-        # max index is 5, use 6, expect assert failure
-        triangles = num.array([[1,6,2], [1,2,4], [4,2,5], [3,1,4]])
-        self.failUnlessRaises(AssertionError, General_mesh,
-                              nodes, triangles, geo_reference=geo)
-        
-
-        
-        # max index is 5, use 10, expect assert failure
-        triangles = num.array([[1,10,2], [1,2,4], [4,2,5], [3,1,4]])
-        self.failUnlessRaises(AssertionError, General_mesh,
-                              nodes, triangles, geo_reference=geo)
-
-################################################################################
-
-if __name__ == "__main__":
-    #suite = unittest.makeSuite(Test_General_Mesh, 'test')
-    suite = unittest.makeSuite(Test_General_Mesh, 'test')     
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
-
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_generic_boundary_conditions.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_generic_boundary_conditions.py	(revision 9459)
+++ 	(revision )
@@ -1,437 +1,0 @@
-#!/usr/bin/env python
-"""
-    Generic boundary conditions for a domain.
-    
-    A boundary represents the edge of the model, where inflow, outflow, and
-    reflection can take place.
-    
-    The boundaries in this model can be applied universally across all
-    domain models, without being tied to a particular implementation.
-"""
-
-import unittest
-from math import sqrt, pi
-
-from generic_boundary_conditions import *
-from anuga.abstract_2d_finite_volumes.generic_domain import Generic_Domain
-from anuga.config import epsilon
-
-import numpy as num
-
-
-class Test_Generic_Boundary_Conditions(unittest.TestCase):
-    def setUp(self):
-        pass
-        #print "  Setting up"
-
-    def tearDown(self):
-        pass
-        #print "  Tearing down"
-
-
-    def test_generic(self):
-        b = Boundary()
-
-        try:
-            b.evaluate()
-        except:
-            pass
-        else:
-            raise Exception('Should have raised exception')
-
-
-    def test_dirichlet_empty(self):
-
-        try:
-            Bd = Dirichlet_boundary()
-        except:
-            pass
-        else:
-            raise Exception('Should have raised exception')
-
-    def test_dirichlet(self):
-        x = [3.14,0,0.1]
-        Bd = Dirichlet_boundary(x)
-
-        q = Bd.evaluate()
-        assert num.allclose(q, x)
-
-
-    def test_time(self):
-        from quantity import Quantity
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        domain = Generic_Domain(points, elements)
-        domain.check_integrity()
-
-        domain.conserved_quantities = ['stage', 'ymomentum']
-        domain.evolved_quantities = ['stage', 'ymomentum']        
-        domain.quantities['stage'] =\
-                                   Quantity(domain, [[1,2,3], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-        domain.quantities['ymomentum'] =\
-                                   Quantity(domain, [[2,3,4], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-
-        domain.check_integrity()
-
-        #Test time bdry, you need to provide a domain and function
-        try:
-            T = Time_boundary(domain)
-        except:
-            pass
-        else:
-            raise Exception('Should have raised exception')
-
-        #Test time bdry, you need to provide a function
-        try:
-            T = Time_boundary()
-        except:
-            pass
-        else:
-            raise Exception('Should have raised exception')
-
-
-        def function(t):
-            return [1.0, 0.0]
-        
-        T = Time_boundary(domain, function)
-
-        from anuga.config import default_boundary_tag
-        domain.set_boundary( {default_boundary_tag: T} )
-
-
-        #FIXME: should not necessarily be true always.
-        #E.g. with None as a boundary object.
-        assert len(domain.boundary) == len(domain.boundary_objects)
-
-        q = T.evaluate(0, 2)  #Vol=0, edge=2
-
-        assert num.allclose(q, [1.0, 0.0])
-
-
-    def test_time_space_boundary(self):
-        from quantity import Quantity
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        domain = Generic_Domain(points, elements)
-        domain.check_integrity()
-
-        domain.conserved_quantities = ['stage', 'ymomentum']
-        domain.evolved_quantities = ['stage', 'ymomentum']        
-        domain.quantities['stage'] =\
-                                   Quantity(domain, [[1,2,3], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-        domain.quantities['ymomentum'] =\
-                                   Quantity(domain, [[2,3,4], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-
-        domain.check_integrity()
-
-        #Test time space bdry, you need to provide a domain and function
-        try:
-            T = Time_space_boundary(domain)
-        except:
-            pass
-        else:
-            raise Exception('Should have raised exception')
-
-        #Test time bdry, you need to provide a function
-        try:
-            T = Time_space_boundary()
-        except:
-            pass
-        else:
-            raise Exception('Should have raised exception')
-
-
-        def function(t,x,y):
-            return [x,y]
-        
-        T = Time_space_boundary(domain, function)
-
-        from anuga.config import default_boundary_tag
-        domain.set_boundary( {default_boundary_tag: T} )
-
-
-        #FIXME: should not necessarily be true always.
-        #E.g. with None as a boundary object.
-        assert len(domain.boundary) == len(domain.boundary_objects)
-
-        q = T.evaluate(0, 2)  #Vol=0, edge=2
-        assert num.allclose(q, domain.get_edge_midpoint_coordinate(0,2))
-
-
-        q = T.evaluate(1, 1)  #Vol=1, edge=1
-        assert num.allclose(q, domain.get_edge_midpoint_coordinate(1,1))        
-
-
-
-
-
-    def test_transmissive(self):
-        from quantity import Quantity
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        domain = Generic_Domain(points, elements)
-        domain.check_integrity()
-
-        domain.conserved_quantities = ['stage', 'ymomentum']
-        domain.evolved_quantities = ['stage', 'ymomentum']        
-        domain.quantities['stage'] =\
-                                   Quantity(domain, [[1,2,3], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-        domain.quantities['ymomentum'] =\
-                                   Quantity(domain, [[2,3,4], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-
-        domain.check_integrity()
-
-        #Test transmissve bdry
-        try:
-            T = Transmissive_boundary()
-        except:
-            pass
-        else:
-            raise Exception('Should have raised exception')
-
-        T = Transmissive_boundary(domain)
-
-        from anuga.config import default_boundary_tag
-        domain.set_boundary( {default_boundary_tag: T} )
-
-
-        #FIXME: should not necessarily be true always.
-        #E.g. with None as a boundary object.
-        assert len(domain.boundary) == len(domain.boundary_objects)
-
-        q = T.evaluate(0, 2)  #Vol=0, edge=2
-
-        assert num.allclose(q, [1.5, 2.5])
-
-
-        # Now set the centroid_transmissive_bc flag to true
-        domain.set_centroid_transmissive_bc(True)
-
-        q = T.evaluate(0, 2)  #Vol=0, edge=2
-
-        assert num.allclose(q, [2.0 ,3.0]) # centroid value
-
-
-
-        
-
-    def NOtest_fileboundary_time_only(self):
-        """Test that boundary values can be read from file and interpolated
-        This is using the .tms file format
-        
-        See also test_util for comprenhensive testing of the underlying 
-        file_function and also tests in test_datamanager which tests 
-        file_function using the sts format
-        """
-        #FIXME (Ole): This test was disabled 18 August 2008 as no
-        # need for this was found. Rather I implemented an Exception
-        # to catch possible errors in the model setup
-        
-        from quantity import Quantity
-        import time, os
-        from math import sin, pi
-        from anuga.config import time_format
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        domain = Generic_Domain(points, elements)
-        domain.conserved_quantities = ['stage', 'ymomentum']
-        domain.quantities['stage'] =\
-                                   Quantity(domain, [[1,2,3], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-        domain.quantities['ymomentum'] =\
-                                   Quantity(domain, [[2,3,4], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-        domain.check_integrity()
-
-
-        #Write file
-        filename = 'boundarytest' + str(time.time())
-        fid = open(filename + '.txt', 'w')
-        start = time.mktime(time.strptime('2000', '%Y'))
-        dt = 5*60  #Five minute intervals
-        for i in range(10):
-            t = start + i*dt
-            t_string = time.strftime(time_format, time.gmtime(t))
-
-            fid.write('%s,%f %f\n' %(t_string, 1.0*i, sin(i*2*pi/10)))
-        fid.close()
-
-
-        #Convert ASCII file to NetCDF (Which is what we really like!)
-        
-        from anuga.shallow_water.data_manager import timefile2netcdf
-        
-        timefile2netcdf(filename, quantity_names = ['stage', 'ymomentum'])
-        
-
-
-        F = File_boundary(filename + '.tms', domain)
-
-        
-        os.remove(filename + '.txt')
-        os.remove(filename + '.tms')        
-
-
-        
-
-        #Check that midpoint coordinates at boundary are correctly computed
-        assert num.allclose( F.midpoint_coordinates,
-                             [[1.0, 0.0], [0.0, 1.0], [3.0, 0.0],
-                              [3.0, 1.0], [1.0, 3.0], [0.0, 3.0]])
-
-        #assert allclose(F.midpoint_coordinates[(3,2)], [0.0, 3.0])
-        #assert allclose(F.midpoint_coordinates[(3,1)], [1.0, 3.0])
-        #assert allclose(F.midpoint_coordinates[(0,2)], [0.0, 1.0])
-        #assert allclose(F.midpoint_coordinates[(0,0)], [1.0, 0.0])
-        #assert allclose(F.midpoint_coordinates[(2,0)], [3.0, 0.0])
-        #assert allclose(F.midpoint_coordinates[(2,1)], [3.0, 1.0])
-
-
-        #Check time interpolation
-        from anuga.config import default_boundary_tag
-        domain.set_boundary( {default_boundary_tag: F} )
-
-        domain.time = 5*30/2  #A quarter way through first step
-        q = F.evaluate()
-        assert num.allclose(q, [1.0/4, sin(2*pi/10)/4])
-
-
-        domain.time = 2.5*5*60  #Half way between steps 2 and 3
-        q = F.evaluate()
-        assert num.allclose(q, [2.5, (sin(2*2*pi/10) + sin(3*2*pi/10))/2])
-
-
-
-    def test_fileboundary_exception(self):
-        """Test that boundary object complains if number of
-        conserved quantities are wrong
-        """
-
-        from quantity import Quantity
-        import time, os
-        from math import sin, pi
-        from anuga.config import time_format
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        domain = Generic_Domain(points, elements)
-        domain.conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
-        domain.evolved_quantities = ['stage', 'xmomentum', 'ymomentum']
-        domain.quantities['stage'] =\
-                                   Quantity(domain, [[1,2,3], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-        domain.quantities['xmomentum'] =\
-                                   Quantity(domain, [[2,3,4], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-        domain.quantities['ymomentum'] =\
-                                   Quantity(domain, [[2,3,4], [5,5,5],
-                                                     [0,0,9], [-6, 3, 3]])
-
-        domain.check_integrity()
-
-        #Write file (with only two values)
-        filename = 'boundarytest' + str(time.time())
-        fid = open(filename + '.txt', 'w')
-        start = time.mktime(time.strptime('2000', '%Y'))
-        dt = 5*60  #Five minute intervals
-        for i in range(10):
-            t = start + i*dt
-            t_string = time.strftime(time_format, time.gmtime(t))
-
-            fid.write('%s,%f %f\n' %(t_string, 1.0*i, sin(i*2*pi/10)))
-        fid.close()
-
-
-        #Convert ASCII file to NetCDF (Which is what we really like!)
-        from anuga.file_conversion.file_conversion import timefile2netcdf
-        
-        timefile2netcdf(filename+'.txt', quantity_names = ['stage', 'xmomentum'])
-
-        
-        try:
-            F = File_boundary(filename + '.tms',
-                              domain)
-        except:
-            pass
-        else:
-            raise Exception('Should have raised an exception')
-        
-        os.remove(filename + '.txt')
-        os.remove(filename + '.tms')        
-
-
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_Generic_Boundary_Conditions, 'test')
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_generic_domain.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_generic_domain.py	(revision 9459)
+++ 	(revision )
@@ -1,902 +1,0 @@
-#!/usr/bin/env python
-
-import unittest
-from math import sqrt
-
-import anuga
-
-from anuga.abstract_2d_finite_volumes.generic_domain import *
-from anuga.pmesh.mesh_interface import create_mesh_from_regions
-from anuga.config import epsilon
-import numpy as num
-from anuga.pmesh.mesh import Segment, Vertex, Mesh
-
-
-def add_to_verts(tag, elements, domain):
-    if tag == "mound":
-        domain.test = "Mound"
-
-
-
-class Test_Domain(unittest.TestCase):
-    def setUp(self):
-        pass
-
-
-    def tearDown(self):
-        pass
-
-
-    def test_simple(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
-        evolved_quantities = ['stage', 'xmomentum', 'ymomentum', 'xvelocity']
-        
-        other_quantities = ['elevation', 'friction']
-
-        domain = Generic_Domain(points, vertices, None,
-                        conserved_quantities, evolved_quantities, other_quantities)
-        domain.check_integrity()
-
-        for name in conserved_quantities + other_quantities:
-            assert domain.quantities.has_key(name)
-
-
-        assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.)
-
-
-
-    def test_CFL(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
-        evolved_quantities = ['stage', 'xmomentum', 'ymomentum', 'xvelocity']
-        
-        other_quantities = ['elevation', 'friction']
-
-        domain = Generic_Domain(points, vertices, None,
-                        conserved_quantities, evolved_quantities, other_quantities)
-
-        try:
-            domain.set_CFL(-0.1)
-        except:
-            pass
-        else:
-            msg = 'Should have caught a negative cfl'
-            raise Exception, msg
-
-
-        
-        try:
-            domain.set_CFL(3.0)
-        except:
-            pass
-        else:
-            msg = 'Should have warned of cfl>2.0'
-            raise Exception, msg
-
-        assert domain.CFL == 3.0
-        
-
-    def test_conserved_quantities(self):
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        domain = Generic_Domain(points, vertices, boundary=None,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'])
-
-
-        domain.set_quantity('stage', [[1,2,3], [5,5,5],
-                                      [0,0,9], [-6, 3, 3]])
-
-        domain.set_quantity('xmomentum', [[1,2,3], [5,5,5],
-                                          [0,0,9], [-6, 3, 3]])
-
-        domain.check_integrity()
-
-        #Centroids
-        q = domain.get_conserved_quantities(0)
-        assert num.allclose(q, [2., 2., 0.])
-
-        q = domain.get_conserved_quantities(1)
-        assert num.allclose(q, [5., 5., 0.])
-
-        q = domain.get_conserved_quantities(2)
-        assert num.allclose(q, [3., 3., 0.])
-
-        q = domain.get_conserved_quantities(3)
-        assert num.allclose(q, [0., 0., 0.])
-
-
-        #Edges
-        q = domain.get_conserved_quantities(0, edge=0)
-        assert num.allclose(q, [2.5, 2.5, 0.])
-        q = domain.get_conserved_quantities(0, edge=1)
-        assert num.allclose(q, [2., 2., 0.])
-        q = domain.get_conserved_quantities(0, edge=2)
-        assert num.allclose(q, [1.5, 1.5, 0.])
-
-        for i in range(3):
-            q = domain.get_conserved_quantities(1, edge=i)
-            assert num.allclose(q, [5, 5, 0.])
-
-
-        q = domain.get_conserved_quantities(2, edge=0)
-        assert num.allclose(q, [4.5, 4.5, 0.])
-        q = domain.get_conserved_quantities(2, edge=1)
-        assert num.allclose(q, [4.5, 4.5, 0.])
-        q = domain.get_conserved_quantities(2, edge=2)
-        assert num.allclose(q, [0., 0., 0.])
-
-
-        q = domain.get_conserved_quantities(3, edge=0)
-        assert num.allclose(q, [3., 3., 0.])
-        q = domain.get_conserved_quantities(3, edge=1)
-        assert num.allclose(q, [-1.5, -1.5, 0.])
-        q = domain.get_conserved_quantities(3, edge=2)
-        assert num.allclose(q, [-1.5, -1.5, 0.])
-
-
-
-    def test_create_quantity_from_expression(self):
-        """Quantity created from other quantities using arbitrary expression
-
-        """
-
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        domain = Generic_Domain(points, vertices, boundary=None,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'],
-                        other_quantities = ['elevation', 'friction'])
-
-
-        domain.set_quantity('elevation', -1)
-
-
-        domain.set_quantity('stage', [[1,2,3], [5,5,5],
-                                      [0,0,9], [-6, 3, 3]])
-
-        domain.set_quantity('xmomentum', [[1,2,3], [5,5,5],
-                                          [0,0,9], [-6, 3, 3]])
-
-        domain.set_quantity('ymomentum', [[3,3,3], [4,2,1],
-                                          [2,4,-1], [1, 0, 1]])
-
-        domain.check_integrity()
-
-
-
-        expression = 'stage - elevation'
-        Q = domain.create_quantity_from_expression(expression)
-
-        assert num.allclose(Q.vertex_values, [[2,3,4], [6,6,6],
-                                              [1,1,10], [-5, 4, 4]])
-
-        expression = '(xmomentum*xmomentum + ymomentum*ymomentum)**0.5'
-        Q = domain.create_quantity_from_expression(expression)
-
-        X = domain.quantities['xmomentum'].vertex_values
-        Y = domain.quantities['ymomentum'].vertex_values
-
-        assert num.allclose(Q.vertex_values, (X**2 + Y**2)**0.5)
-
-
-
-    def test_set_quanitities_to_be_monitored(self):
-        """test_set_quanitities_to_be_monitored
-        """
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-
-        domain = Generic_Domain(points, vertices, boundary=None,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'],
-                        other_quantities = ['elevation', 'friction', 'depth'])
-
-
-        assert domain.quantities_to_be_monitored is None
-        domain.set_quantities_to_be_monitored(['stage', 'stage-elevation'])
-        assert len(domain.quantities_to_be_monitored) == 2
-        assert domain.quantities_to_be_monitored.has_key('stage')
-        assert domain.quantities_to_be_monitored.has_key('stage-elevation')
-        for key in domain.quantities_to_be_monitored['stage'].keys():
-            assert domain.quantities_to_be_monitored['stage'][key] is None
-
-
-        # Check that invalid requests are dealt with
-        try:
-            domain.set_quantities_to_be_monitored(['yyyyy'])        
-        except:
-            pass
-        else:
-            msg = 'Should have caught illegal quantity'
-            raise Exception, msg
-
-        try:
-            domain.set_quantities_to_be_monitored(['stage-xx'])        
-        except NameError:
-            pass
-        else:
-            msg = 'Should have caught illegal quantity'
-            raise Exception, msg
-
-        try:
-            domain.set_quantities_to_be_monitored('stage', 'stage-elevation')
-        except:
-            pass
-        else:
-            msg = 'Should have caught too many arguments'
-            raise Exception, msg
-
-        try:
-            domain.set_quantities_to_be_monitored('stage', 'blablabla')
-        except:
-            pass
-        else:
-            msg = 'Should have caught polygon as a string'
-            raise Exception, msg        
-
-
-
-        # Now try with a polygon restriction
-        domain.set_quantities_to_be_monitored('xmomentum',
-                                              polygon=[[1,1], [1,3], [3,3], [3,1]],
-                                              time_interval = [0,3])
-        assert domain.monitor_indices[0] == 1
-        assert domain.monitor_time_interval[0] == 0
-        assert domain.monitor_time_interval[1] == 3        
-        
-
-    def test_set_quantity_from_expression(self):
-        """Quantity set using arbitrary expression
-
-        """
-
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        domain = Generic_Domain(points, vertices, boundary=None,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'],
-                        other_quantities = ['elevation', 'friction', 'depth'])
-
-
-        domain.set_quantity('elevation', -1)
-
-
-        domain.set_quantity('stage', [[1,2,3], [5,5,5],
-                                      [0,0,9], [-6, 3, 3]])
-
-        domain.set_quantity('xmomentum', [[1,2,3], [5,5,5],
-                                          [0,0,9], [-6, 3, 3]])
-
-        domain.set_quantity('ymomentum', [[3,3,3], [4,2,1],
-                                          [2,4,-1], [1, 0, 1]])
-
-
-
-
-        domain.set_quantity('depth', expression = 'stage - elevation')
-
-        domain.check_integrity()
-
-
-
-
-        Q = domain.quantities['depth']
-
-        assert num.allclose(Q.vertex_values, [[2,3,4], [6,6,6],
-                                              [1,1,10], [-5, 4, 4]])
-
-
-
-                                      
-    def test_add_quantity(self):
-        """Test that quantities already set can be added to using
-        add_quantity
-
-        """
-
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        domain = Generic_Domain(points, vertices, boundary=None,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'],
-                        other_quantities = ['elevation', 'friction', 'depth'])
-
-
-        A = num.array([[1,2,3], [5,5,-5], [0,0,9], [-6,3,3]], num.float)
-        B = num.array([[2,4,4], [3,2,1], [6,-3,4], [4,5,-1]], num.float)
-        
-        # Shorthands
-        stage = domain.quantities['stage']
-        elevation = domain.quantities['elevation']
-        depth = domain.quantities['depth']
-        
-        # Go testing
-        domain.set_quantity('elevation', A)
-        domain.add_quantity('elevation', B)
-        assert num.allclose(elevation.vertex_values, A+B)
-        
-        domain.add_quantity('elevation', 4)
-        assert num.allclose(elevation.vertex_values, A+B+4)        
-        
-        
-        # Test using expression
-        domain.set_quantity('stage', [[1,2,3], [5,5,5],
-                                      [0,0,9], [-6, 3, 3]])        
-        domain.set_quantity('depth', 1.0)                                     
-        domain.add_quantity('depth', expression = 'stage - elevation')        
-        assert num.allclose(depth.vertex_values, stage.vertex_values-elevation.vertex_values+1)
-                
-        
-        # Check self referential expression
-        reference = 2*stage.vertex_values - depth.vertex_values 
-        domain.add_quantity('stage', expression = 'stage - depth')                
-        assert num.allclose(stage.vertex_values, reference)        
-                                      
-
-        # Test using a function
-        def f(x, y):
-            return x+y
-            
-        domain.set_quantity('elevation', f)            
-        domain.set_quantity('stage', 5.0)
-        domain.set_quantity('depth', expression = 'stage - elevation')
-        
-        domain.add_quantity('depth', f)
-        assert num.allclose(stage.vertex_values, depth.vertex_values)                
-         
-            
-                                      
-                                      
-    def test_setting_timestepping_method(self):
-        """test_setting_timestepping_method
-        """
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-
-        domain = Generic_Domain(points, vertices, boundary=None,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'],
-                        other_quantities = ['elevation', 'friction', 'depth'])
-
-
-        domain.timestepping_method = None
-
-
-        # Check that invalid requests are dealt with
-        try:
-            domain.set_timestepping_method('eee')        
-        except:
-            pass
-        else:
-            msg = 'Should have caught illegal method'
-            raise Exception, msg
-
-
-        #Should have no trouble with euler, rk2 or rk3
-        domain.set_timestepping_method('euler')
-        domain.set_timestepping_method('rk2')
-        domain.set_timestepping_method('rk3')
-
-        domain.set_timestepping_method(1)
-        domain.set_timestepping_method(2)
-        domain.set_timestepping_method(3)
-        # Since rk3 was just set, check if the number of substeps is correct
-        assert domain.timestep_fluxcalls == 3
-
-        #test get timestepping method
-        assert domain.get_timestepping_method() == 'rk3'
-
-
-
-    def test_boundary_indices(self):
-
-        from anuga.config import default_boundary_tag
-
-
-        a = [0.0, 0.5]
-        b = [0.0, 0.0]
-        c = [0.5, 0.5]
-
-        points = [a, b, c]
-        vertices = [ [0,1,2] ]
-        domain = Generic_Domain(points, vertices)
-
-        domain.set_boundary( \
-                {default_boundary_tag: anuga.Dirichlet_boundary([5,2,1])} )
-
-
-        domain.check_integrity()
-
-        assert num.allclose(domain.neighbours, [[-1,-2,-3]])
-
-
-
-    def test_boundary_conditions(self):
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-        boundary = { (0, 0): 'First',
-                     (0, 2): 'First',
-                     (2, 0): 'Second',
-                     (2, 1): 'Second',
-                     (3, 1): 'Second',
-                     (3, 2): 'Second'}
-
-
-        domain = Generic_Domain(points, vertices, boundary,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'])
-        domain.check_integrity()
-
-
-
-        domain.set_quantity('stage', [[1,2,3], [5,5,5],
-                                      [0,0,9], [-6, 3, 3]])
-
-
-        domain.set_boundary( {'First': anuga.Dirichlet_boundary([5,2,1]),
-                              'Second': anuga.Transmissive_boundary(domain)} )
-
-        domain.update_boundary()
-
-        assert domain.quantities['stage'].boundary_values[0] == 5. #Dirichlet
-        assert domain.quantities['stage'].boundary_values[1] == 5. #Dirichlet
-        assert domain.quantities['stage'].boundary_values[2] ==\
-               domain.get_conserved_quantities(2, edge=0)[0] #Transmissive (4.5)
-        assert domain.quantities['stage'].boundary_values[3] ==\
-               domain.get_conserved_quantities(2, edge=1)[0] #Transmissive (4.5)
-        assert domain.quantities['stage'].boundary_values[4] ==\
-               domain.get_conserved_quantities(3, edge=1)[0] #Transmissive (-1.5)
-        assert domain.quantities['stage'].boundary_values[5] ==\
-               domain.get_conserved_quantities(3, edge=2)[0] #Transmissive (-1.5)
-
-        #Check enumeration
-        for k, ((vol_id, edge_id), _) in enumerate(domain.boundary_objects):
-            assert domain.neighbours[vol_id, edge_id] == -k-1
-
-
-
-
-    def test_conserved_evolved_boundary_conditions(self):
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-        boundary = { (0, 0): 'First',
-                     (0, 2): 'First',
-                     (2, 0): 'Second',
-                     (2, 1): 'Second',
-                     (3, 1): 'Second',
-                     (3, 2): 'Second'}
-
-
- 
-        try:
-            domain = Generic_Domain(points, vertices, boundary,
-                            conserved_quantities = ['stage', 'xmomentum', 'ymomentum'],
-                            evolved_quantities =\
-                                   ['stage', 'xmomentum', 'xvelocity', 'ymomentum', 'yvelocity'])
-        except:
-            pass
-        else:
-            msg = 'Should have caught the evolved quantities not being in order'
-            raise Exception, msg            
-
-
-        domain = Generic_Domain(points, vertices, boundary,
-                        conserved_quantities = ['stage', 'xmomentum', 'ymomentum'],
-                        evolved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum', 'xvelocity', 'yvelocity'])
-
-
-        domain.set_quantity('stage', [[1,2,3], [5,5,5],
-                                      [0,0,9], [6, -3, 3]])
-
-
-        domain.set_boundary( {'First': anuga.Dirichlet_boundary([5,2,1,4,6]),
-                              'Second': anuga.Transmissive_boundary(domain)} )
-
-#        try:
-#            domain.update_boundary()
-#        except:
-#            pass
-#        else:
-#            msg = 'Should have caught the lack of conserved_values_to_evolved_values member function'
-#            raise Exception, msg
-
-        domain.update_boundary()
-
-        def  conserved_values_to_evolved_values(q_cons, q_evol):
-
-            q_evol[0:3] = q_cons
-            q_evol[3] = q_cons[1]/q_cons[0]
-            q_evol[4] = q_cons[2]/q_cons[0]
-
-            return q_evol
-
-        domain.conserved_values_to_evolved_values = conserved_values_to_evolved_values
-
-        domain.update_boundary()
-
-
-        assert domain.quantities['stage'].boundary_values[0] == 5. #Dirichlet
-        assert domain.quantities['stage'].boundary_values[1] == 5. #Dirichlet
-        assert domain.quantities['xvelocity'].boundary_values[0] == 4. #Dirichlet
-        assert domain.quantities['yvelocity'].boundary_values[1] == 6. #Dirichlet
-
-        q_cons = domain.get_conserved_quantities(2, edge=0) #Transmissive
-        assert domain.quantities['stage'    ].boundary_values[2] == q_cons[0]
-        assert domain.quantities['xmomentum'].boundary_values[2] == q_cons[1]
-        assert domain.quantities['ymomentum'].boundary_values[2] == q_cons[2]
-        assert domain.quantities['xvelocity'].boundary_values[2] == q_cons[1]/q_cons[0]
-        assert domain.quantities['yvelocity'].boundary_values[2] == q_cons[2]/q_cons[0]
-
-        q_cons = domain.get_conserved_quantities(2, edge=1) #Transmissive
-        assert domain.quantities['stage'    ].boundary_values[3] == q_cons[0]
-        assert domain.quantities['xmomentum'].boundary_values[3] == q_cons[1]
-        assert domain.quantities['ymomentum'].boundary_values[3] == q_cons[2]
-        assert domain.quantities['xvelocity'].boundary_values[3] == q_cons[1]/q_cons[0]
-        assert domain.quantities['yvelocity'].boundary_values[3] == q_cons[2]/q_cons[0]        
-
-
-        q_cons = domain.get_conserved_quantities(3, edge=1) #Transmissive
-        assert domain.quantities['stage'    ].boundary_values[4] == q_cons[0]
-        assert domain.quantities['xmomentum'].boundary_values[4] == q_cons[1]
-        assert domain.quantities['ymomentum'].boundary_values[4] == q_cons[2]
-        assert domain.quantities['xvelocity'].boundary_values[4] == q_cons[1]/q_cons[0]
-        assert domain.quantities['yvelocity'].boundary_values[4] == q_cons[2]/q_cons[0]               
-
-
-        q_cons = domain.get_conserved_quantities(3, edge=2) #Transmissive
-        assert domain.quantities['stage'    ].boundary_values[5] == q_cons[0]
-        assert domain.quantities['xmomentum'].boundary_values[5] == q_cons[1]
-        assert domain.quantities['ymomentum'].boundary_values[5] == q_cons[2]
-        assert domain.quantities['xvelocity'].boundary_values[5] == q_cons[1]/q_cons[0]
-        assert domain.quantities['yvelocity'].boundary_values[5] == q_cons[2]/q_cons[0]
- 
-
-    def test_distribute_first_order(self):
-        """Domain implements a default first order gradient limiter
-        """
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-        boundary = { (0, 0): 'Third',
-                     (0, 2): 'First',
-                     (2, 0): 'Second',
-                     (2, 1): 'Second',
-                     (3, 1): 'Second',
-                     (3, 2): 'Third'}
-
-
-        domain = Generic_Domain(points, vertices, boundary,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'])
-        domain.set_default_order(1)
-        domain.check_integrity()
-
-
-        domain.set_quantity('stage', [[1,2,3], [5,5,5],
-                                      [0,0,9], [-6, 3, 3]])
-
-        assert num.allclose( domain.quantities['stage'].centroid_values,
-                             [2,5,3,0] )
-
-        domain.set_quantity('xmomentum', [[1,1,1], [2,2,2],
-                                          [3,3,3], [4, 4, 4]])
-
-        domain.set_quantity('ymomentum', [[10,10,10], [20,20,20],
-                                          [30,30,30], [40, 40, 40]])
-
-
-        domain.distribute_to_vertices_and_edges()
-
-        #First order extrapolation
-        assert num.allclose( domain.quantities['stage'].vertex_values,
-                             [[ 2.,  2.,  2.],
-                              [ 5.,  5.,  5.],
-                              [ 3.,  3.,  3.],
-                              [ 0.,  0.,  0.]])
-
-
-
-
-    def test_update_conserved_quantities(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-        boundary = { (0, 0): 'Third',
-                     (0, 2): 'First',
-                     (2, 0): 'Second',
-                     (2, 1): 'Second',
-                     (3, 1): 'Second',
-                     (3, 2): 'Third'}
-
-
-        domain = Generic_Domain(points, vertices, boundary,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'])
-        domain.check_integrity()
-
-
-        domain.set_quantity('stage', [1,2,3,4], location='centroids')
-        domain.set_quantity('xmomentum', [1,2,3,4], location='centroids')
-        domain.set_quantity('ymomentum', [1,2,3,4], location='centroids')
-
-
-        #Assign some values to update vectors
-        #Set explicit_update
-
-
-        for name in domain.conserved_quantities:
-            domain.quantities[name].explicit_update = num.array([4.,3.,2.,1.])
-            domain.quantities[name].semi_implicit_update = num.array([1.,1.,1.,1.])
-
-
-        #Update with given timestep (assuming no other forcing terms)
-        domain.timestep = 0.1
-        domain.update_conserved_quantities()
-
-        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
-        denom = num.ones(4, num.float) - domain.timestep*sem
-
-#        x = array([1, 2, 3, 4]) + array( [.4,.3,.2,.1] )
-#        x /= denom
-
-        x = num.array([1., 2., 3., 4.])
-        x += domain.timestep*num.array( [4,3,2,1] )
-        x /= denom
-
-
-        for name in domain.conserved_quantities:
-            assert num.allclose(domain.quantities[name].centroid_values, x)
-
-
-    def test_set_region(self):
-        """Set quantities for sub region
-        """
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-        boundary = { (0, 0): 'Third',
-                     (0, 2): 'First',
-                     (2, 0): 'Second',
-                     (2, 1): 'Second',
-                     (3, 1): 'Second',
-                     (3, 2): 'Third'}
-
-        domain = Generic_Domain(points, vertices, boundary,
-                        conserved_quantities =\
-                        ['stage', 'xmomentum', 'ymomentum'])
-        domain.set_default_order(1)                        
-        domain.check_integrity()
-
-        domain.set_quantity('stage', [[1,2,3], [5,5,5],
-                                      [0,0,9], [-6, 3, 3]])
-
-        assert num.allclose( domain.quantities['stage'].centroid_values,
-                             [2,5,3,0] )
-
-        domain.set_quantity('xmomentum', [[1,1,1], [2,2,2],
-                                          [3,3,3], [4, 4, 4]])
-
-        domain.set_quantity('ymomentum', [[10,10,10], [20,20,20],
-                                          [30,30,30], [40, 40, 40]])
-
-
-        domain.distribute_to_vertices_and_edges()
-
-        #First order extrapolation
-        assert num.allclose( domain.quantities['stage'].vertex_values,
-                             [[ 2.,  2.,  2.],
-                              [ 5.,  5.,  5.],
-                              [ 3.,  3.,  3.],
-                              [ 0.,  0.,  0.]])
-
-        domain.build_tagged_elements_dictionary({'mound':[0,1]})
-        domain.set_tag_region([add_to_verts])
-
-        self.failUnless(domain.test == "Mound",
-                        'set region failed')
-
-                             
-    def test_rectangular_periodic_and_ghosts(self):
-
-        from mesh_factory import rectangular_periodic
-        
-
-        M=5
-        N=2
-        points, vertices, boundary, full_send_dict, ghost_recv_dict = rectangular_periodic(M, N)
-
-        assert num.allclose(ghost_recv_dict[0][0], [24, 25, 26, 27,  0,  1,  2,  3])
-        assert num.allclose(full_send_dict[0][0] , [ 4,  5,  6,  7, 20, 21, 22, 23])
-
-        conserved_quantities = ['quant1', 'quant2']
-        domain = Generic_Domain(points, vertices, boundary, conserved_quantities,
-                        full_send_dict=full_send_dict,
-                        ghost_recv_dict=ghost_recv_dict)
-
-
-
-
-        assert num.allclose(domain.ghost_recv_dict[0][0], [24, 25, 26, 27,  0,  1,  2,  3])
-        assert num.allclose(domain.full_send_dict[0][0] , [ 4,  5,  6,  7, 20, 21, 22, 23])
-
-        def xylocation(x,y):
-            return 15*x + 9*y
-
-        
-        domain.set_quantity('quant1',xylocation,location='centroids')
-        domain.set_quantity('quant2',xylocation,location='centroids')
-
-
-        assert num.allclose(domain.quantities['quant1'].centroid_values,
-                            [  0.5,   1.,   5.,    5.5,   3.5,   4.,    8.,    8.5,   6.5,  7.,   11.,   11.5,   9.5,
-                               10.,   14.,   14.5,  12.5,  13.,   17.,   17.5,  15.5,  16.,   20.,   20.5,
-                               18.5,  19.,   23.,   23.5])
-
-
-
-        assert num.allclose(domain.quantities['quant2'].centroid_values,
-                            [  0.5,   1.,   5.,    5.5,   3.5,   4.,    8.,    8.5,   6.5,  7.,   11.,   11.5,   9.5,
-                               10.,   14.,   14.5,  12.5,  13.,   17.,   17.5,  15.5,  16.,   20.,   20.5,
-                               18.5,  19.,   23.,   23.5])
-
-        domain.update_ghosts()
-
-
-        assert num.allclose(domain.quantities['quant1'].centroid_values,
-                            [  15.5,  16.,   20.,   20.5,   3.5,   4.,    8.,    8.5,   6.5,  7.,   11.,   11.5,   9.5,
-                               10.,   14.,   14.5,  12.5,  13.,   17.,   17.5,  15.5,  16.,   20.,   20.5,
-                                3.5,   4.,    8.,    8.5])
-
-
-
-        assert num.allclose(domain.quantities['quant2'].centroid_values,
-                            [  15.5,  16.,   20.,   20.5,   3.5,   4.,    8.,    8.5,   6.5,  7.,   11.,   11.5,   9.5,
-                               10.,   14.,   14.5,  12.5,  13.,   17.,   17.5,  15.5,  16.,   20.,   20.5,
-                                3.5,   4.,    8.,    8.5])
-
-        
-        assert num.allclose(domain.tri_full_flag, [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-                                                   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0])
-
-        assert num.allclose(domain.node_full_flag, [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-                                                   1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0])
-
-
-        #assert num.allclose(domain.number_of_full_nodes, 18)
-        
-        assert num.allclose(domain.number_of_full_triangles, 20)
-
-        #Test that points are arranged in a counter clock wise order
-        domain.check_integrity()
-
-
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_Domain,'test_')
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_ghost.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_ghost.py	(revision 9459)
+++ 	(revision )
@@ -1,52 +1,0 @@
-#!/usr/bin/env python
-
-import unittest
-from math import sqrt
-
-from anuga.abstract_2d_finite_volumes.generic_domain import Generic_Domain
-from anuga.config import epsilon
-
-import numpy as num
-
-
-class Test_Domain(unittest.TestCase):
-    def setUp(self):
-        pass
-
-
-    def tearDown(self):
-        pass
-
-
-    def test_simple(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
-        other_quantities = ['elevation', 'friction']
-
-        domain = Generic_Domain(points, vertices, None,
-                        conserved_quantities, None, other_quantities)
-        domain.check_integrity()
-
-        for name in conserved_quantities + other_quantities:
-            assert domain.quantities.has_key(name)
-
-
-        assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.)
-
-
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_Domain,'test')
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_neighbour_mesh.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_neighbour_mesh.py	(revision 9459)
+++ 	(revision )
@@ -1,1853 +1,0 @@
-#!/usr/bin/env python
-
-
-
-#FIXME: Seperate the tests for mesh and general_mesh
-
-#FIXME (Ole): Maxe this test independent of anything that inherits from General_mesh (namely shallow_water)
-
-import unittest
-from math import sqrt
-
-from neighbour_mesh import *
-from mesh_factory import rectangular
-from mesh_factory import rectangular_periodic
-from anuga.config import epsilon
-
-from anuga.coordinate_transforms.geo_reference import Geo_reference
-from anuga.geometry.polygon import is_inside_polygon
-from anuga.utilities.numerical_tools import ensure_numeric
-
-import numpy as num
-
-
-def distance(x, y):
-    return sqrt(num.sum((num.array(x)-num.array(y))**2))
-
-class Test_Mesh(unittest.TestCase):
-    def setUp(self):
-        pass
-
-    def tearDown(self):
-        pass
-
-    def test_triangle_inputs(self):
-        points = [[0.0, 0.0], [4.0, 0.0], [0.0, 3.0]]
-        vertices = [0,1,2] #Wrong
-
-        try:
-            mesh = Mesh(points, vertices)
-        except:
-            pass
-        else:
-            msg = 'Should have raised exception'
-            raise Exception(msg)
-
-
-    def test_basic_triangle(self):
-
-        a = [0.0, 0.0]
-        b = [4.0, 0.0]
-        c = [0.0, 3.0]
-
-        points = [a, b, c]
-        vertices = [[0,1,2]]
-        mesh = Mesh(points, vertices)
-
-        #Centroid
-        centroid = mesh.centroid_coordinates[0]
-        assert centroid[0] == 4.0/3
-        assert centroid[1] == 1.0
-
-        #Area
-        assert mesh.areas[0] == 6.0,\
-               'Area was %f, should have been 6.0' %mesh.areas[0]
-
-        #Normals
-        normals = mesh.get_normals()
-        assert num.allclose(normals[0, 0:2], [3.0/5, 4.0/5])
-        assert num.allclose(normals[0, 2:4], [-1.0, 0.0])
-        assert num.allclose(normals[0, 4:6], [0.0, -1.0])
-
-        assert num.allclose(mesh.get_normal(0,0), [3.0/5, 4.0/5])
-        assert num.allclose(mesh.get_normal(0,1), [-1.0, 0.0])
-        assert num.allclose(mesh.get_normal(0,2), [0.0, -1.0])
-
-        #Edge lengths
-        assert num.allclose(mesh.edgelengths[0], [5.0, 3.0, 4.0])
-
-
-        #Vertex coordinates
-        #V = mesh.get_vertex_coordinates()
-        #assert allclose(V[0], [0.0, 0.0, 4.0, 0.0, 0.0, 3.0])
-        
-
-        V = mesh.get_vertex_coordinates()
-        assert num.allclose(V, [ [0.0, 0.0],
-                             [4.0, 0.0],
-                             [0.0, 3.0] ])
-
-        V0 = mesh.get_vertex_coordinate(0, 0)
-        assert num.allclose(V0, [0.0, 0.0])
-
-        V1 = mesh.get_vertex_coordinate(0, 1)
-        assert num.allclose(V1, [4.0, 0.0])
-
-        V2 = mesh.get_vertex_coordinate(0, 2)
-        assert num.allclose(V2, [0.0, 3.0])
-
-
-        #General tests:
-
-        #Test that points are arranged in a counter clock wise order etc
-        mesh.check_integrity()
-
-
-        #Test that the centroid is located 2/3 of the way
-        #from each vertex to the midpoint of the opposite side
-
-        V = mesh.get_vertex_coordinates()
-        x0 = V[0, 0]; y0 = V[0, 1]
-        x1 = V[1, 0]; y1 = V[1, 1]
-        x2 = V[2, 0]; y2 = V[2, 1]
-        #x0 = V[0,0]
-        #y0 = V[0,1]
-        #x1 = V[0,2]
-        #y1 = V[0,3]
-        #x2 = V[0,4]
-        #y2 = V[0,5]
-
-        m0 = [(x1 + x2)/2, (y1 + y2)/2]
-        m1 = [(x0 + x2)/2, (y0 + y2)/2]
-        m2 = [(x1 + x0)/2, (y1 + y0)/2]
-
-        d0 = distance(centroid, [x0, y0])
-        d1 = distance(m0, [x0, y0])
-        assert d0 == 2*d1/3
-        #
-        d0 = distance(centroid, [x1, y1])
-        d1 = distance(m1, [x1, y1])
-        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
-
-        d0 = distance(centroid, [x2, y2])
-        d1 = distance(m2, [x2, y2])
-        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
-
-        #Radius
-        d0 = distance(centroid, m0)
-        assert d0 == 5.0/6
-
-        d1 = distance(centroid, m1)
-        assert d1 == sqrt(73.0/36)
-
-        d2 = distance(centroid, m2)
-        assert d2 == sqrt(13.0/9)
-
-        assert mesh.radii[0] == min(d0, d1, d2)
-        assert mesh.radii[0] == 5.0/6
-
-
-        #Let x be the centroid of triangle abc.
-        #Test that areas of the three triangles axc, cxb, and bxa are equal.
-        points = [a, b, c, centroid]
-        vertices = [[0,3,2], [2,3,1], [1,3,0]]
-        new_mesh = Mesh(points, vertices)
-
-        assert new_mesh.areas[0] == new_mesh.areas[1]
-        assert new_mesh.areas[1] == new_mesh.areas[2]
-        assert new_mesh.areas[1] == new_mesh.areas[2]
-
-        assert new_mesh.areas[1] == mesh.areas[0]/3
-
-
-
-    def test_general_triangle(self):
-        a = [2.0, 1.0]
-        b = [6.0, 2.0]
-        c = [1.0, 3.0]
-
-        points = [a, b, c]
-        vertices = [[0,1,2]]
-
-        mesh = Mesh(points, vertices)
-        centroid = mesh.centroid_coordinates[0]
-
-
-        #Test that the centroid is located 2/3 of the way
-        #from each vertex to the midpoint of the opposite side
-
-        V = mesh.get_vertex_coordinates()
-        x0 = V[0, 0]; y0 = V[0, 1]
-        x1 = V[1, 0]; y1 = V[1, 1]
-        x2 = V[2, 0]; y2 = V[2, 1]        
-
-        #x0 = V[0,0]
-        #y0 = V[0,1]
-        #x1 = V[0,2]
-        #y1 = V[0,3]
-        #x2 = V[0,4]
-        #y2 = V[0,5]
-
-        m0 = [(x1 + x2)/2, (y1 + y2)/2]
-        m1 = [(x0 + x2)/2, (y0 + y2)/2]
-        m2 = [(x1 + x0)/2, (y1 + y0)/2]
-
-        d0 = distance(centroid, [x0, y0])
-        d1 = distance(m0, [x0, y0])
-        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
-        #
-        d0 = distance(centroid, [x1, y1])
-        d1 = distance(m1, [x1, y1])
-        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
-
-        d0 = distance(centroid, [x2, y2])
-        d1 = distance(m2, [x2, y2])
-        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
-
-        #Radius
-        d0 = distance(centroid, m0)
-        d1 = distance(centroid, m1)
-        d2 = distance(centroid, m2)
-        assert mesh.radii[0] == min(d0, d1, d2)
-
-
-
-        #Let x be the centroid of triangle abc.
-        #Test that areas of the three triangles axc, cxb, and bxa are equal.
-
-        points = [a, b, c, centroid]
-        vertices = [[0,3,2], [2,3,1], [1,3,0]]
-        new_mesh = Mesh(points, vertices)
-
-        assert new_mesh.areas[0] == new_mesh.areas[1]
-        assert new_mesh.areas[1] == new_mesh.areas[2]
-        assert new_mesh.areas[1] == new_mesh.areas[2]
-
-        assert new_mesh.areas[1] == mesh.areas[0]/3
-
-
-        #Test that points are arranged in a counter clock wise order
-        mesh.check_integrity()
-
-    def test_inscribed_circle_equilateral(self):
-        """test that the radius is calculated correctly by mesh in the case of an equilateral triangle"""
-        a = [0.0, 0.0]
-        b = [2.0, 0.0]
-        c = [1.0, sqrt(3.0)]
-
-        points = [a, b, c]
-        vertices = [[0,1,2]]
-
-        mesh = Mesh(points, vertices,use_inscribed_circle=False)
-        assert num.allclose(mesh.radii[0],sqrt(3.0)/3),'Steve''s doesn''t work'
-
-        mesh = Mesh(points, vertices,use_inscribed_circle=True)
-        assert num.allclose(mesh.radii[0],sqrt(3.0)/3),'inscribed circle doesn''t work'
-
-    def test_inscribed_circle_rightangle_triangle(self):
-        """test that the radius is calculated correctly by mesh in the case of a right-angled triangle"""
-        a = [0.0, 0.0]
-        b = [4.0, 0.0]
-        c = [0.0, 3.0]
-
-        points = [a, b, c]
-        vertices = [[0,1,2]]
-
-        mesh = Mesh(points, vertices,use_inscribed_circle=False)
-        assert num.allclose(mesh.radii[0],5.0/6),'Steve''s doesn''t work'
-
-        mesh = Mesh(points, vertices,use_inscribed_circle=True)
-        assert num.allclose(mesh.radii[0],1.0),'inscribed circle doesn''t work'
-
-
-    def test_two_triangles(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        e = [2.0, 2.0]
-        points = [a, b, c, e]
-        vertices = [ [1,0,2], [1,2,3] ]   #bac, bce
-        mesh = Mesh(points, vertices)
-
-        assert mesh.areas[0] == 2.0
-
-        assert num.allclose(mesh.centroid_coordinates[0], [2.0/3, 2.0/3])
-
-
-        #Test that points are arranged in a counter clock wise order
-        mesh.check_integrity()
-
-
-
-    def test_more_triangles(self):
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe, daf, dae
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-        mesh = Mesh(points, vertices)
-
-        #Test that points are arranged in a counter clock wise order
-        mesh.check_integrity()
-
-        assert mesh.areas[0] == 2.0
-        assert mesh.areas[1] == 2.0
-        assert mesh.areas[2] == 2.0
-        assert mesh.areas[3] == 2.0
-
-        assert mesh.edgelengths[1,0] == 2.0
-        assert mesh.edgelengths[1,1] == 2.0
-        assert mesh.edgelengths[1,2] == sqrt(8.0)
-
-        assert num.allclose(mesh.centroid_coordinates[0], [2.0/3, 2.0/3])
-        assert num.allclose(mesh.centroid_coordinates[1], [4.0/3, 4.0/3])
-        assert num.allclose(mesh.centroid_coordinates[2], [8.0/3, 2.0/3])
-        assert num.allclose(mesh.centroid_coordinates[3], [2.0/3, 8.0/3])
-
-    def test_mesh_and_neighbours(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-        mesh = Mesh(points, vertices)
-
-        mesh.check_integrity()
-
-
-        T = mesh
-        tid = 0
-        assert T.number_of_boundaries[tid] == 2
-        assert T.neighbours[tid, 0] < 0  #Opposite point b (0,2)
-        assert T.neighbours[tid, 1] == 1 #Opposite point a (0,0)
-        assert T.neighbours[tid, 2] < 0  #Opposite point c (2,0)
-
-        tid = 1
-        assert T.number_of_boundaries[tid] == 0
-        assert T.neighbours[tid, 0] == 2  #Opposite point b (0,2)
-        assert T.neighbours[tid, 1] == 3  #Opposite point c (2,0)
-        assert T.neighbours[tid, 2] == 0  #Opposite point e (2,2)
-
-        tid = 2
-        assert T.number_of_boundaries[tid] == 2
-        assert T.neighbours[tid, 0] < 0   #Opposite point e (2,2)
-        assert T.neighbours[tid, 1] < 0   #Opposite point c (2,0)
-        assert T.neighbours[tid, 2] == 1  #Opposite point f (4,0)
-
-        tid = 3
-        assert T.number_of_boundaries[tid] == 2
-        assert T.neighbours[tid, 0] == 1  #Opposite point d (0,4)
-        assert T.neighbours[tid, 1] < 0   #Opposite point b (0,3)
-        assert T.neighbours[tid, 2] < 0   #Opposite point e (2,2)
-
-        #Neighbouring edges
-        tid = 0
-        assert T.neighbour_edges[tid, 0] < 0  #Opposite point b (0,2)
-        assert T.neighbour_edges[tid, 1] == 2 #Opposite point a (0,0)
-        assert T.neighbour_edges[tid, 2] < 0  #Opposite point c (2,0)
-
-        tid = 1
-        assert T.neighbour_edges[tid, 0] == 2 #Opposite point b (0,2)
-        assert T.neighbour_edges[tid, 1] == 0 #Opposite point c (2,0)
-        assert T.neighbour_edges[tid, 2] == 1 #Opposite point e (2,2)
-
-        tid = 2
-        assert T.neighbour_edges[tid, 0] < 0  #Opposite point e (2,2)
-        assert T.neighbour_edges[tid, 1] < 0  #Opposite point c (2,0)
-        assert T.neighbour_edges[tid, 2] == 0 #Opposite point f (4,0)
-
-        tid = 3
-        assert T.neighbour_edges[tid, 0] == 1 #Opposite point d (0,4)
-        assert T.neighbour_edges[tid, 1] < 0  #Opposite point b (0,3)
-        assert T.neighbour_edges[tid, 2] < 0  #Opposite point e (2,2)
-
-
-    def test_build_neighbour_structure_duplicates(self):
-        p0 = [-66.0, 14.0]
-        p1 = [14.0, -66.0]
-        p2 = [14.0, 14.0]
-        p3 = [60.0, 20.0]
-        p4 = [10.0, 60.0]
-        p5 = [60.0, 60.0]
-
-        points = [p0, p1, p2, p3, p4, p5]
-        triangles = [ [0, 1, 2],
-                      [3, 2, 1],
-                      [0, 2, 4],
-                      [0, 2, 4],
-                      [4, 2, 5],
-                      [5, 2, 3]]
-        try:
-            mesh = Mesh(points, triangles)
-        except:
-            pass
-        else:
-            raise Exception("triangle edge duplicates not caught")
-
-
-    def test_rectangular_mesh_basic(self):
-        M=1
-        N=1
-
-        points, vertices, boundary = rectangular(M, N)
-        mesh = Mesh(points, vertices, boundary)
-
-        #Test that points are arranged in a counter clock wise order
-        mesh.check_integrity()
-
-        M=2
-        N=2
-        points, vertices, boundary = rectangular(M, N)
-        mesh = Mesh(points, vertices, boundary)
-
-        #Test that points are arranged in a counter clock wise order
-        mesh.check_integrity()
-
-        #assert mesh.boundary[(7,1)] == 2 # top
-        assert mesh.boundary[(7,1)] == 'top' # top
-        assert mesh.boundary[(3,1)] == 'top' # top
-
-
-
-
-
-
-    def test_boundary_tags(self):
-
-
-        points, vertices, boundary = rectangular(4, 4)
-        mesh = Mesh(points, vertices, boundary)
-
-
-        #Test that points are arranged in a counter clock wise order
-        mesh.check_integrity()
-
-        #print mesh.get_boundary_tags()
-        #print mesh.boundary
-
-        for k in [1, 3, 5, 7]:
-            assert mesh.boundary[(k,2)] == 'left'
-
-        for k in [24, 26, 28, 30]:
-            assert mesh.boundary[(k,2)] == 'right'
-
-        for k in [7, 15, 23, 31]:
-            assert mesh.boundary[(k,1)] == 'top'
-        for k in [0, 8, 16, 24]:
-            assert mesh.boundary[(k,1)] == 'bottom'
-
-
-
-    def test_rectangular_mesh(self):
-        M=4
-        N=16
-        len1 = 100.0
-        len2 = 17.0
-
-        points, vertices, boundary = rectangular(M, N, len1, len2)
-        mesh = Mesh(points, vertices, boundary)
-
-        assert len(mesh) == 2*M*N
-
-        for i in range(len(mesh)):
-            assert mesh.areas[i] == len1*len2/(2*M*N)
-
-            hypo = sqrt((len1/M)**2 + (len2/N)**2) #hypothenuse
-            assert mesh.edgelengths[i, 0] == hypo
-            assert mesh.edgelengths[i, 1] == len1/M #x direction
-            assert mesh.edgelengths[i, 2] == len2/N #y direction
-
-        #Test that points are arranged in a counter clock wise order
-        mesh.check_integrity()
-
-
-    def test_rectangular_mesh2(self):
-        #Check that integers don't cause trouble
-        N = 16
-
-        points, vertices, boundary = rectangular(2*N, N, len1=10, len2=10)
-        mesh = Mesh(points, vertices, boundary)
-
-
-    def test_surrogate_neighbours(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-        mesh = Mesh(points, vertices)
-        mesh.check_integrity()
-
-
-        T = mesh
-        tid = 0
-        assert T.number_of_boundaries[tid] == 2
-        assert T.surrogate_neighbours[tid, 0] == tid
-        assert T.surrogate_neighbours[tid, 1] == 1
-        assert T.surrogate_neighbours[tid, 2] == tid
-
-        tid = 1
-        assert T.number_of_boundaries[tid] == 0
-        assert T.surrogate_neighbours[tid, 0] == 2
-        assert T.surrogate_neighbours[tid, 1] == 3
-        assert T.surrogate_neighbours[tid, 2] == 0
-
-        tid = 2
-        assert T.number_of_boundaries[tid] == 2
-        assert T.surrogate_neighbours[tid, 0] == tid
-        assert T.surrogate_neighbours[tid, 1] == tid
-        assert T.surrogate_neighbours[tid, 2] == 1
-
-        tid = 3
-        assert T.number_of_boundaries[tid] == 2
-        assert T.surrogate_neighbours[tid, 0] == 1
-        assert T.surrogate_neighbours[tid, 1] == tid
-        assert T.surrogate_neighbours[tid, 2] == tid
-
-
-    def test_boundary_inputs(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        boundary = { (0, 0): 'First',
-                     (0, 2): 'Second',
-                     (2, 0): 'Third',
-                     (2, 1): 'Fourth',
-                     (3, 1): 'Fifth',
-                     (3, 2): 'Sixth'}
-
-
-        mesh = Mesh(points, vertices, boundary)
-        mesh.check_integrity()
-
-
-        #Check enumeration
-        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
-        #    b = -k-1
-        #    assert mesh.neighbours[vol_id, edge_id] == b
-
-
-
-    def test_boundary_inputs_using_one_default(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        boundary = { (0, 0): 'First',
-                     (0, 2): 'Second',
-                     (2, 0): 'Third',
-                     (2, 1): 'Fourth',
-                     #(3, 1): 'Fifth',  #Skip this
-                     (3, 2): 'Sixth'}
-
-
-        mesh = Mesh(points, vertices, boundary)
-        mesh.check_integrity()
-
-        from anuga.config import default_boundary_tag
-        assert mesh.boundary[ (3, 1) ] == default_boundary_tag
-
-
-        #Check enumeration
-        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
-        #    b = -k-1
-        #    assert mesh.neighbours[vol_id, edge_id] == b
-
-    def test_boundary_inputs_using_all_defaults(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        boundary = { (0, 0): 'First',
-                     (0, 2): 'Second',
-                     (2, 0): 'Third',
-                     (2, 1): 'Fourth',
-                     #(3, 1): 'Fifth',  #Skip this
-                     (3, 2): 'Sixth'}
-
-
-        mesh = Mesh(points, vertices) #, boundary)
-        mesh.check_integrity()
-
-        from anuga.config import default_boundary_tag
-        assert mesh.boundary[ (0, 0) ] == default_boundary_tag
-        assert mesh.boundary[ (0, 2) ] == default_boundary_tag
-        assert mesh.boundary[ (2, 0) ] == default_boundary_tag
-        assert mesh.boundary[ (2, 1) ] == default_boundary_tag
-        assert mesh.boundary[ (3, 1) ] == default_boundary_tag
-        assert mesh.boundary[ (3, 2) ] == default_boundary_tag
-
-
-        #Check enumeration
-        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
-        #    b = -k-1
-        #    assert mesh.neighbours[vol_id, edge_id] == b
-
-
-
-
-
-
-    def test_inputs(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        #Too few points
-        try:
-            mesh = Mesh([points[0]], vertices)
-        except AssertionError:
-            pass
-        else:
-            raise Exception('Should have raised an exception')
-
-        #Too few points - 1 element
-        try:
-            mesh = Mesh([points[0]], [vertices[0]])
-        except AssertionError:
-            pass
-        else:
-            raise Exception('Should have raised an exception')
-
-        #Wrong dimension of vertices
-        try:
-            mesh = Mesh(points, vertices[0])
-        except AssertionError:
-            pass
-        else:
-            raise Exception('Should have raised an exception')
-
-        #Unsubscriptable coordinates object raises exception
-        try:
-            mesh = Mesh(points[0], [vertices[0]])
-        except AssertionError:
-            pass
-        else:
-            raise Exception('Should have raised an exception')
-
-        #FIXME: This has been commented out pending a decision
-        #whether to allow partial boundary tags or not
-        #
-        #Not specifying all boundary tags
-        #try:
-        #    mesh = Mesh(points, vertices, {(3,0): 'x'})
-        #except AssertionError:
-        #    pass
-        #else:
-        #    raise Exception('Should have raised an exception')
-
-        #Specifying wrong non existing segment       
-        try:
-            mesh = Mesh(points, vertices, {(5,0): 'x'})
-        except AssertionError:
-            pass
-        except RuntimeError:
-            pass
-        else:
-            raise Exception('Should have raised an exception')
-
-
-
-
-    def test_internal_boundaries(self):
-        """
-        get values based on triangle lists.
-        """
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        # Add an internal boundary
-        boundary[(2,0)] = 'internal'
-        boundary[(1,0)] = 'internal'
-
-        #Create shallow water domain
-        domain = Mesh(points, vertices, boundary)
-        domain.build_tagged_elements_dictionary({'bottom':[0,1],
-                                                 'top':[4,5],
-                                                 'all':[0,1,2,3,4,5]})
-
-
-    def test_boundary_polygon(self):
-        from mesh_factory import rectangular
-        #from mesh import Mesh
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(2, 2)
-        mesh = Mesh(points, vertices, boundary)
-
-
-        P = mesh.get_boundary_polygon()
-
-        assert len(P) == 8
-        assert num.allclose(P, [[0.0, 0.0], [0.5, 0.0], [1.0, 0.0],
-                                [1.0, 0.5], [1.0, 1.0], [0.5, 1.0],
-                                [0.0, 1.0], [0.0, 0.5]])
-        for p in points:
-            #print p, P
-            assert is_inside_polygon(p, P)
-
-
-    def test_boundary_polygon_II(self):
-
-        #Points
-        a = [0.0, 0.0] #0
-        b = [0.0, 0.5] #1
-        c = [0.0, 1.0] #2
-        d = [0.5, 0.0] #3
-        e = [0.5, 0.5] #4
-        f = [1.0, 0.0] #5
-        g = [1.0, 0.5] #6
-        h = [1.0, 1.0] #7
-        i = [1.5, 0.5] #8
-
-        points = [a, b, c, d, e, f, g, h, i]
-
-        #dea, bae, bec, fgd,
-        #edg, ghe, gfi, gih
-        vertices = [ [3,4,0], [1,0,4], [1,4,2], [5,6,3],
-                     [4,3,6], [6,7,4], [6,5,8], [6,8,7]]
-
-        mesh = Mesh(points, vertices)
-
-        mesh.check_integrity()
-
-        P = mesh.get_boundary_polygon()
-
-        assert len(P) == 8
-        assert num.allclose(P, [a, d, f, i, h, e, c, b])
-
-        for p in points:
-            #print p, P
-            assert is_inside_polygon(p, P)
-
-
-    def test_boundary_polygon_III(self):
-        """Same as II but vertices ordered differently
-        """
-
-
-        #Points
-        a = [0.0, 0.0] #0
-        b = [0.0, 0.5] #1
-        c = [0.0, 1.0] #2
-        d = [0.5, 0.0] #3
-        e = [0.5, 0.5] #4
-        f = [1.0, 0.0] #5
-        g = [1.0, 0.5] #6
-        h = [1.0, 1.0] #7
-        i = [1.5, 0.5] #8
-
-        points = [a, b, c, d, e, f, g, h, i]
-
-        #edg, ghe, gfi, gih
-        #dea, bae, bec, fgd,
-        vertices = [[4,3,6], [6,7,4], [6,5,8], [6,8,7],
-                    [3,4,0], [1,0,4], [1,4,2], [5,6,3]]
-
-
-        mesh = Mesh(points, vertices)
-        mesh.check_integrity()
-
-
-        P = mesh.get_boundary_polygon()
-
-        assert len(P) == 8
-        assert num.allclose(P, [a, d, f, i, h, e, c, b])
-
-        for p in points:
-            assert is_inside_polygon(p, P)
-
-	    
-    def test_boundary_polygon_IIIa(self):
-        """test_boundary_polygon_IIIa - Check pathological situation where
-	one triangle has no neighbours. This may be the case if a mesh
-	is partitioned using pymetis.
-        """
-
-
-        #Points
-        a = [0.0, 0.0] #0
-        b = [0.0, 0.5] #1
-        c = [0.0, 1.0] #2
-        d = [0.5, 0.0] #3
-        e = [0.5, 0.5] #4
-        f = [1.0, 0.0] #5
-        g = [1.0, 0.5] #6
-        h = [1.0, 1.0] #7
-       
-	# Add pathological triangle with no neighbours to an otherwise
-	# trivial mesh
-	
-	points = [a, b, c, d, e, f, g, h]
-
-        #cbe, aeb, dea, fed, ghe (pathological triangle)
-        vertices = [[2,1,4], [0,4,1], [3,4,0], [5,4,3],
-     	            [6,7,4]]	
-		    
-        mesh = Mesh(points, vertices)
-        mesh.check_integrity()
-
-        P = mesh.get_boundary_polygon(verbose=False)
-
-        
-        assert len(P) == 9
-	
-	# Note that point e appears twice!
-        assert num.allclose(P, [a, d, f, e, g, h, e, c, b])
-
-        for p in points:
-	    msg = 'Point %s is not inside polygon %s'\
-	    %(p, P)	
-            assert is_inside_polygon(p, P), msg		    
-
-
-				 	
-	    
-	    
-
-    def test_boundary_polygon_IV(self):
-        """Reproduce test test_spatio_temporal_file_function_time
-        from test_util.py that looked as if it produced the wrong boundary
-        """
-
-        from mesh_factory import rectangular        
-
-        #Create a domain to hold test grid
-        #(0:15, -20:10)
-        points, vertices, boundary =\
-                rectangular(4, 4, 15, 30, origin = (0, -20))        
-
-        #####
-        mesh = Mesh(points, vertices)
-        mesh.check_integrity()
-
-        P = mesh.get_boundary_polygon()
-
-        #print P
-        assert len(P) == 16
-        for p in points:
-            assert is_inside_polygon(p, P)
-
-
-
-        #####
-        mesh = Mesh(points, vertices, boundary)
-        mesh.check_integrity()
-
-        P = mesh.get_boundary_polygon()
-
-        
-        #print P, len(P)
-        assert len(P) == 16
-
-        for p in points:
-            assert is_inside_polygon(p, P)
-
-        #print mesh.statistics()    
-
-
-
-    def test_boundary_polygon_V(self):
-        """Create a discontinuous mesh (duplicate vertices)
-        and check that boundary is as expected
-        
-        """
-
-        #Points
-        a = [0.0, 0.0] #0
-        b = [0.0, 0.5] #1
-        c = [0.0, 1.0] #2
-        d = [0.5, 0.0] #3
-        e = [0.5, 0.5] #4
-        f = [1.0, 0.0] #5
-        g = [1.0, 0.5] #6
-        h = [1.0, 1.0] #7
-        i = [1.5, 0.5] #8
-
-        #Duplicate points for triangles edg [4,3,6] (central) and
-        #gid [6,8,7] (top right boundary) to them disconnected
-        #from the others
-
-        e0 = [0.5, 0.5] #9 
-        d0 = [0.5, 0.0] #10
-        g0 = [1.0, 0.5] #11
-        i0 = [1.5, 0.5] #12        
-        
-
-        points = [a, b, c, d, e, f, g, h, i, e0, d0, g0, i0]
-
-
-
-        #dea, bae, bec, fgd,
-        #edg, ghe, gfi, gih
-        #vertices = [ [3,4,0], [1,0,4], [1,4,2], [5,6,3],
-        #             [4,3,6], [6,7,4], [6,5,8], [6,8,7]]
-
-
-        #dea, bae, bec, fgd,
-        #e0d0g0, ghe, gfi, g0i0h
-        vertices = [[3,4,0], [1,0,4], [1,4,2], [5,6,3],
-                    [9,10,11], [6,7,4], [6,5,8], [11,12,7]]        
-
-        mesh = Mesh(points, vertices)
-
-        mesh.check_integrity()
-
-        P = mesh.get_boundary_polygon()
-
-        #print P
-        
-        assert len(P) == 8
-        assert num.allclose(P, [a, d, f, i, h, e, c, b])
-        assert num.allclose(P, [(0.0, 0.0), (0.5, 0.0), (1.0, 0.0), (1.5, 0.5), (1.0, 1.0), (0.5, 0.5), (0.0, 1.0), (0.0, 0.5)])
-        
-
-        for p in points:
-            #print p, P
-            assert is_inside_polygon(p, P)
-
-
-
-    def test_boundary_polygon_VI(self):
-        """test_boundary_polygon_VI(self)
-
-        Create a discontinuous mesh (duplicate vertices) from a real situation that failed
-        and check that boundary is as expected
-        """
-
-        # First do the continuous version of mesh
-
-        points = [[   6626.85400391,      0.        ],
-                  [      0.        ,  38246.4140625 ],
-                  [   9656.2734375 ,  68351.265625  ],
-                  [  20827.25585938,  77818.203125  ],
-                  [  32755.59375   ,  58126.9765625 ],
-                  [  35406.3359375 ,  79332.9140625 ],
-                  [  31998.23828125,  88799.84375   ],
-                  [  23288.65820313, 104704.296875  ],
-                  [  32187.57617188, 109816.4375    ],
-                  [  50364.08984375, 110763.1328125 ],
-                  [  80468.9453125 ,  96184.0546875 ],
-                  [  86149.1015625 , 129886.34375   ],
-                  [ 118715.359375  , 129886.34375   ],
-                  [ 117768.6640625 ,  85770.4296875 ],
-                  [ 101485.5390625 ,  45251.9453125 ],
-                  [  49985.4140625 ,   2272.06396484],
-                  [  51737.94140625,  90559.2109375 ],
-                  [  56659.0703125 ,  65907.6796875 ],
-                  [  75735.4765625 ,  23762.00585938],
-                  [  52341.70703125,  38563.39453125]]
-
-        triangles = [[19, 0,15],
-                     [ 2, 4, 3],
-                     [ 4, 2, 1],
-                     [ 1,19, 4],
-                     [15,18,19],
-                     [18,14,17],
-                     [19, 1, 0],
-                     [ 6, 8, 7],
-                     [ 8, 6,16],
-                     [10, 9,16],
-                     [17, 5, 4],
-                     [16,17,10],
-                     [17,19,18],
-                     [ 5,17,16],
-                     [10,14,13],
-                     [10,17,14],
-                     [ 8,16, 9],
-                     [12,11,10],
-                     [10,13,12],
-                     [19,17, 4],
-                     [16, 6, 5]]
-
-
-        triangles = num.array(triangles,num.int)
-        points = num.array(points,num.float)
-
-        mesh = Mesh(points, triangles)
-        mesh.check_integrity()
-        Pref = mesh.get_boundary_polygon()
-
-        #plot_polygons([ensure_numeric(Pref)], 'goodP')
-
-        for p in points:
-            assert is_inside_polygon(p, Pref)
-        
-        
-        # Then do the discontinuous version
-        import warnings
-        warnings.filterwarnings('ignore')
-
-        
-        points = [[  52341.70703125,  38563.39453125],
-                  [   6626.85400391,      0.        ],
-                  [  49985.4140625 ,   2272.06396484],
-                  [   9656.2734375 ,  68351.265625  ],
-                  [  32755.59375   ,  58126.9765625 ],
-                  [  20827.25585938,  77818.203125  ],
-                  [  32755.59375   ,  58126.9765625 ],
-                  [   9656.2734375 ,  68351.265625  ],
-                  [      0.        ,  38246.4140625 ],
-                  [      0.        ,  38246.4140625 ],
-                  [  52341.70703125,  38563.39453125],
-                  [  32755.59375   ,  58126.9765625 ],
-                  [  49985.4140625 ,   2272.06396484],
-                  [  75735.4765625 ,  23762.00585938],
-                  [  52341.70703125,  38563.39453125],
-                  [  75735.4765625 ,  23762.00585938],
-                  [ 101485.5390625 ,  45251.9453125 ],
-                  [  56659.0703125 ,  65907.6796875 ],
-                  [  52341.70703125,  38563.39453125],
-                  [      0.        ,  38246.4140625 ],
-                  [   6626.85400391,      0.        ],
-                  [  31998.23828125,  88799.84375   ],
-                  [  32187.57617188, 109816.4375    ],
-                  [  23288.65820313, 104704.296875  ],
-                  [  32187.57617188, 109816.4375    ],
-                  [  31998.23828125,  88799.84375   ],
-                  [  51737.94140625,  90559.2109375 ],
-                  [  80468.9453125 ,  96184.0546875 ],
-                  [  50364.08984375, 110763.1328125 ],
-                  [  51737.94140625,  90559.2109375 ],
-                  [  56659.0703125 ,  65907.6796875 ],
-                  [  35406.3359375 ,  79332.9140625 ],
-                  [  32755.59375   ,  58126.9765625 ],
-                  [  51737.94140625,  90559.2109375 ],
-                  [  56659.0703125 ,  65907.6796875 ],
-                  [  80468.9453125 ,  96184.0546875 ],
-                  [  56659.0703125 ,  65907.6796875 ],
-                  [  52341.70703125,  38563.39453125],
-                  [  75735.4765625 ,  23762.00585938],
-                  [  35406.3359375 ,  79332.9140625 ],
-                  [  56659.0703125 ,  65907.6796875 ],
-                  [  51737.94140625,  90559.2109375 ],
-                  [  80468.9453125 ,  96184.0546875 ],
-                  [ 101485.5390625 ,  45251.9453125 ],
-                  [ 117768.6640625 ,  85770.4296875 ],
-                  [  80468.9453125 ,  96184.0546875 ],
-                  [  56659.0703125 ,  65907.6796875 ],
-                  [ 101485.5390625 ,  45251.9453125 ],
-                  [  32187.57617188, 109816.4375    ],
-                  [  51737.94140625,  90559.2109375 ],
-                  [  50364.08984375, 110763.1328125 ],
-                  [ 118715.359375  , 129886.34375   ],
-                  [  86149.1015625 , 129886.34375   ],
-                  [  80468.9453125 ,  96184.0546875 ],
-                  [  80468.9453125 ,  96184.0546875 ],
-                  [ 117768.6640625 ,  85770.4296875 ],
-                  [ 118715.359375  , 129886.34375   ],
-                  [  52341.70703125,  38563.39453125],
-                  [  56659.0703125 ,  65907.6796875 ],
-                  [  32755.59375   ,  58126.9765625 ],
-                  [  51737.94140625,  90559.2109375 ],
-                  [  31998.23828125,  88799.84375   ],
-                  [  35406.3359375 ,  79332.9140625 ]]
-
-        scaled_points = ensure_numeric(points, num.int)/1000  # Simplify for ease of interpretation
-
-        triangles = [[ 0, 1, 2],
-                     [ 3, 4, 5],
-                     [ 6, 7, 8],
-                     [ 9,10,11],
-                     [12,13,14],
-                     [15,16,17],
-                     [18,19,20],
-                     [21,22,23],
-                     [24,25,26],
-                     [27,28,29],
-                     [30,31,32],
-                     [33,34,35],
-                     [36,37,38],
-                     [39,40,41],
-                     [42,43,44],
-                     [45,46,47],
-                     [48,49,50],
-                     [51,52,53],
-                     [54,55,56],
-                     [57,58,59],
-                     [60,61,62]]
-
-
-        # First use scaled points for ease of debugging
-        mesh = Mesh(scaled_points, triangles)
-        mesh.check_integrity()
-        P = mesh.get_boundary_polygon()
-
-        for p in scaled_points:
-            assert is_inside_polygon(p, P)            
-
-        # Then use original points and test        
-        mesh = Mesh(points, triangles)
-        mesh.check_integrity()
-        P = mesh.get_boundary_polygon()
-
-        for p in points:
-            assert is_inside_polygon(p, P)            
-
-        assert num.allclose(P, Pref)    
-
-    def test_lone_vertices(self):
-        a = [2.0, 1.0]
-        b = [6.0, 2.0]
-        c = [1.0, 3.0]
-        d = [2.0, 4.0]
-        e = [4.0, 3.0]
-
-        points = [a, b, d, c, e]
-        vertices = [[0,1,3]]
-
-        mesh = Mesh(points, vertices)
-        mesh.check_integrity()
-        loners = mesh.get_lone_vertices()
-
-        #print loners
-        self.failUnless(loners==[2,4],
-                        'FAILED!')
-
-        
-        a = [2.0, 1.0]
-        b = [6.0, 2.0]
-        c = [1.0, 3.0]
-        d = [2.0, 4.0]
-
-        points = [d, a, b, c]
-        vertices = [[3,1,2]]
-
-        mesh = Mesh(points, vertices)
-        mesh.check_integrity()
-        loners = mesh.get_lone_vertices()
-        self.failUnless(loners==[0],
-                        'FAILED!') 
-
-    def test_mesh_get_boundary_polygon_with_georeferencing(self):
-        """test_mesh_get_boundary_polygon_with_georeferencing
-        
-        Test that get_boundary_polygon returns absolute coordinates
-        """
-        
-        # test
-        a = [0.0, 0.0]
-        b = [4.0, 0.0]
-        c = [0.0, 4.0]
-
-        absolute_points = [a, b, c]
-        vertices = [[0, 1, 2]]
-        
-        geo = Geo_reference(56, 67, -56)
-
-        relative_points = geo.change_points_geo_ref(absolute_points)
-
-        mesh = Mesh(relative_points, vertices, geo_reference=geo)
-        boundary_polygon = mesh.get_boundary_polygon()
-
-        assert num.allclose(absolute_points, boundary_polygon)
-
-    def test_get_triangle_containing_point(self):
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-        mesh = Mesh(points, vertices)
-        
-        mesh.check_integrity()
-
-
-        try:
-            id = mesh.get_triangle_containing_point([3.0, 5.0])
-        except:
-            pass
-        else:
-            msg = 'Should have caught point outside polygon (Non)'            
-            raise Exception(msg)
-            
-        id = mesh.get_triangle_containing_point([0.5, 1.0])
-        assert id == 0
-
-        id = mesh.get_triangle_containing_point([1.0, 3.0])
-        assert id == 3        
-
-        for i, point in enumerate(mesh.get_centroid_coordinates()):
-            id = mesh.get_triangle_containing_point(point)
-            assert id == i        
-
-    def test_get_triangle_neighbours(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        e = [2.0, 2.0]
-        points = [a, b, c, e]
-        vertices = [ [1,0,2], [1,2,3] ]   #bac, bce
-        mesh = Mesh(points, vertices)
-
-        neighbours = mesh.get_triangle_neighbours(0)
-        assert num.allclose(neighbours, [-1,1,-2])
-        neighbours = mesh.get_triangle_neighbours(-10)
-        assert neighbours == []
-        neighbours = mesh.get_triangle_neighbours(2)
-        assert neighbours == []
-
-
-    def test_get_intersecting_segments1(self):
-        """test_get_intersecting_segments(self):
-
-        Very simple test (horizontal lines)
-        """
-
-        # Build test mesh
-        
-        # Create basic mesh
-        # 9 points at (0,0), (0, 1), ..., (2,2)
-        # 8 triangles enumerated from left bottom to right top.
-        points, vertices, boundary = rectangular(2, 2, 2, 2)
-        mesh = Mesh(points, vertices, boundary)
-
-        # Very simple horizontal line intersecting
-        #
-
-
-        for y_line in [0.1, 0.2, 0.314159, 0.41, 0.6, 0.99, 1.01, 1.5, 1.77, 1.9]:
-            if y_line < 1:
-                ceiling = 1
-                floor = 0
-                intersected_triangles = [0,1,4,5]
-            elif y_line > 1:
-                ceiling = 2
-                floor = 1
-                intersected_triangles = [2,3,6,7]
-            else:
-                raise Exception('this test is not for parallel lines')
-
-
-            line = [[-1,y_line], [3,y_line]]
-
-            L = mesh.get_intersecting_segments(line)
-            assert len(L) == 4
-
-            
-
-            # Check all normals point straight down etc
-            total_length = 0
-            for x in L:
-                if x.triangle_id % 2 == 0:
-                    assert num.allclose(x.length, ceiling-y_line)
-                else:
-                    assert num.allclose(x.length, y_line-floor)                
-
-                
-                assert num.allclose(x.normal, [0,-1])
-
-                assert num.allclose(x.segment[1][0], x.segment[0][0] + x.length)
-                assert num.allclose(x.segment[0][1], y_line)
-                assert num.allclose(x.segment[1][1], y_line)                
-
-                assert x.triangle_id in intersected_triangles
-
-                total_length += x.length
-
-            msg = 'Segments do not add up'
-            assert num.allclose(total_length, 2), msg
-            
-
-    def test_get_intersecting_segments_coinciding(self):
-        """test_get_intersecting_segments_coinciding(self):
-
-        Test that lines coinciding with triangle edges work.
-        """
-
-        # Build test mesh
-        
-        # Create basic mesh
-        # 9 points at (0,0), (0, 1), ..., (2,2)
-        # 8 triangles enumerated from left bottom to right top.
-        points, vertices, boundary = rectangular(2, 2, 2, 2)
-        mesh = Mesh(points, vertices, boundary)
-        intersected_triangles = [1,5]
-
-        # Very simple horizontal line intersecting
-        #
-
-        y_line = 1.0
-        
-        line = [[-1,y_line], [3,y_line]]
-
-        L = mesh.get_intersecting_segments(line)
-
-
-        msg = 'Only two triangles should be returned'    
-        assert len(L) == 2, msg    
-            
-
-        # Check all 
-        total_length = 0
-        for x in L:
-            assert num.allclose(x.length, 1.0)
-            assert num.allclose(x.normal, [0,-1])
-
-            assert num.allclose(x.segment[1][0], x.segment[0][0] + x.length)
-            assert num.allclose(x.segment[0][1], y_line)
-            assert num.allclose(x.segment[1][1], y_line)                            
-
-
-
-            assert x.triangle_id in intersected_triangles
-
-            total_length += x.length
-
-        msg = 'Segments do not add up'
-        assert num.allclose(total_length, 2), msg
-        
-
-    def test_get_intersecting_segments_partially_coinciding(self):
-        """test_get_intersecting_segments_partially_coinciding(self):
-
-        Test that line coinciding with triangle edges work.
-        But this ones only coincide with parts of the edge. 
-        """
-
-        # Build test mesh
-        
-        # Create basic mesh
-        # 9 points at (0,0), (0, 1), ..., (2,2)
-        # 8 triangles enumerated from left bottom to right top.
-        points, vertices, boundary = rectangular(2, 2, 2, 2)
-        mesh = Mesh(points, vertices, boundary)
-        intersected_triangles = [1,5]
-
-        # Horizontal line intersecting along center but stopping
-        # parway through second triangle's edge
-        #
-
-        y_line = 1.0
-        
-        #line = [[0, y_line], [2, y_line]]
-        line = [[0, y_line], [1.5, y_line]]
-
-        L = mesh.get_intersecting_segments(line)
-        #for x in L:
-        #    print x
-
-        msg = 'Two triangles should be returned'    
-        assert len(L) == 2, msg    
-            
-
-        # Check all 
-        total_length = 0
-        for x in L:
-            if x.triangle_id == 1:
-                assert num.allclose(x.length, 1)        
-                assert num.allclose(x.normal, [0, -1])
-                
-            if x.triangle_id == 5:
-                assert num.allclose(x.length, 0.5)
-                assert num.allclose(x.normal, [0, -1])
-
-
-            assert x.triangle_id in intersected_triangles
-
-            total_length += x.length
-
-        msg = 'Segments do not add up'
-        assert num.allclose(total_length, 1.5), msg            
-
-
-
-    def test_get_intersecting_segments2(self):
-        """test_get_intersecting_segments(self):
-
-        Lines with a slope
-        """
-
-        s2 = sqrt(2.0)/2
-        
-
-        # Build test mesh
-        
-        # Create basic mesh
-        # 9 points at (0,0), (0, 1), ..., (2,2)
-        # 8 triangles enumerated from left bottom to right top.
-        points, vertices, boundary = rectangular(2, 2, 2, 2)
-        mesh = Mesh(points, vertices, boundary)
-        
-
-        # Diagonal cutting through a vertex and hypothenuses
-        line = [[0, 2], [2, 0]]
-        intersected_triangles = [3,2,5,4]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 4
-
-        #print L
-        
-        # Check all segments
-        total_length = 0
-        for i, x in enumerate(L): 
-            assert num.allclose(x.length, s2)
-            assert num.allclose(x.normal, [-s2, -s2])
-            assert num.allclose(sum(x.normal**2), 1)
-            
-            assert x.triangle_id in intersected_triangles
-
-            total_length += x.length
-
-        msg = 'Segments do not add up'
-        assert num.allclose(total_length, 4*s2), msg
-
-
-        # Diagonal cutting through a vertex and hypothenuses (reversed)
-        line = [[2, 0], [0, 2]]
-        intersected_triangles = [3,2,5,4]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 4
-
-        #print L
-        
-        # Check all segments
-        total_length = 0
-        for i, x in enumerate(L): 
-            assert num.allclose(x.length, s2)
-            assert num.allclose(x.normal, [s2, s2])
-            assert num.allclose(sum(x.normal**2), 1)
-            
-            assert x.triangle_id in intersected_triangles
-
-            total_length += x.length
-
-        msg = 'Segments do not add up'
-        assert num.allclose(total_length, 4*s2), msg                    
-
-
-
-        # Diagonal coinciding with hypothenuses
-        line = [[2, 2], [0, 0]]
-        intersected_triangles = [6,0]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 2
-
-        #print L
-        
-        # Check all segments
-        total_length = 0
-        for i, x in enumerate(L): 
-            assert num.allclose(x.length, 2*s2)
-            assert num.allclose(x.normal, [-s2, s2])
-            assert num.allclose(sum(x.normal**2), 1)
-            
-            assert x.triangle_id in intersected_triangles
-
-            total_length += x.length
-
-        msg = 'Segments do not add up'
-        assert num.allclose(total_length, 4*s2), msg                        
-
-
-        # Diagonal coinciding with hypothenuses (reversed)
-        line = [[0, 0], [2, 2]]
-        intersected_triangles = [6,0]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 2
-
-        #print L
-        
-        # Check all segments
-        total_length = 0
-        for i, x in enumerate(L): 
-            assert num.allclose(x.length, 2*s2)
-            assert num.allclose(x.normal, [s2, -s2])
-            assert num.allclose(sum(x.normal**2), 1)
-            
-            assert x.triangle_id in intersected_triangles
-
-            total_length += x.length
-
-        msg = 'Segments do not add up'
-        assert num.allclose(total_length, 4*s2), msg                        
-
-
-
-        # line with slope [1, -1] cutting through vertices of tri 7 and 6
-        line = [[1, 2], [2, 1]]
-        intersected_triangles = [7,6]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 2
-
-        #print L
-        
-        # Check all segments
-        total_length = 0
-        for i, x in enumerate(L): 
-            assert num.allclose(x.length, s2)
-            assert num.allclose(x.normal, [-s2, -s2])
-            assert num.allclose(sum(x.normal**2), 1)
-            
-            assert x.triangle_id in intersected_triangles
-
-            total_length += x.length
-
-        msg = 'Segments do not add up'
-        assert num.allclose(total_length, 2*s2), msg
-
-
-        # Arbitrary line with slope [1, -1] cutting through tri 7 and 6
-        line = [[1.1, 2], [2.1, 1]]
-        intersected_triangles = [7,6]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 2
-        
-        # Check all segments
-        total_length = 0
-        for i, x in enumerate(L): 
-            assert num.allclose(x.normal, [-s2, -s2])
-            assert num.allclose(sum(x.normal**2), 1)
-
-            msg = 'Triangle %d' %x.triangle_id + ' is not in %s' %(intersected_triangles)
-            assert x.triangle_id in intersected_triangles, msg
-            
-
-
-    def test_get_intersecting_segments3(self):
-        """test_get_intersecting_segments(self):
-
-        Check that line can stop inside a triangle
-        
-        """
-
-
-
-        s2 = sqrt(2.0)/2
-        
-
-        # Build test mesh
-        
-        # Create basic mesh
-        # 9 points at (0,0), (0, 1), ..., (2,2)
-        # 8 triangles enumerated from left bottom to right top.
-        points, vertices, boundary = rectangular(2, 2, 2, 2)
-        mesh = Mesh(points, vertices, boundary)
-        
-
-        # Line cutting through one triangle and ending on its edge
-        line = [[0.5, 3], [0.5, 1.5]]
-        intersected_triangles = [3]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 1
-        assert L[0].triangle_id == 3
-        assert num.allclose(L[0].length, 0.5)        
-        assert num.allclose(L[0].normal, [-1,0])                
-
-
-
-        # Now try to shorten it so that its endpoint falls short of the far edge
-        line = [[0.5, 3], [0.5, 1.6]]
-        intersected_triangles = [3]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 1
-        assert L[0].triangle_id == 3
-        assert num.allclose(L[0].length, 0.4)
-        assert num.allclose(L[0].normal, [-1,0])
-
-        intersected_triangles = [3]
-
-        # Now the same, but with direction changed
-        line = [[0.5, 3], [0.5, 1.6]]
-        line = [[0.5, 1.6], [0.5, 3]]        
-        intersected_triangles = [3]                
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 1
-        assert L[0].triangle_id == 3
-        assert num.allclose(L[0].length, 0.4)
-        assert num.allclose(L[0].normal, [1,0])                
-        
-
-            
-
-    def test_get_intersecting_segments4(self):
-        """test_get_intersecting_segments(self):
-
-        Simple poly line
-        
-        """
-
-
-
-        s2 = sqrt(2.0)/2
-        
-
-        # Build test mesh
-        
-        # Create basic mesh
-        # 9 points at (0,0), (0, 1), ..., (2,2)
-        # 8 triangles enumerated from left bottom to right top.
-        points, vertices, boundary = rectangular(2, 2, 2, 2)
-        mesh = Mesh(points, vertices, boundary)
-        
-
-        # Polyline with three segments cutting through mesh
-        line = [[0.5, 3], [0.5, 1.5], [1,1]]
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 2
-
-        for x in L:
-            if x.triangle_id == 3:
-                assert num.allclose(x.length, 0.5)        
-                assert num.allclose(x.normal, [-1,0])
-                
-            if x.triangle_id == 2:
-                assert num.allclose(x.length, s2)
-                assert num.allclose(x.normal, [-s2,-s2])
-
-
-
-    def test_get_intersecting_segments5(self):
-        """test_get_intersecting_segments(self):
-
-        More complex poly line
-        
-        """
-
-
-
-        s2 = sqrt(2.0)/2
-        
-
-        # Build test mesh
-        
-        # Create basic mesh
-        # 9 points at (0,0), (0, 1), ..., (2,2)
-        # 8 triangles enumerated from left bottom to right top.
-        points, vertices, boundary = rectangular(2, 2, 2, 2)
-        mesh = Mesh(points, vertices, boundary)
-        
-
-        # Polyline with three segments cutting through mesh
-        line = [[0.5, 3], [0.5, 1.5], [1.25, 0.75]] 
-
-        L = mesh.get_intersecting_segments(line)
-        assert len(L) == 3
-
-        for x in L:
-            if x.triangle_id == 3:
-                assert num.allclose(x.length, 0.5)        
-                assert num.allclose(x.normal, [-1,0])
-                
-            if x.triangle_id == 2:
-                msg = str(x.length)
-                assert num.allclose(x.length, s2), msg
-                assert num.allclose(x.normal, [-s2,-s2])
-
-            if x.triangle_id == 5:
-                segvec = num.array([line[2][0]-1,
-                                    line[2][1]-1])
-                msg = str(x.length)
-                assert num.allclose(x.length, sqrt(sum(segvec**2))), msg
-                assert num.allclose(x.normal, [-s2,-s2])                                                
-
-
-    def test_get_intersecting_segments6(self):
-        """test_get_intersecting_segments(self):
-
-        Even more complex poly line, where line breaks within triangle 5
-
-        5 segments are returned even though only four triangles [3,2,5,6] are touched.
-        Triangle 5 therefor has two segments in it.
-        
-        """
-
-
-
-        s2 = sqrt(2.0)/2
-        
-
-        # Build test mesh
-        
-        # Create basic mesh
-        # 9 points at (0,0), (0, 1), ..., (2,2)
-        # 8 triangles enumerated from left bottom to right top.
-        points, vertices, boundary = rectangular(2, 2, 2, 2)
-        mesh = Mesh(points, vertices, boundary)
-        
-
-        # Polyline with three segments cutting through mesh
-        line = [[0.5, 3], [0.5, 1.5], [1.25, 0.75], [2.25, 1.75]]
-
-        L = mesh.get_intersecting_segments(line)
-        #for x in L:
-        #    print x
-
-        assert len(L) == 5
-
-        for x in L:
-            if x.triangle_id == 3:
-                assert num.allclose(x.length, 0.5)        
-                assert num.allclose(x.normal, [-1,0])
-                
-            if x.triangle_id == 2:
-                msg = str(x.length)
-                assert num.allclose(x.length, s2), msg
-                assert num.allclose(x.normal, [-s2,-s2])
-
-            if x.triangle_id == 5:
-                if x.segment == ((1.0, 1.0), (1.25, 0.75)):                    
-                    segvec = num.array([line[2][0]-1,
-                                        line[2][1]-1])
-                    msg = str(x.length)
-                    assert num.allclose(x.length, sqrt(sum(segvec**2))), msg
-                    assert num.allclose(x.normal, [-s2,-s2])
-                elif x.segment == ((1.25, 0.75), (1.5, 1.0)):
-                    segvec = num.array([1.5-line[2][0],
-                                        1.0-line[2][1]])
-                    
-                    assert num.allclose(x.length, sqrt(sum(segvec**2))), msg
-                    assert num.allclose(x.normal, [s2,-s2])
-                else:
-                    msg = 'Unknown segment: %s' %x.segment
-                    raise Exception(msg)
-                
-
-                    
-            if x.triangle_id == 6:
-                assert num.allclose(x.normal, [s2,-s2])
-                assert num.allclose(x.segment, ((1.5, 1.0), (2, 1.5)))
-
-
-      # Internal test that sum of line segments add up
-      # to length of input line
-      #
-      # Could be useful perhaps
-      #
-      #xi1 = line[1][0]
-      #eta1 = line[1][1]
-      #linevector = num.array([xi1-xi0, eta1-eta0])
-      #linelength = sqrt(sum(linevector**2))
-      #
-      #segmentlength = 0
-      #for segment in triangle_intersections:
-      #    vector = array([segment[1][0] - segment[0][0],
-      #                    segment[1][1] - segment[0][1]])
-      #    length = sqrt(sum(vector**2))      
-      #    segmentlength += length
-      #
-      #msg = 'Sum of intersecting segments do not add up'    
-      #assert allclose(segmentlength, linelength), msg    
-
-
-
-
-    def test_get_intersecting_segments7(self):
-        """test_get_intersecting_segments(self):
-
-        Check that line can stop inside a triangle - this is from
-        flow throug a cross sections example in test_datamanager.
-        
-        """
-
-        # Build test mesh
-        width = 5
-        length = 100
-        t_end = 1
-        points, vertices, boundary = rectangular(length, width,
-                                                 length, width)
-
-        mesh = Mesh(points, vertices, boundary)
-        
-
-        # A range of partial lines
-        x = length/2.
-        for i in range(10):
-            start_point = [length/2., i*width/10.]
-            #print 
-            #print start_point
-                            
-            line = [start_point, [length/2., width]]
- 
-            L = mesh.get_intersecting_segments(line)
-
-            if start_point[1] < 1:
-                assert len(L) == 5
-                
-            
-            total_length = 0    
-            for x in L:
-                total_length += x.length
-                
-
-            ref_length = line[1][1] - line[0][1]
-            #print ref_length, total_length
-            assert num.allclose(total_length, ref_length)
-
-
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_Mesh, 'test_mesh_and_neighbours')
-    runner = unittest.TextTestRunner()#verbosity=2)
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_pmesh2domain.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_pmesh2domain.py	(revision 9459)
+++ 	(revision )
@@ -1,260 +1,0 @@
-#!/usr/bin/env python
-#
-
-import unittest
-
-from pmesh2domain import *
-
-from anuga.shallow_water.shallow_water_domain import Domain
-from anuga.abstract_2d_finite_volumes.generic_boundary_conditions \
-                        import Dirichlet_boundary
-
-from anuga.coordinate_transforms.geo_reference import Geo_reference
-from anuga.pmesh.mesh import importMeshFromFile
-
-import numpy as num
-
-
-class Test_pmesh2domain(unittest.TestCase):
-
-    def setUp(self):
-        pass
-
-    def tearDown(self):
-        pass
-
-    def test_pmesh2Domain(self):
-         import os
-         import tempfile
-
-         fileName = tempfile.mktemp(".tsh")
-         file = open(fileName,"w")
-         file.write("4 3 # <vertex #> <x> <y> [attributes]\n \
-0 0.0 0.0 0.0 0.0 0.01 \n \
-1 1.0 0.0 10.0 10.0 0.02  \n \
-2 0.0 1.0 0.0 10.0 0.03  \n \
-3 0.5 0.25 8.0 12.0 0.04  \n \
-# Vert att title  \n \
-elevation  \n \
-stage  \n \
-friction  \n \
-2 # <triangle #> [<vertex #>] [<neigbouring triangle #>]  \n\
-0 0 3 2 -1  -1  1 dsg\n\
-1 0 1 3 -1  0 -1   ole nielsen\n\
-4 # <segment #> <vertex #>  <vertex #> [boundary tag] \n\
-0 1 0 2 \n\
-1 0 2 3 \n\
-2 2 3 \n\
-3 3 1 1 \n\
-3 0 # <x> <y> [attributes] ...Mesh Vertices... \n \
-0 216.0 -86.0 \n \
-1 160.0 -167.0 \n \
-2 114.0 -91.0 \n \
-3 # <vertex #>  <vertex #> [boundary tag] ...Mesh Segments... \n \
-0 0 1 0 \n \
-1 1 2 0 \n \
-2 2 0 0 \n \
-0 # <x> <y> ...Mesh Holes... \n \
-0 # <x> <y> <attribute>...Mesh Regions... \n \
-0 # <x> <y> <attribute>...Mesh Regions, area... \n\
-#Geo reference \n \
-56 \n \
-140 \n \
-120 \n")
-         file.close()
-
-         tags = {}
-         b1 =  Dirichlet_boundary(dirichlet_values = num.array([0.0]))
-         b2 =  Dirichlet_boundary(dirichlet_values = num.array([1.0]))
-         b3 =  Dirichlet_boundary(dirichlet_values = num.array([2.0]))
-         tags["1"] = b1
-         tags["2"] = b2
-         tags["3"] = b3
-
-         domain = pmesh_to_domain_instance(fileName, Domain)
-         os.remove(fileName)
-         #print "domain.tagged_elements", domain.tagged_elements
-         ## check the quantities
-         #print domain.quantities['elevation'].vertex_values
-         answer = [[0., 8., 0.],
-                   [0., 10., 8.]]
-         assert num.allclose(domain.quantities['elevation'].vertex_values,
-                             answer)
-
-         #print domain.quantities['stage'].vertex_values
-         answer = [[0., 12., 10.],
-                   [0., 10., 12.]]
-         assert num.allclose(domain.quantities['stage'].vertex_values,
-                             answer)
-
-         #print domain.quantities['friction'].vertex_values
-         answer = [[0.01, 0.04, 0.03],
-                   [0.01, 0.02, 0.04]]
-         assert num.allclose(domain.quantities['friction'].vertex_values,
-                             answer)
-
-         #print domain.quantities['friction'].vertex_values
-         tagged_elements = domain.get_tagged_elements()
-         assert num.allclose(tagged_elements['dsg'][0],0)
-         assert num.allclose(tagged_elements['ole nielsen'][0],1)
-
-         self.failUnless( domain.boundary[(1, 0)]  == '1',
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-         self.failUnless( domain.boundary[(1, 2)]  == '2',
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-         self.failUnless( domain.boundary[(0, 1)]  == '3',
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-         self.failUnless( domain.boundary[(0, 0)]  == 'exterior',
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-         #print "domain.boundary",domain.boundary
-         self.failUnless( len(domain.boundary)  == 4,
-                          "test_pmesh2Domain Too many boundaries")
-         #FIXME change to use get_xllcorner
-         #print "d.geo_reference.xllcorner",domain.geo_reference.xllcorner 
-         self.failUnless(domain.geo_reference.xllcorner  == 140.0,
-                          "bad geo_referece")
-    #************
-    
-    def test_pmesh2Domain_instance(self):
-         import os
-         import tempfile
-
-         fileName = tempfile.mktemp(".tsh")
-         file = open(fileName,"w")
-         file.write("4 3 # <vertex #> <x> <y> [attributes]\n \
-0 0.0 0.0 0.0 0.0 0.01 \n \
-1 1.0 0.0 10.0 10.0 0.02  \n \
-2 0.0 1.0 0.0 10.0 0.03  \n \
-3 0.5 0.25 8.0 12.0 0.04  \n \
-# Vert att title  \n \
-elevation  \n \
-stage  \n \
-friction  \n \
-2 # <triangle #> [<vertex #>] [<neigbouring triangle #>]  \n\
-0 0 3 2 -1  -1  1 dsg\n\
-1 0 1 3 -1  0 -1   ole nielsen\n\
-4 # <segment #> <vertex #>  <vertex #> [boundary tag] \n\
-0 1 0 2 \n\
-1 0 2 3 \n\
-2 2 3 \n\
-3 3 1 1 \n\
-3 0 # <x> <y> [attributes] ...Mesh Vertices... \n \
-0 216.0 -86.0 \n \
-1 160.0 -167.0 \n \
-2 114.0 -91.0 \n \
-3 # <vertex #>  <vertex #> [boundary tag] ...Mesh Segments... \n \
-0 0 1 0 \n \
-1 1 2 0 \n \
-2 2 0 0 \n \
-0 # <x> <y> ...Mesh Holes... \n \
-0 # <x> <y> <attribute>...Mesh Regions... \n \
-0 # <x> <y> <attribute>...Mesh Regions, area... \n\
-#Geo reference \n \
-56 \n \
-140 \n \
-120 \n")
-         file.close()
-
-         mesh_instance = importMeshFromFile(fileName)
-        
-         tags = {}
-         b1 =  Dirichlet_boundary(dirichlet_values = num.array([0.0]))
-         b2 =  Dirichlet_boundary(dirichlet_values = num.array([1.0]))
-         b3 =  Dirichlet_boundary(dirichlet_values = num.array([2.0]))
-         tags["1"] = b1
-         tags["2"] = b2
-         tags["3"] = b3
-
-         domain = pmesh_to_domain_instance(mesh_instance, Domain)
-
-         os.remove(fileName)
-         #print "domain.tagged_elements", domain.tagged_elements
-         ## check the quantities
-         #print domain.quantities['elevation'].vertex_values
-         answer = [[0., 8., 0.],
-                   [0., 10., 8.]]
-         assert num.allclose(domain.quantities['elevation'].vertex_values,
-                             answer)
-
-         #print domain.quantities['stage'].vertex_values
-         answer = [[0., 12., 10.],
-                   [0., 10., 12.]]
-         assert num.allclose(domain.quantities['stage'].vertex_values,
-                             answer)
-
-         #print domain.quantities['friction'].vertex_values
-         answer = [[0.01, 0.04, 0.03],
-                   [0.01, 0.02, 0.04]]
-         assert num.allclose(domain.quantities['friction'].vertex_values,
-                             answer)
-
-         #print domain.quantities['friction'].vertex_values
-         tagged_elements = domain.get_tagged_elements()         
-         assert num.allclose(tagged_elements['dsg'][0],0)
-         assert num.allclose(tagged_elements['ole nielsen'][0],1)
-
-         self.failUnless( domain.boundary[(1, 0)]  == '1',
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-         self.failUnless( domain.boundary[(1, 2)]  == '2',
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-         self.failUnless( domain.boundary[(0, 1)]  == '3',
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-         self.failUnless( domain.boundary[(0, 0)]  == 'exterior',
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-         #print "domain.boundary",domain.boundary
-         self.failUnless( len(domain.boundary)  == 4,
-                          "test_pmesh2Domain Too many boundaries")
-         #FIXME change to use get_xllcorner
-         #print "d.geo_reference.xllcorner",domain.geo_reference.xllcorner 
-         self.failUnless(domain.geo_reference.xllcorner  == 140.0,
-                          "bad geo_referece")
-         
-    #***********
-    def old_test_tags_to_boundaries (self):
-         meshDict = {}
-         p0 = [0.0, 0.0]
-         p1 = [1.0, 0.0]
-         p2 = [0.0, 1.0]
-         p3 = [0.646446609407, 0.353553390593]
-         meshDict['vertices'] = [p0,p1,p2,p3]
-         meshDict['vertex_attributes'] = [[0.0, 0.0,7.0],[10.0, 0.0,7.0],[0.0, 10.0,7.0],[6.46446609407, 3.53553390593,7.0]]
-         meshDict['triangles'] = [[0,3,2],[0,1,3]]
-         meshDict['triangle_tags'] = [6.6,6.6]
-         meshDict['triangle_neighbors'] = [[-1,-1,1],[-1,0,-1]]
-         meshDict['segments'] = [[1,0],[0,2],[2,3],[3,1]]
-         meshDict['segment_tags'] = [2,3,1,1]
-
-         domain = Domain.pmesh_dictionary_to_domain(meshDict)
-
-         #domain.set_tag_dict(tag_dict)
-         #Boundary tests
-         b1 =  Dirichlet_boundary(conserved_quantities = num.array([0.0]))
-         b2 =  Dirichlet_boundary(conserved_quantities = num.array([1.0]))
-         b3 =  Dirichlet_boundary(conserved_quantities = num.array([1.0]))
-         #test adding a boundary
-         tags = {}
-         tags[1] = b1
-         tags[2] = b2
-         tags[3] = b3
-         domain.set_boundary(tags)
-         inverted_id = Volume.instances[0].neighbours[0]
-         id = -(inverted_id+1)
-         boundary_value = Boundary_value.instances[id]
-         boundary_obj = boundary_value.boundary_object
-
-         self.failUnless( boundary_obj  == b1,
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-
-         inverted_id = Volume.instances[0].neighbours[1]
-         id = -(inverted_id+1)
-         boundary_value = Boundary_value.instances[id]
-         boundary_obj = boundary_value.boundary_object
-         self.failUnless( boundary_obj  == b3,
-                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
-
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_pmesh2domain, 'test')
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_quantity.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_quantity.py	(revision 9459)
+++ 	(revision )
@@ -1,2859 +1,0 @@
-#!/usr/bin/env python
-
-import unittest
-from math import sqrt, pi
-import tempfile
-
-from quantity import *
-from anuga.config import epsilon
-
-from anuga.fit_interpolate.fit import fit_to_mesh
-#from anuga.pyvolution.least_squares import fit_to_mesh         
-from anuga.abstract_2d_finite_volumes.generic_domain \
-                import Generic_Domain
-from anuga.geospatial_data.geospatial_data import Geospatial_data
-from anuga.coordinate_transforms.geo_reference import Geo_reference
-from anuga.geometry.polygon import *
-
-import numpy as num
-
-
-#Aux for fit_interpolate.fit example
-def linear_function(point):
-    point = num.array(point)
-    return point[:,0]+3*point[:,1]
-    #return point[:,1]
-
-
-def axes2points(x, y):
-    """Generate all combinations of grid point coordinates from x and y axes
-
-    Args:
-        * x: x coordinates (array)
-        * y: y coordinates (array)
-
-    Returns:
-        * P: Nx2 array consisting of coordinates for all
-             grid points defined by x and y axes. The x coordinate
-             will vary the fastest to match the way 2D numpy
-             arrays are laid out by default ('C' order). That way,
-             the x and y coordinates will match a corresponding
-             2D array A when flattened (A.flat[:] or A.reshape(-1))
-
-    Note:
-        Example
-
-        x = [1, 2, 3]
-        y = [10, 20]
-
-        P = [[1, 10],
-             [2, 10],
-             [3, 10],
-             [1, 20],
-             [2, 20],
-             [3, 20]]
-    """
-    import numpy 
-    
-    # Reverse y coordinates to have them start at bottom of array
-    y = numpy.flipud(y)
-
-    # Repeat x coordinates for each y (fastest varying)
-    X = numpy.kron(numpy.ones(len(y)), x)
-
-    # Repeat y coordinates for each x (slowest varying)
-    Y = numpy.kron(y, numpy.ones(len(x)))
-
-    # Check
-    N = len(X)
-    assert len(Y) == N
-
-    # Create Nx2 array of x and y coordinates
-    X = numpy.reshape(X, (N, 1))
-    Y = numpy.reshape(Y, (N, 1))
-    P = numpy.concatenate((X, Y), axis=1)
-
-    # Return
-    return P
-
-
-
-class Test_Quantity(unittest.TestCase):
-    def setUp(self):
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        self.mesh1 = Generic_Domain(points[:3], [elements[0]])
-        self.mesh1.check_integrity()
-        
-        #print self.mesh1.__class__
-        #print isinstance(self.mesh1, Domain)
-
-        self.mesh4 = Generic_Domain(points, elements)
-        self.mesh4.check_integrity()
-
-        # UTM round Onslow
-        a = [240000, 7620000]
-        b = [240000, 7680000]
-        c = [300000, 7620000]
-
-        points = [a, b, c]
-        elements = [[0,2,1]]
-        
-        self.mesh_onslow = Generic_Domain(points, elements)
-        self.mesh_onslow.check_integrity()
-        
-    def tearDown(self):
-        pass
-        #print "  Tearing down"
-
-
-    def test_creation(self):
-
-        quantity = Quantity(self.mesh1, [[1,2,3]])
-        assert num.allclose(quantity.vertex_values, [[1.,2.,3.]])
-
-        try:
-            quantity = Quantity()
-        except:
-            pass
-        else:
-            raise Exception('Should have raised empty quantity exception')
-
-
-        # FIXME(Ole): Temporarily disabled 18 Jan 2009
-        #try:
-        #    quantity = Quantity([1,2,3])
-        #except AssertionError:
-        #    pass
-        #except:
-        #    raise Exception('Should have raised "mising mesh object" error')
-
-
-    def test_creation_zeros(self):
-
-        quantity = Quantity(self.mesh1)
-        assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
-
-
-        quantity = Quantity(self.mesh4)
-        assert num.allclose(quantity.vertex_values, [[0.,0.,0.], [0.,0.,0.],
-                                                     [0.,0.,0.], [0.,0.,0.]])
-
-    def test_set_boundary_values(self):
-
-        quantity = Quantity(self.mesh1)
-
-        quantity.set_boundary_values()
-
-        assert  num.allclose(quantity.boundary_values, [0.0, 0.0, 0.0])
-
-
-    def test_set_boundary_values_with_function(self):
-
-        quantity = Quantity(self.mesh1)
-        #assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
-
-        def simple(x,y):
-            return x+3*y
-
-        quantity.set_boundary_values(simple)
-
-        assert  num.allclose(quantity.boundary_values, [1.0, 4.0, 3.0])
-
-    def test_set_boundary_values_with_constant(self):
-
-        quantity = Quantity(self.mesh1)
-        #assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
-
-        quantity.set_boundary_values(10.0)
-
-        assert  num.allclose(quantity.boundary_values, [10.0, 10.0, 10.0])
-
-
-    def test_set_boundary_values_with_array(self):
-
-        quantity = Quantity(self.mesh1)
-        #assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
-
-
-        quantity.set_boundary_values([10.0, 4.0, 5.0])
-
-        assert  num.allclose(quantity.boundary_values, [10.0, 4.0, 5.0])
-
-    def test_set_boundary_values_with_wrong_sized_array(self):
-
-        quantity = Quantity(self.mesh1)
-        #assert num.allclose(quantity.vertex_values, [[0.,0.,0.]])
-
-        try:
-            quantity.set_boundary_values([10.0, 4.0, 5.0, 8.0])
-        except:
-            pass
-        else:
-            msg = 'Should have caught this'
-            raise Exception(msg)
-
-    def test_set_boundary_values_from_edges(self):
-
-        quantity = Quantity(self.mesh4)
-
-        def simple(x,y):
-            return x+3*y
-
-        quantity.set_values(simple)
-
-        assert  num.allclose(quantity.boundary_values, [  0.,   0.,   0.,   0.,  0.,   0.])
-
-        quantity.set_boundary_values_from_edges()
-
-        assert  num.allclose(quantity.boundary_values, [  1.,   3.,   3.,   6.,  10.,   9.])
-
-        
-    def test_interpolation(self):
-        quantity = Quantity(self.mesh1, [[1,2,3]])
-        assert num.allclose(quantity.centroid_values, [2.0]) #Centroid
-
-        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5]])
-
-
-    def test_interpolation2(self):
-        quantity = Quantity(self.mesh4,
-                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
-
-
-        quantity.extrapolate_second_order()
-
-        #print quantity.vertex_values
-        assert num.allclose(quantity.vertex_values, [[3.5, -1.0, 3.5],
-                                                     [3.+2./3, 6.+2./3, 4.+2./3],
-                                                 [4.6, 3.4, 1.],
-                                                 [-5.0, 1.0, 4.0]])
-
-        #print quantity.edge_values
-        assert num.allclose(quantity.edge_values, [[1.25, 3.5, 1.25],
-                                                   [5. + 2/3.0, 4.0 + 1.0/6, 5.0 + 1.0/6],
-                                                   [2.2, 2.8, 4.0],
-                                                   [2.5, -0.5, -2.0]])
-        
-    def test_save_to_array(self):
-        quantity = Quantity(self.mesh4,
-                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-        
-        
-        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
-
-        cellsize = 1.0
-        x,y,z = quantity.save_to_array(cellsize=cellsize, smooth=False)
-        #x,y,z = quantity.save_to_array(smooth=False)
-        
-        from pprint import pprint
-        #pprint(x)
-        #pprint(y)
-        #pprint(z)
-        
-        
-        x_ex = [ 0.,  1.,  2.,  3.,  4.]
-        y_ex = [ 0.,  1.,  2.,  3.,  4.]
-        
-        z_ex = [[  2.00000000e+00,   2.50000000e+00,   0.00000000e+00,
-          4.50000000e+00,   9.00000000e+00],
-       [  1.50000000e+00,   5.00000000e+00,   0.00000000e+00,
-          4.50000000e+00,  -9.99900000e+03],
-       [  3.00000000e+00,   3.00000000e+00,   3.00000000e+00,
-         -9.99900000e+03,  -9.99900000e+03],
-       [ -1.50000000e+00,  -1.50000000e+00,  -9.99900000e+03,
-         -9.99900000e+03,  -9.99900000e+03],
-       [ -6.00000000e+00,  -9.99900000e+03,  -9.99900000e+03,
-         -9.99900000e+03,  -9.99900000e+03]]
-
-        assert num.allclose(x_ex,x)
-        assert num.allclose(y_ex,y)
-        assert num.allclose(z_ex,z)
-                
-               
-        Plot = False 
-        if Plot: 
-            import pylab
-            import numpy
-            #a = numpy.where(a == -9999, numpy.nan, a)
-            #a = numpy.where(a > 10.0, numpy.nan, a)
-        
-            #z = z[::-1,:]
-
-            
-            print z
-            print z.shape
-            print x
-            print y
-
-            nrows = z.shape[0]
-            ncols = z.shape[1]            
-        
-            ratio = float(nrows)/float(ncols)
-            print ratio
-            
-            #y = numpy.arange(nrows)*cellsize
-            #x = numpy.arange(ncols)*cellsize
-        
-            #Setup fig size to correpond to array size
-            fig = pylab.figure(figsize=(10, 10*ratio))
-        
-            levels = numpy.arange(-7, 10, 0.1)
-            CF = pylab.contourf(x,y,z, levels=levels)
-            CB = pylab.colorbar(CF, shrink=0.8, extend='both')
-            #CC = pylab.contour(x,y,a, levels=levels)
-            
-            pylab.show()
-        
-
-
-        x,y,z = quantity.save_to_array(cellsize=cellsize, smooth=True)
-        
-        
-        x_ex = [ 0.,  1.,  2.,  3.,  4.]
-        y_ex = [ 0.,  1.,  2.,  3.,  4.]
-        z_ex = [[  2.00000000e+00,   2.33333333e+00,   2.66666667e+00,
-          5.83333333e+00,   9.00000000e+00],
-       [  2.50000000e+00,   2.83333333e+00,   2.66666667e+00,
-          5.83333333e+00,  -9.99900000e+03],
-       [  3.00000000e+00,   2.83333333e+00,   2.66666667e+00,
-         -9.99900000e+03,  -9.99900000e+03],
-       [ -1.50000000e+00,  -1.66666667e+00,  -9.99900000e+03,
-         -9.99900000e+03,  -9.99900000e+03],
-       [ -6.00000000e+00,  -9.99900000e+03,  -9.99900000e+03,
-         -9.99900000e+03,  -9.99900000e+03]]
-
-        #pprint(z)
-        assert num.allclose(x_ex,x)
-        assert num.allclose(y_ex,y)
-        assert num.allclose(z_ex,z)
-        
-        if Plot:
-            import pylab
-            import numpy
-            #a = numpy.where(a == -9999, numpy.nan, a)
-            #a = numpy.where(a > 10.0, numpy.nan, a)
-        
-            #a = a[::-1,:]
-            nrows = z.shape[0]
-            ncols = z.shape[1]
-        
-            ratio = float(nrows)/float(ncols)
-            print ratio
-        
-            #Setup fig size to correpond to array size
-            fig = pylab.figure(figsize=(10, 10*ratio))
-        
-            levels = numpy.arange(-7, 10, 0.1)
-            CF = pylab.contourf(x,y,z, levels=levels)
-            CB = pylab.colorbar(CF, shrink=0.8, extend='both')
-            #CC = pylab.contour(x,y,a, levels=[0.0,1.0,2.0,3.0])
-            
-            pylab.show()        
-        
-
-
-
-
-    def test_get_extrema_1(self):
-        quantity = Quantity(self.mesh4,
-                                      [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroids
-
-        v = quantity.get_maximum_value()
-        assert v == 5
-
-        v = quantity.get_minimum_value()
-        assert v == 0        
-
-        i = quantity.get_maximum_index()
-        assert i == 1
-
-        i = quantity.get_minimum_index()
-        assert i == 3        
-        
-        x,y = quantity.get_maximum_location()
-        xref, yref = 4.0/3, 4.0/3
-        assert x == xref
-        assert y == yref
-
-        v = quantity.get_values(interpolation_points = [[x,y]])
-        assert num.allclose(v, 5)
-
-
-        x,y = quantity.get_minimum_location()
-        v = quantity.get_values(interpolation_points = [[x,y]])
-        assert num.allclose(v, 0)
-
-
-    def test_get_maximum_2(self):
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        domain = Generic_Domain(points, vertices)
-
-        quantity = Quantity(domain)
-        quantity.set_values(lambda x, y: x+2*y) #2 4 4 6
-        
-        v = quantity.get_maximum_value()
-        assert v == 6
-
-        v = quantity.get_minimum_value()
-        assert v == 2        
-
-        i = quantity.get_maximum_index()
-        assert i == 3
-
-        i = quantity.get_minimum_index()
-        assert i == 0        
-        
-        x,y = quantity.get_maximum_location()
-        xref, yref = 2.0/3, 8.0/3
-        assert x == xref
-        assert y == yref
-
-        v = quantity.get_values(interpolation_points = [[x,y]])
-        assert num.allclose(v, 6)
-
-        x,y = quantity.get_minimum_location()        
-        v = quantity.get_values(interpolation_points = [[x,y]])
-        assert num.allclose(v, 2)
-
-        #Multiple locations for maximum -
-        #Test that the algorithm picks the first occurrence        
-        v = quantity.get_maximum_value(indices=[0,1,2])
-        assert num.allclose(v, 4)
-
-        i = quantity.get_maximum_index(indices=[0,1,2])
-        assert i == 1
-        
-        x,y = quantity.get_maximum_location(indices=[0,1,2])
-        xref, yref = 4.0/3, 4.0/3
-        assert x == xref
-        assert y == yref
-
-        v = quantity.get_values(interpolation_points = [[x,y]])
-        assert num.allclose(v, 4)        
-
-        # More test of indices......
-        v = quantity.get_maximum_value(indices=[2,3])
-        assert num.allclose(v, 6)
-
-        i = quantity.get_maximum_index(indices=[2,3])
-        assert i == 3
-        
-        x,y = quantity.get_maximum_location(indices=[2,3])
-        xref, yref = 2.0/3, 8.0/3
-        assert x == xref
-        assert y == yref
-
-        v = quantity.get_values(interpolation_points = [[x,y]])
-        assert num.allclose(v, 6)        
-
-        
-
-    def test_boundary_allocation(self):
-        quantity = Quantity(self.mesh4,
-                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-
-        assert quantity.boundary_values.shape[0] == len(self.mesh4.boundary)
-
-
-    def test_set_values(self):
-        quantity = Quantity(self.mesh4)
-
-        # get referece to data arrays
-        centroid_values = quantity.centroid_values
-        vertex_values = quantity.vertex_values
-
-        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
-                            location = 'vertices')
-        assert num.allclose(quantity.vertex_values,
-                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-
-        assert id(vertex_values) == id(quantity.vertex_values)
-        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
-        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
-                                                   [5., 5., 5.],
-                                                   [4.5, 4.5, 0.],
-                                                   [3.0, -1.5, -1.5]])
-
-
-        # Test default
-        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-        assert num.allclose(quantity.vertex_values,
-                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
-        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
-                                                   [5., 5., 5.],
-                                                   [4.5, 4.5, 0.],
-                                                   [3.0, -1.5, -1.5]])
-
-        # Test centroids
-        quantity.set_values([1,2,3,4], location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [1., 2., 3., 4.]) #Centroid
-
-        # Test exceptions
-        try:
-            quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
-                                location = 'bas kamel tuba')
-        except:
-            pass
-
-
-
-        try:
-            quantity.set_values([[1,2,3], [0,0,9]])
-        except ValueError:
-            pass
-        except:
-            raise Exception('should have raised ValueeError')
-
-
-
-    def test_set_values_const(self):
-        quantity = Quantity(self.mesh4)
-
-        quantity.set_values(1.0, location = 'vertices')
-        assert num.allclose(quantity.vertex_values,
-                            [[1,1,1], [1,1,1], [1,1,1], [1, 1, 1]])
-
-        assert num.allclose(quantity.centroid_values, [1, 1, 1, 1]) #Centroid
-        assert num.allclose(quantity.edge_values, [[1, 1, 1],
-                                                   [1, 1, 1],
-                                                   [1, 1, 1],
-                                                   [1, 1, 1]])
-
-
-        quantity.set_values(2.0, location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [2, 2, 2, 2])
-
-
-    def test_set_values_func(self):
-        quantity = Quantity(self.mesh4)
-
-        def f(x, y):
-            return x+y
-
-        quantity.set_values(f, location = 'vertices')
-        #print "quantity.vertex_values",quantity.vertex_values
-        assert num.allclose(quantity.vertex_values,
-                            [[2,0,2], [2,2,4], [4,2,4], [4,2,4]])
-        assert num.allclose(quantity.centroid_values,
-                            [4.0/3, 8.0/3, 10.0/3, 10.0/3])
-        assert num.allclose(quantity.edge_values,
-                            [[1,2,1], [3,3,2], [3,4,3], [3,4,3]])
-
-
-        quantity.set_values(f, location = 'centroids')
-        assert num.allclose(quantity.centroid_values,
-                            [4.0/3, 8.0/3, 10.0/3, 10.0/3])
-
-
-    def test_integral(self):
-        quantity = Quantity(self.mesh4)
-
-        # Try constants first
-        const = 5
-        quantity.set_values(const, location = 'vertices')
-        #print 'Q', quantity.get_integral()
-
-        assert num.allclose(quantity.get_integral(), self.mesh4.get_area() * const)
-
-        # Try with a linear function
-        def f(x, y):
-            return x+y
-
-        quantity.set_values(f, location = 'vertices')
-
-
-        ref_integral = (4.0/3 + 8.0/3 + 10.0/3 + 10.0/3) * 2
-
-        assert num.allclose (quantity.get_integral(), ref_integral)
-
-    def test_integral_with_region(self):
-        quantity = Quantity(self.mesh4)
-
-        # Try constants first
-        const = 5
-        quantity.set_values(const, location = 'vertices')
-        #print 'Q', quantity.get_integral()
-
-        assert num.allclose(quantity.get_integral(), self.mesh4.get_area() * const)
-
-        # Try with a linear function
-        def f(x, y):
-            return x+y
-
-        quantity.set_values(f, location = 'vertices')
-
-
-        from anuga import Region
-
-        reg1 = Region(self.mesh4, indices=[2])
-        ref_integral = (10.0/3) * 2
-
-        assert num.allclose (quantity.get_integral(region=reg1), ref_integral)
-
-        reg2 = Region(self.mesh4, indices=[2,3])
-        ref_integral = (10.0/3 + 10.0/3) * 2
-
-        assert num.allclose (quantity.get_integral(region=reg2), ref_integral)
-
-        id=[2,3]
-        ref_integral = (10.0/3 + 10.0/3) * 2
-
-        assert num.allclose (quantity.get_integral(indices=id), ref_integral)
-
-    def test_set_vertex_values(self):
-        quantity = Quantity(self.mesh4)
-        quantity.set_vertex_values([0,1,2,3,4,5])
-
-        assert num.allclose(quantity.vertex_values,
-                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-        assert num.allclose(quantity.centroid_values,
-                            [1., 7./3, 11./3, 8./3]) #Centroid
-        assert num.allclose(quantity.edge_values, [[1., 1.5, 0.5],
-                                                   [3., 2.5, 1.5],
-                                                   [3.5, 4.5, 3.],
-                                                   [2.5, 3.5, 2]])
-
-
-    def test_set_vertex_values_subset(self):
-        quantity = Quantity(self.mesh4)
-        quantity.set_vertex_values([0,1,2,3,4,5])
-        quantity.set_vertex_values([0,20,30,50], indices = [0,2,3,5])
-
-        assert num.allclose(quantity.vertex_values,
-                            [[1,0,20], [1,20,4], [4,20,50], [30,1,4]])
-
-
-    def test_set_vertex_values_using_general_interface(self):
-        quantity = Quantity(self.mesh4)
-
-
-        quantity.set_values([0,1,2,3,4,5])
-
-
-        assert num.allclose(quantity.vertex_values,
-                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-        #Centroid
-        assert num.allclose(quantity.centroid_values, [1., 7./3, 11./3, 8./3])
-
-        assert num.allclose(quantity.edge_values, [[1., 1.5, 0.5],
-                                                   [3., 2.5, 1.5],
-                                                   [3.5, 4.5, 3.],
-                                                   [2.5, 3.5, 2]])
-
-
-
-    def test_set_vertex_values_using_general_interface_with_subset(self):
-        """test_set_vertex_values_using_general_interface_with_subset(self):
-        
-        Test that indices and polygon works (for constants values)
-        """
-        
-        quantity = Quantity(self.mesh4)
-
-
-        quantity.set_values([0,2,3,5], indices=[0,2,3,5])
-        assert num.allclose(quantity.vertex_values,
-                            [[0,0,2], [0,2,0], [0,2,5], [3,0,0]])
-
-
-        # Constant
-        quantity.set_values(0.0)
-        quantity.set_values(3.14, indices=[0,2], location='vertices')
-
-        # Indices refer to triangle numbers
-        assert num.allclose(quantity.vertex_values,
-                            [[3.14,3.14,3.14], [0,0,0],
-                             [3.14,3.14,3.14], [0,0,0]])        
-        
-
-
-        # Now try with polygon (pick points where y>2)
-        polygon = [[0,2.1], [4,2.1], [4,7], [0,7]]
-        quantity.set_values(0.0)
-        quantity.set_values(3.14, polygon=polygon)
-        
-        assert num.allclose(quantity.vertex_values,
-                            [[0,0,0], [0,0,0], [0,0,0],
-                             [3.14,3.14,3.14]])                
-
-
-        # Another polygon (pick triangle 1 and 2 (rightmost triangles) 
-        # using centroids
-        polygon = [[2.1, 0.0], [3.5,0.1], [2,2.2], [0.2,2]]
-        quantity.set_values(0.0)
-        quantity.set_values(3.14, location='centroids', polygon=polygon)
-        assert num.allclose(quantity.vertex_values,
-                            [[0,0,0],
-                             [3.14,3.14,3.14],
-                             [3.14,3.14,3.14],                         
-                             [0,0,0]])                
-
-
-        # Same polygon now use vertices (default)
-        polygon = [[2.1, 0.0], [3.5,0.1], [2,2.2], [0.2,2]]
-        quantity.set_values(0.0)
-        #print 'Here 2'
-        quantity.set_values(3.14, polygon=polygon)
-        assert num.allclose(quantity.vertex_values,
-                            [[0,0,0],
-                             [3.14,3.14,3.14],
-                             [3.14,3.14,3.14],                         
-                             [0,0,0]])                
-        
-
-        # Test input checking
-        try:
-            quantity.set_values(3.14, polygon=polygon, indices = [0,2])
-        except:
-            pass
-        else:
-            msg = 'Should have caught this'
-            raise Exception(msg)
-
-
-
-
-
-    def test_set_vertex_values_using_general_interface_subset_and_geo(self):
-        """test_set_vertex_values_using_general_interface_with_subset(self):
-        Test that indices and polygon works using georeferencing
-        """
-        
-        quantity = Quantity(self.mesh4)
-        G = Geo_reference(56, 10, 100)
-        quantity.domain.set_georeference(G)
-
-
-        # Constant
-        quantity.set_values(0.0)
-        quantity.set_values(3.14, indices=[0,2], location='vertices')
-
-        # Indices refer to triangle numbers here - not vertices (why?)
-        assert num.allclose(quantity.vertex_values,
-                            [[3.14,3.14,3.14], [0,0,0],
-                             [3.14,3.14,3.14], [0,0,0]])        
-        
-
-
-        # Now try with polygon (pick points where y>2)
-        polygon = num.array([[0,2.1], [4,2.1], [4,7], [0,7]])
-        polygon += [G.xllcorner, G.yllcorner]
-        
-        quantity.set_values(0.0)
-        quantity.set_values(3.14, polygon=polygon, location='centroids')
-        assert num.allclose(quantity.vertex_values,
-                            [[0,0,0], [0,0,0], [0,0,0],
-                             [3.14,3.14,3.14]])                
-
-
-        # Another polygon (pick triangle 1 and 2 (rightmost triangles)
-        polygon = num.array([[2.1, 0.0], [3.5,0.1], [2,2.2], [0.2,2]])
-        polygon += [G.xllcorner, G.yllcorner]
-        
-        quantity.set_values(0.0)
-        quantity.set_values(3.14, polygon=polygon)
-        msg = ('quantity.vertex_values=\n%s\nshould be close to\n'
-               '[[0,0,0],\n'
-               ' [3.14,3.14,3.14],\n'
-               ' [3.14,3.14,3.14],\n'
-               ' [0,0,0]]' % str(quantity.vertex_values))
-        assert num.allclose(quantity.vertex_values,
-                            [[0,0,0],
-                             [3.14,3.14,3.14],
-                             [3.14,3.14,3.14],                         
-                             [0,0,0]]), msg
-
-
-
-    def test_set_values_using_fit(self):
-
-
-        quantity = Quantity(self.mesh4)
-
-        #Get (enough) datapoints
-        data_points = [[ 0.66666667, 0.66666667],
-                       [ 1.33333333, 1.33333333],
-                       [ 2.66666667, 0.66666667],
-                       [ 0.66666667, 2.66666667],
-                       [ 0.0, 1.0],
-                       [ 0.0, 3.0],
-                       [ 1.0, 0.0],
-                       [ 1.0, 1.0],
-                       [ 1.0, 2.0],
-                       [ 1.0, 3.0],
-                       [ 2.0, 1.0],
-                       [ 3.0, 0.0],
-                       [ 3.0, 1.0]]
-
-        z = linear_function(data_points)
-
-        #Use built-in fit_interpolate.fit
-        quantity.set_values( Geospatial_data(data_points, z), alpha = 0 )
-        #quantity.set_values(points = data_points, values = z, alpha = 0)
-
-
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-        #print quantity.vertex_values, answer
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        #Now try by setting the same values directly
-        vertex_attributes = fit_to_mesh(data_points,
-                                        quantity.domain.get_nodes(),
-                                        quantity.domain.get_triangles(),
-                                        point_attributes=z,
-                                        alpha = 0,
-                                        verbose=False)
-
-        #print vertex_attributes
-        quantity.set_values(vertex_attributes)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-
-
-
-    def test_test_set_values_using_fit_w_geo(self):
-
-
-        #Mesh
-        vertex_coordinates = [[0.76, 0.76],
-                              [0.76, 5.76],
-                              [5.76, 0.76]]
-        triangles = [[0,2,1]]
-
-        mesh_georef = Geo_reference(56,-0.76,-0.76)
-        mesh1 = Generic_Domain(vertex_coordinates, triangles,
-                       geo_reference = mesh_georef)
-        mesh1.check_integrity()
-
-        #Quantity
-        quantity = Quantity(mesh1)
-
-        #Data
-        data_points = [[ 201.0, 401.0],
-                       [ 201.0, 403.0],
-                       [ 203.0, 401.0]]
-
-        z = [2, 4, 4]
-
-        data_georef = Geo_reference(56,-200,-400)
-
-
-        #Reference
-        ref = fit_to_mesh(data_points, vertex_coordinates, triangles,
-                          point_attributes=z,
-                          data_origin = data_georef.get_origin(),
-                          mesh_origin = mesh_georef.get_origin(),
-                          alpha = 0)
-
-        assert num.allclose( ref, [0,5,5] )
-
-
-        #Test set_values
-
-        quantity.set_values( Geospatial_data(data_points, z, data_georef), alpha = 0 )
-
-        #quantity.set_values(points = data_points,
-        #                    values = z,
-        #                    data_georef = data_georef,
-        #                    alpha = 0)
-
-
-        #quantity.set_values(points = data_points,
-        #                    values = z,
-        #                    data_georef = data_georef,
-        #                    alpha = 0)
-        assert num.allclose(quantity.vertex_values.flat, ref)
-
-
-
-        #Test set_values using geospatial data object
-        quantity.vertex_values[:] = 0.0
-
-        geo = Geospatial_data(data_points, z, data_georef)
-
-
-        quantity.set_values(geospatial_data = geo, alpha = 0)
-        assert num.allclose(quantity.vertex_values.flat, ref)
-
-
-
-    def test_set_values_from_file1(self):
-        quantity = Quantity(self.mesh4)
-
-        #Get (enough) datapoints
-        data_points = [[ 0.66666667, 0.66666667],
-                       [ 1.33333333, 1.33333333],
-                       [ 2.66666667, 0.66666667],
-                       [ 0.66666667, 2.66666667],
-                       [ 0.0, 1.0],
-                       [ 0.0, 3.0],
-                       [ 1.0, 0.0],
-                       [ 1.0, 1.0],
-                       [ 1.0, 2.0],
-                       [ 1.0, 3.0],
-                       [ 2.0, 1.0],
-                       [ 3.0, 0.0],
-                       [ 3.0, 1.0]]
-
-        data_geo_spatial = Geospatial_data(data_points,
-                         geo_reference = Geo_reference(56, 0, 0))
-        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(data_points_absolute)
-        att = 'spam_and_eggs'
-        
-        #Create .txt file
-        ptsfile = tempfile.mktemp(".txt")
-        file = open(ptsfile,"w")
-        file.write(" x,y," + att + " \n")
-        for data_point, attribute in map(None, data_points_absolute
-                                         ,attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            file.write(row + "\n")
-        file.close()
-
-
-        #Check that values can be set from file
-        quantity.set_values(filename = ptsfile,
-                            attribute_name = att, alpha = 0)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-
-        #print quantity.vertex_values.flat
-        #print answer
-
-
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        #Check that values can be set from file using default attribute
-        quantity.set_values(filename = ptsfile, alpha = 0)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Cleanup
-        import os
-        os.remove(ptsfile)
-
-
-
-    def Xtest_set_values_from_file_using_polygon(self):
-        """test_set_values_from_file_using_polygon(self):
-        
-        Test that polygon restriction works for general points data
-        """
-        
-        quantity = Quantity(self.mesh4)
-
-        #Get (enough) datapoints
-        data_points = [[ 0.66666667, 0.66666667],
-                       [ 1.33333333, 1.33333333],
-                       [ 2.66666667, 0.66666667],
-                       [ 0.66666667, 2.66666667],
-                       [ 0.0, 1.0],
-                       [ 0.0, 3.0],
-                       [ 1.0, 0.0],
-                       [ 1.0, 1.0],
-                       [ 1.0, 2.0],
-                       [ 1.0, 3.0],
-                       [ 2.0, 1.0],
-                       [ 3.0, 0.0],
-                       [ 3.0, 1.0]]
-
-        data_geo_spatial = Geospatial_data(data_points,
-                         geo_reference = Geo_reference(56, 0, 0))
-        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(data_points_absolute)
-        att = 'spam_and_eggs'
-        
-        #Create .txt file
-        ptsfile = tempfile.mktemp(".txt")
-        file = open(ptsfile,"w")
-        file.write(" x,y," + att + " \n")
-        for data_point, attribute in map(None, data_points_absolute
-                                         ,attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            file.write(row + "\n")
-        file.close()
-
-        # Create restricting polygon (containing node #4 (2,2) and 
-        # centroid of triangle #1 (bce)
-        polygon = [[1.0, 1.0], [4.0, 1.0],
-                   [4.0, 4.0], [1.0, 4.0]]
-
-        #print self.mesh4.nodes
-        #print inside_polygon(self.mesh4.nodes, polygon)
-        assert num.allclose(inside_polygon(self.mesh4.nodes, polygon), 4)
-
-        #print quantity.domain.get_vertex_coordinates()
-        #print quantity.domain.get_nodes()        
-        
-        # Check that values can be set from file
-        quantity.set_values(filename=ptsfile,
-                            polygon=polygon,
-                            location='unique vertices',
-                            alpha=0)
-
-        # Get indices for vertex coordinates in polygon
-        indices = inside_polygon(quantity.domain.get_vertex_coordinates(), 
-                                 polygon)
-        points = take(quantity.domain.get_vertex_coordinates(), indices)
-        
-        answer = linear_function(points)
-
-        #print quantity.vertex_values.flat
-        #print answer
-
-        # Check vertices in polygon have been set
-        assert num.allclose(take(quantity.vertex_values.flat, indices),
-                            answer)
-
-        # Check vertices outside polygon are zero
-        indices = outside_polygon(quantity.domain.get_vertex_coordinates(), 
-                                  polygon)        
-        assert num.allclose(take(quantity.vertex_values.flat, indices),
-                            0.0)        
-
-        #Cleanup
-        import os
-        os.remove(ptsfile)
-
-
-        
-
-    def test_cache_test_set_values_from_file(self):
-        # FIXME (Ole): What is this about?
-        # I don't think it checks anything new
-        quantity = Quantity(self.mesh4)
-
-        #Get (enough) datapoints
-        data_points = [[ 0.66666667, 0.66666667],
-                       [ 1.33333333, 1.33333333],
-                       [ 2.66666667, 0.66666667],
-                       [ 0.66666667, 2.66666667],
-                       [ 0.0, 1.0],
-                       [ 0.0, 3.0],
-                       [ 1.0, 0.0],
-                       [ 1.0, 1.0],
-                       [ 1.0, 2.0],
-                       [ 1.0, 3.0],
-                       [ 2.0, 1.0],
-                       [ 3.0, 0.0],
-                       [ 3.0, 1.0]]
-
-        georef = Geo_reference(56, 0, 0)
-        data_geo_spatial = Geospatial_data(data_points,
-                                           geo_reference=georef)
-                                           
-        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(data_points_absolute)
-        att = 'spam_and_eggs'
-        
-        # Create .txt file
-        ptsfile = tempfile.mktemp(".txt")
-        file = open(ptsfile,"w")
-        file.write(" x,y," + att + " \n")
-        for data_point, attribute in map(None, data_points_absolute
-                                         ,attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            file.write(row + "\n")
-        file.close()
-
-
-        # Check that values can be set from file
-        quantity.set_values(filename=ptsfile,
-                            attribute_name=att, 
-                            alpha=0, 
-                            use_cache=True,
-                            verbose=False)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        # Check that values can be set from file using default attribute
-        quantity.set_values(filename=ptsfile, 
-                            alpha=0)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        # Check cache
-        quantity.set_values(filename=ptsfile,
-                            attribute_name=att, 
-                            alpha=0, 
-                            use_cache=True,
-                            verbose=False)
-        
-        
-        #Cleanup
-        import os
-        os.remove(ptsfile)
-
-    def test_set_values_from_lat_long(self):
-        quantity = Quantity(self.mesh_onslow)
-
-        #Get (enough) datapoints
-        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6]]
-
-        data_geo_spatial = Geospatial_data(data_points,
-                                           points_are_lats_longs=True)
-        points_UTM = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(points_UTM)
-        att = 'elevation'
-        
-        #Create .txt file
-        txt_file = tempfile.mktemp(".txt")
-        file = open(txt_file,"w")
-        file.write(" lat,long," + att + " \n")
-        for data_point, attribute in map(None, data_points, attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            #print "row", row 
-            file.write(row + "\n")
-        file.close()
-
-
-        #Check that values can be set from file
-        quantity.set_values(filename=txt_file,
-                            attribute_name=att, 
-                            alpha=0)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-
-        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
-        #print "answer",answer
-
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        #Check that values can be set from file using default attribute
-        quantity.set_values(filename=txt_file, alpha=0)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Cleanup
-        import os
-        os.remove(txt_file)
-         
-    def test_set_values_from_lat_long(self):
-        quantity = Quantity(self.mesh_onslow)
-
-        #Get (enough) datapoints
-        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6]]
-
-        data_geo_spatial = Geospatial_data(data_points,
-                                           points_are_lats_longs=True)
-        points_UTM = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(points_UTM)
-        att = 'elevation'
-        
-        #Create .txt file
-        txt_file = tempfile.mktemp(".txt")
-        file = open(txt_file,"w")
-        file.write(" lat,long," + att + " \n")
-        for data_point, attribute in map(None, data_points, attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            #print "row", row 
-            file.write(row + "\n")
-        file.close()
-
-
-        #Check that values can be set from file
-        quantity.set_values(filename=txt_file,
-                            attribute_name=att, alpha=0)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-
-        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
-        #print "answer",answer
-
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        #Check that values can be set from file using default attribute
-        quantity.set_values(filename=txt_file, alpha=0)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Cleanup
-        import os
-        os.remove(txt_file)
-        
-    def test_set_values_from_UTM_pts(self):
-        quantity = Quantity(self.mesh_onslow)
-
-        #Get (enough) datapoints
-        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6]]
-
-        data_geo_spatial = Geospatial_data(data_points,
-                                           points_are_lats_longs=True)
-        points_UTM = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(points_UTM)
-        att = 'elevation'
-        
-        #Create .txt file
-        txt_file = tempfile.mktemp(".txt")
-        file = open(txt_file,"w")
-        file.write(" x,y," + att + " \n")
-        for data_point, attribute in map(None, points_UTM, attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            #print "row", row 
-            file.write(row + "\n")
-        file.close()
-
-
-        pts_file = tempfile.mktemp(".pts")        
-        convert = Geospatial_data(txt_file)
-        convert.export_points_file(pts_file)
-
-        #Check that values can be set from file
-        quantity.set_values_from_file(pts_file, att, 0,
-                                      'vertices', None)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
-        #print "answer",answer
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Check that values can be set from file
-        quantity.set_values(filename=pts_file,
-                            attribute_name=att, alpha=0)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
-        #print "answer",answer
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        #Check that values can be set from file using default attribute
-        quantity.set_values(filename=txt_file, alpha=0)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Cleanup
-        import os
-        os.remove(txt_file)
-        os.remove(pts_file)
-        
-    def verbose_test_set_values_from_UTM_pts(self):
-        quantity = Quantity(self.mesh_onslow)
-
-        #Get (enough) datapoints
-        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       [-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
-                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6],
-                       ]
-
-        data_geo_spatial = Geospatial_data(data_points,
-                                           points_are_lats_longs=True)
-        points_UTM = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(points_UTM)
-        att = 'elevation'
-        
-        #Create .txt file
-        txt_file = tempfile.mktemp(".txt")
-        file = open(txt_file,"w")
-        file.write(" x,y," + att + " \n")
-        for data_point, attribute in map(None, points_UTM, attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            #print "row", row 
-            file.write(row + "\n")
-        file.close()
-
-
-        pts_file = tempfile.mktemp(".pts")        
-        convert = Geospatial_data(txt_file)
-        convert.export_points_file(pts_file)
-
-        #Check that values can be set from file
-        quantity.set_values_from_file(pts_file, att, 0,
-                                      'vertices', None, verbose = True,
-                                      max_read_lines=2)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
-        #print "answer",answer
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Check that values can be set from file
-        quantity.set_values(filename=pts_file,
-                            attribute_name=att, alpha=0)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-        #print "quantity.vertex_values.flat", quantity.vertex_values.flat
-        #print "answer",answer
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        #Check that values can be set from file using default attribute
-        quantity.set_values(filename=txt_file, alpha=0)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Cleanup
-        import os
-        os.remove(txt_file)
-        os.remove(pts_file)
-        
-    def test_set_values_from_file_with_georef1(self):
-
-        #Mesh in zone 56 (absolute coords)
-
-        x0 = 314036.58727982
-        y0 = 6224951.2960092
-
-        a = [x0+0.0, y0+0.0]
-        b = [x0+0.0, y0+2.0]
-        c = [x0+2.0, y0+0.0]
-        d = [x0+0.0, y0+4.0]
-        e = [x0+2.0, y0+2.0]
-        f = [x0+4.0, y0+0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        #absolute going in ..
-        mesh4 = Generic_Domain(points, elements,
-                       geo_reference = Geo_reference(56, 0, 0))
-        mesh4.check_integrity()
-        quantity = Quantity(mesh4)
-
-        #Get (enough) datapoints (relative to georef)
-        data_points_rel = [[ 0.66666667, 0.66666667],
-                       [ 1.33333333, 1.33333333],
-                       [ 2.66666667, 0.66666667],
-                       [ 0.66666667, 2.66666667],
-                       [ 0.0, 1.0],
-                       [ 0.0, 3.0],
-                       [ 1.0, 0.0],
-                       [ 1.0, 1.0],
-                       [ 1.0, 2.0],
-                       [ 1.0, 3.0],
-                       [ 2.0, 1.0],
-                       [ 3.0, 0.0],
-                       [ 3.0, 1.0]]
-
-        data_geo_spatial = Geospatial_data(data_points_rel,
-                         geo_reference = Geo_reference(56, x0, y0))
-        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(data_points_absolute)
-        att = 'spam_and_eggs'
-        
-        #Create .txt file
-        ptsfile = tempfile.mktemp(".txt")
-        file = open(ptsfile,"w")
-        file.write(" x,y," + att + " \n")
-        for data_point, attribute in map(None, data_points_absolute
-                                         ,attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            file.write(row + "\n")
-        file.close()
-
-        #file = open(ptsfile, 'r')
-        #lines = file.readlines()
-        #file.close()
-     
-
-        #Check that values can be set from file
-        quantity.set_values(filename=ptsfile,
-                            attribute_name=att, alpha=0)
-        answer = linear_function(quantity.domain.get_vertex_coordinates())
-
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        #Check that values can be set from file using default attribute
-        quantity.set_values(filename=ptsfile, alpha=0)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Cleanup
-        import os
-        os.remove(ptsfile)
-
-
-    def test_set_values_from_file_with_georef2(self):
-
-        #Mesh in zone 56 (relative coords)
-
-        x0 = 314036.58727982
-        y0 = 6224951.2960092
-        #x0 = 0.0
-        #y0 = 0.0
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        mesh4 = Generic_Domain(points, elements,
-                       geo_reference = Geo_reference(56, x0, y0))
-        mesh4.check_integrity()
-        quantity = Quantity(mesh4)
-
-        #Get (enough) datapoints
-        data_points = [[ x0+0.66666667, y0+0.66666667],
-                       [ x0+1.33333333, y0+1.33333333],
-                       [ x0+2.66666667, y0+0.66666667],
-                       [ x0+0.66666667, y0+2.66666667],
-                       [ x0+0.0, y0+1.0],
-                       [ x0+0.0, y0+3.0],
-                       [ x0+1.0, y0+0.0],
-                       [ x0+1.0, y0+1.0],
-                       [ x0+1.0, y0+2.0],
-                       [ x0+1.0, y0+3.0],
-                       [ x0+2.0, y0+1.0],
-                       [ x0+3.0, y0+0.0],
-                       [ x0+3.0, y0+1.0]]
-
-
-        data_geo_spatial = Geospatial_data(data_points,
-                         geo_reference = Geo_reference(56, 0, 0))
-        data_points_absolute = data_geo_spatial.get_data_points(absolute=True)
-        attributes = linear_function(data_points_absolute)
-        att = 'spam_and_eggs'
-        
-        #Create .txt file
-        ptsfile = tempfile.mktemp(".txt")
-        file = open(ptsfile,"w")
-        file.write(" x,y," + att + " \n")
-        for data_point, attribute in map(None, data_points_absolute
-                                         ,attributes):
-            row = str(data_point[0]) + ',' + str(data_point[1]) \
-                  + ',' + str(attribute)
-            file.write(row + "\n")
-        file.close()
-
-
-        #Check that values can be set from file
-        quantity.set_values(filename=ptsfile,
-                            attribute_name=att, alpha=0)
-        answer = linear_function(quantity.domain. \
-                                 get_vertex_coordinates(absolute=True))
-
-
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-
-        #Check that values can be set from file using default attribute
-        quantity.set_values(filename=ptsfile, alpha=0)
-        assert num.allclose(quantity.vertex_values.flat, answer)
-
-        #Cleanup
-        import os
-        os.remove(ptsfile)
-
-
-    def test_set_values_from_utm_grid_file(self):
-        
-        
-
-        x0 = 0.0
-        y0 = 0.0
-
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0, 0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0, 0.0]
-
-        points = [a, b, c, d, e, f]
-
-        #bac, bce, ecf, dbe
-        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
-
-        mesh4 = Generic_Domain(points, elements)
-                     #  geo_reference = Geo_reference(56, x0, y0))
-        mesh4.check_integrity()
-        quantity = Quantity(mesh4)
-
-        """ Format of asc file 
-        ncols         11
-        nrows         12
-        xllcorner     240000
-        yllcorner     7620000
-        cellsize      6000
-        NODATA_value  -9999
-        """
-        ncols = 11  # Nx
-        nrows = 12  # Ny
-        xllcorner = x0
-        yllcorner = y0
-        cellsize  = 1.0
-        NODATA_value =  -9999
-        
-        #xllcorner = 0
-        #yllcorner = 100
-        #cellsize  = 10
-        #NODATA_value =  -9999
-        
-        #Create .asc file
-        #txt_file = tempfile.mktemp(".asc")
-        txt_file = 'test_asc.asc'
-        datafile = open(txt_file,"w")
-        datafile.write('ncols '+str(ncols)+"\n")
-        datafile.write('nrows '+str(nrows)+"\n")
-        datafile.write('xllcorner '+str(xllcorner)+"\n")
-        datafile.write('yllcorner '+str(yllcorner)+"\n")
-        datafile.write('cellsize '+str(cellsize)+"\n")
-        datafile.write('NODATA_value '+str(NODATA_value)+"\n")
-        
-        x = num.linspace(xllcorner, xllcorner+(ncols-1)*cellsize, ncols)
-        y = num.linspace(yllcorner, yllcorner+(nrows-1)*cellsize, nrows)
-        points = axes2points(x, y)
-        
-        #print points
-        #print x.shape, x
-        #print y.shape, y
-        
-        datavalues = linear_function(points)
-        #print datavalues 
-        
-        datavalues = datavalues.reshape(nrows,ncols)
-
-        #print datavalues
-        #print datavalues.shape
-        for row in datavalues:
-            #print row
-            datafile.write(" ".join(str(elem) for elem in row) + "\n")         
-        datafile.close()
-
-        #print quantity.vertex_values
-        #print quantity.centroid_values 
-
-        quantity.set_values_from_utm_grid_file(txt_file,
-                             location='vertices',
-                             indices=None,
-                             verbose=False)
-
-        # check order of vertices
-
-        answer = [[  6.,   0.,   2.],
-                  [  6.,   2.,   8.],
-                  [  8.,  2.,   4.],
-                  [ 12.,   6.,   8.]]
-        #print quantity.vertex_values
-        assert num.allclose(quantity.vertex_values, answer)
-        
-        
-        #print quantity.vertex_values
-        #print quantity.centroid_values 
-        quantity.set_values(0.0)
-        
-        
-        #print quantity.vertex_values
-        #print quantity.centroid_values 
-        quantity.set_values_from_utm_grid_file(txt_file,
-                             location='centroids',
-                             indices=None,
-                             verbose=False)
-        
-        #print quantity.vertex_values
-        #print quantity.centroid_values      
-        
-
-        answer = [ 2.66666667,  5.33333333,  4.66666667,  8.66666667]
-        
-        assert num.allclose(quantity.centroid_values, answer)
-        #Cleanup
-        #import os
-        #os.remove(txt_file)        
-        
-
-
-    def test_set_values_from_quantity(self):
-
-        quantity1 = Quantity(self.mesh4)
-        quantity1.set_vertex_values([0,1,2,3,4,5])
-
-        assert num.allclose(quantity1.vertex_values,
-                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-
-        quantity2 = Quantity(self.mesh4)
-        quantity2.set_values(quantity=quantity1)
-        assert num.allclose(quantity2.vertex_values,
-                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-        quantity2.set_values(quantity = 2*quantity1)
-        assert num.allclose(quantity2.vertex_values,
-                            [[2,0,4], [2,4,8], [8,4,10], [6,2,8]])
-
-        quantity2.set_values(quantity = 2*quantity1 + 3)
-        assert num.allclose(quantity2.vertex_values,
-                            [[5,3,7], [5,7,11], [11,7,13], [9,5,11]])
-
-
-        #Check detection of quantity as first orgument
-        quantity2.set_values(2*quantity1 + 3)
-        assert num.allclose(quantity2.vertex_values,
-                            [[5,3,7], [5,7,11], [11,7,13], [9,5,11]])
-
-
-
-    def Xtest_set_values_from_quantity_using_polygon(self):
-        """test_set_values_from_quantity_using_polygon(self):
-        
-        Check that polygon can be used to restrict set_values when
-        using another quantity as argument.
-        """
-        
-        # Create restricting polygon (containing node #4 (2,2) and 
-        # centroid of triangle #1 (bce)
-        polygon = [[1.0, 1.0], [4.0, 1.0],
-                   [4.0, 4.0], [1.0, 4.0]]
-        assert num.allclose(inside_polygon(self.mesh4.nodes, polygon), 4)                   
-        
-        quantity1 = Quantity(self.mesh4)
-        quantity1.set_vertex_values([0,1,2,3,4,5])
-
-        assert num.allclose(quantity1.vertex_values,
-                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-
-        quantity2 = Quantity(self.mesh4)
-        quantity2.set_values(quantity=quantity1,
-                             polygon=polygon)
-                             
-        msg = 'Only node #4(e) at (2,2) should have values applied '
-        assert num.allclose(quantity2.vertex_values,
-                            [[0,0,0], [0,0,4], [4,0,0], [0,0,4]]), msg        
-                            #bac,     bce,     ecf,     dbe
-                        
-
-
-    def test_overloading(self):
-
-        quantity1 = Quantity(self.mesh4)
-        quantity1.set_vertex_values([0,1,2,3,4,5])
-
-        assert num.allclose(quantity1.vertex_values,
-                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-
-        quantity2 = Quantity(self.mesh4)
-        quantity2.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
-                             location = 'vertices')
-
-
-
-        quantity3 = Quantity(self.mesh4)
-        quantity3.set_values([[2,2,2], [7,8,9], [7,6,3], [3, 8, -8]],
-                             location = 'vertices')
-
-
-        # Negation
-        Q = -quantity1
-        assert num.allclose(Q.vertex_values, -quantity1.vertex_values)
-        assert num.allclose(Q.centroid_values, -quantity1.centroid_values)
-        assert num.allclose(Q.edge_values, -quantity1.edge_values)
-
-        # Addition
-        Q = quantity1 + 7
-        assert num.allclose(Q.vertex_values, quantity1.vertex_values + 7)
-        assert num.allclose(Q.centroid_values, quantity1.centroid_values + 7)
-        assert num.allclose(Q.edge_values, quantity1.edge_values + 7)
-
-        Q = 7 + quantity1
-        assert num.allclose(Q.vertex_values, quantity1.vertex_values + 7)
-        assert num.allclose(Q.centroid_values, quantity1.centroid_values + 7)
-        assert num.allclose(Q.edge_values, quantity1.edge_values + 7)
-
-        Q = quantity1 + quantity2
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values + quantity2.vertex_values)
-        assert num.allclose(Q.centroid_values,
-                            quantity1.centroid_values + quantity2.centroid_values)
-        assert num.allclose(Q.edge_values,
-                            quantity1.edge_values + quantity2.edge_values)
-
-
-        Q = quantity1 + quantity2 - 3
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values + quantity2.vertex_values - 3)
-
-        Q = quantity1 - quantity2
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values - quantity2.vertex_values)
-
-        #Scaling
-        Q = quantity1*3
-        assert num.allclose(Q.vertex_values, quantity1.vertex_values*3)
-        assert num.allclose(Q.centroid_values, quantity1.centroid_values*3)
-        assert num.allclose(Q.edge_values, quantity1.edge_values*3)
-        Q = 3*quantity1
-        assert num.allclose(Q.vertex_values, quantity1.vertex_values*3)
-
-        #Multiplication
-        Q = quantity1 * quantity2
-        #print Q.vertex_values
-        #print Q.centroid_values
-        #print quantity1.centroid_values
-        #print quantity2.centroid_values
-
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values * quantity2.vertex_values)
-
-        #Linear combinations
-        Q = 4*quantity1 + 2
-        assert num.allclose(Q.vertex_values,
-                            4*quantity1.vertex_values + 2)
-
-        Q = quantity1*quantity2 + 2
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values * quantity2.vertex_values + 2)
-
-        Q = quantity1*quantity2 + quantity3
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values * quantity2.vertex_values +
-                        quantity3.vertex_values)
-        Q = quantity1*quantity2 + 3*quantity3
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values * quantity2.vertex_values +
-                            3*quantity3.vertex_values)
-        Q = quantity1*quantity2 + 3*quantity3 + 5.0
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values * quantity2.vertex_values +
-                            3*quantity3.vertex_values + 5)
-
-        Q = quantity1*quantity2 - quantity3
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values * quantity2.vertex_values -
-                            quantity3.vertex_values)
-        Q = 1.5*quantity1*quantity2 - 3*quantity3 + 5.0
-        assert num.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 num.allclose(Q.vertex_values,
-                            1.5*quantity1.vertex_values * quantity2.vertex_values -
-                            3*quantity3.vertex_values + 5)
-
-
-        #Powers
-        Q = quantity1**2
-        assert num.allclose(Q.vertex_values, quantity1.vertex_values**2)
-
-        Q = quantity1**2 +quantity2**2
-        assert num.allclose(Q.vertex_values,
-                            quantity1.vertex_values**2 + \
-                            quantity2.vertex_values**2)
-
-        Q = (quantity1**2 +quantity2**2)**0.5
-        assert num.allclose(Q.vertex_values,
-                            (quantity1.vertex_values**2 + \
-                            quantity2.vertex_values**2)**0.5)
-
-
-
-
-
-
-
-    def test_compute_gradient(self):
-        quantity = Quantity(self.mesh4)
-
-        #Set up for a gradient of (2,0) at mid triangle
-        quantity.set_values([2.0, 4.0, 6.0, 2.0],
-                            location = 'centroids')
-
-
-        #Gradients
-        quantity.compute_gradients()
-
-        a = quantity.x_gradient
-        b = quantity.y_gradient
-        #print self.mesh4.centroid_coordinates
-        #print a, b
-
-        #The central triangle (1)
-        #(using standard gradient based on neigbours controid values)
-        assert num.allclose(a[1], 2.0)
-        assert num.allclose(b[1], 0.0)
-
-
-        #Left triangle (0) using two point gradient
-        #q0 = q1 + a*(x0-x1) + b*(y0-y1)  <=>
-        #2  = 4  + a*(-2/3)  + b*(-2/3)
-        assert num.allclose(a[0] + b[0], 3)
-        #From orthogonality (a*(y0-y1) + b*(x0-x1) == 0)
-        assert num.allclose(a[0] - b[0], 0)
-
-
-        #Right triangle (2) using two point gradient
-        #q2 = q1 + a*(x2-x1) + b*(y2-y1)  <=>
-        #6  = 4  + a*(4/3)  + b*(-2/3)
-        assert num.allclose(2*a[2] - b[2], 3)
-        #From orthogonality (a*(y1-y2) + b*(x2-x1) == 0)
-        assert num.allclose(a[2] + 2*b[2], 0)
-
-
-        #Top triangle (3) using two point gradient
-        #q3 = q1 + a*(x3-x1) + b*(y3-y1)  <=>
-        #2  = 4  + a*(-2/3)  + b*(4/3)
-        assert num.allclose(a[3] - 2*b[3], 3)
-        #From orthogonality (a*(y1-y3) + b*(x3-x1) == 0)
-        assert num.allclose(2*a[3] + b[3], 0)
-
-
-
-        #print a, b
-        quantity.extrapolate_second_order()
-
-        #Apply q(x,y) = qc + a*(x-xc) + b*(y-yc)
-        assert num.allclose(quantity.vertex_values[0,:], [3., 0.,  3.])
-        assert num.allclose(quantity.vertex_values[1,:], [4./3, 16./3,  16./3])
-
-
-        #a = 1.2, b=-0.6
-        #q(4,0) = 6 + a*(4 - 8/3) + b*(-2/3)
-        assert num.allclose(quantity.vertex_values[2,2], 8)
-
-    def test_get_gradients(self):
-        quantity = Quantity(self.mesh4)
-
-        #Set up for a gradient of (2,0) at mid triangle
-        quantity.set_values([2.0, 4.0, 6.0, 2.0],
-                            location = 'centroids')
-
-
-        #Gradients
-        quantity.compute_gradients()
-
-        a, b = quantity.get_gradients()
-        #print self.mesh4.centroid_coordinates
-        #print a, b
-
-        #The central triangle (1)
-        #(using standard gradient based on neigbours controid values)
-        assert num.allclose(a[1], 2.0)
-        assert num.allclose(b[1], 0.0)
-
-
-        #Left triangle (0) using two point gradient
-        #q0 = q1 + a*(x0-x1) + b*(y0-y1)  <=>
-        #2  = 4  + a*(-2/3)  + b*(-2/3)
-        assert num.allclose(a[0] + b[0], 3)
-        #From orthogonality (a*(y0-y1) + b*(x0-x1) == 0)
-        assert num.allclose(a[0] - b[0], 0)
-
-
-        #Right triangle (2) using two point gradient
-        #q2 = q1 + a*(x2-x1) + b*(y2-y1)  <=>
-        #6  = 4  + a*(4/3)  + b*(-2/3)
-        assert num.allclose(2*a[2] - b[2], 3)
-        #From orthogonality (a*(y1-y2) + b*(x2-x1) == 0)
-        assert num.allclose(a[2] + 2*b[2], 0)
-
-
-        #Top triangle (3) using two point gradient
-        #q3 = q1 + a*(x3-x1) + b*(y3-y1)  <=>
-        #2  = 4  + a*(-2/3)  + b*(4/3)
-        assert num.allclose(a[3] - 2*b[3], 3)
-        #From orthogonality (a*(y1-y3) + b*(x3-x1) == 0)
-        assert num.allclose(2*a[3] + b[3], 0)
-
-
-    def test_second_order_extrapolation2(self):
-        quantity = Quantity(self.mesh4)
-
-        #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.x_gradient
-        b = quantity.y_gradient
-        
-        #print a, b
-
-        assert num.allclose(a[1], 3.0)
-        assert num.allclose(b[1], 1.0)
-
-        #Work out the others
-
-        quantity.extrapolate_second_order()
-
-        #print quantity.vertex_values
-        assert num.allclose(quantity.vertex_values[1,0], 2.0)
-        assert num.allclose(quantity.vertex_values[1,1], 6.0)
-        assert num.allclose(quantity.vertex_values[1,2], 8.0)
-
-
-
-    def test_backup_saxpy_centroid_values(self):
-        quantity = Quantity(self.mesh4)
-
-        #Set up for a gradient of (3,1), f(x) = 3x+y
-        c_values = num.array([2.0+2.0/3, 4.0+4.0/3, 8.0+2.0/3, 2.0+8.0/3])
-        d_values = num.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 num.allclose(quantity.centroid_values, quantity.centroid_backup_values)
-
-
-        quantity.set_values(d_values, location = 'centroids')
-
-        quantity.saxpy_centroid_values(2.0, 3.0)
-
-        assert num.allclose(quantity.centroid_values, 2.0*d_values + 3.0*c_values)
-
-
-
-    def test_first_order_extrapolator(self):
-        quantity = Quantity(self.mesh4)
-
-        #Test centroids
-        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
-
-        #Extrapolate
-        quantity.extrapolate_first_order()
-
-        #Check that gradient is zero
-        a,b = quantity.get_gradients()
-        assert num.allclose(a, [0,0,0,0])
-        assert num.allclose(b, [0,0,0,0])
-
-        #Check vertices but not edge values
-        assert num.allclose(quantity.vertex_values,
-                            [[1,1,1], [2,2,2], [3,3,3], [4, 4, 4]])
-
-
-    def test_second_order_extrapolator(self):
-        quantity = Quantity(self.mesh4)
-
-        #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()
-        quantity.limit()
-
-
-        #Assert that central triangle is limited by neighbours
-        assert quantity.vertex_values[1,0] >= quantity.vertex_values[0,0]
-        assert quantity.vertex_values[1,0] >= quantity.vertex_values[3,1]
-
-        assert quantity.vertex_values[1,1] <= quantity.vertex_values[2,1]
-        assert quantity.vertex_values[1,1] >= quantity.vertex_values[0,2]
-
-        assert quantity.vertex_values[1,2] <= quantity.vertex_values[2,0]
-        assert quantity.vertex_values[1,2] >= quantity.vertex_values[3,1]
-
-
-        #Assert that quantities are conserved
-        for k in range(quantity.centroid_values.shape[0]):
-            assert num.allclose (quantity.centroid_values[k],
-                             num.sum(quantity.vertex_values[k,:])/3)
-
-
-
-
-
-    def test_limit_vertices_by_all_neighbours(self):
-        quantity = Quantity(self.mesh4)
-
-        #Create a deliberate overshoot (e.g. from gradient computation)
-        quantity.set_values([[3,0,3], [2,2,6], [5,3,8], [8,3,5]])
-
-
-        #Limit
-        quantity.limit_vertices_by_all_neighbours()
-
-        #Assert that central triangle is limited by neighbours
-        assert quantity.vertex_values[1,0] >= quantity.vertex_values[0,0]
-        assert quantity.vertex_values[1,0] <= quantity.vertex_values[3,1]
-
-        assert quantity.vertex_values[1,1] <= quantity.vertex_values[2,1]
-        assert quantity.vertex_values[1,1] >= quantity.vertex_values[0,2]
-
-        assert quantity.vertex_values[1,2] <= quantity.vertex_values[2,0]
-        assert quantity.vertex_values[1,2] <= quantity.vertex_values[3,1]
-
-
-
-        #Assert that quantities are conserved
-        for k in range(quantity.centroid_values.shape[0]):
-            assert num.allclose (quantity.centroid_values[k],
-                                 num.sum(quantity.vertex_values[k,:])/3)
-
-
-
-    def test_limit_edges_by_all_neighbours(self):
-        quantity = Quantity(self.mesh4)
-
-        #Create a deliberate overshoot (e.g. from gradient computation)
-        quantity.set_values([[3,0,3], [2,2,6], [5,3,8], [8,3,5]])
-
-
-        #Limit
-        quantity.limit_edges_by_all_neighbours()
-
-        #Assert that central triangle is limited by neighbours
-        assert quantity.edge_values[1,0] <= quantity.centroid_values[2]
-        assert quantity.edge_values[1,0] >= quantity.centroid_values[0]
-
-        assert quantity.edge_values[1,1] <= quantity.centroid_values[2]
-        assert quantity.edge_values[1,1] >= quantity.centroid_values[0]
-
-        assert quantity.edge_values[1,2] <= quantity.centroid_values[2]
-        assert quantity.edge_values[1,2] >= quantity.centroid_values[0]
-
-
-
-        #Assert that quantities are conserved
-        for k in range(quantity.centroid_values.shape[0]):
-            assert num.allclose (quantity.centroid_values[k],
-                                 num.sum(quantity.vertex_values[k,:])/3)
-
-
-    def test_limit_edges_by_neighbour(self):
-        quantity = Quantity(self.mesh4)
-
-        #Create a deliberate overshoot (e.g. from gradient computation)
-        quantity.set_values([[3,0,3], [2,2,6], [5,3,8], [8,3,5]])
-
-
-        #Limit
-        quantity.limit_edges_by_neighbour()
-
-        #Assert that central triangle is limited by neighbours
-        assert quantity.edge_values[1,0] <= quantity.centroid_values[3]
-        assert quantity.edge_values[1,0] >= quantity.centroid_values[1]
-
-        assert quantity.edge_values[1,1] <= quantity.centroid_values[2]
-        assert quantity.edge_values[1,1] >= quantity.centroid_values[1]
-
-        assert quantity.edge_values[1,2] <= quantity.centroid_values[1]
-        assert quantity.edge_values[1,2] >= quantity.centroid_values[0]
-
-
-
-        #Assert that quantities are conserved
-        for k in range(quantity.centroid_values.shape[0]):
-            assert num.allclose (quantity.centroid_values[k],
-                                 num.sum(quantity.vertex_values[k,:])/3)
-
-    def test_limiter2(self):
-        """Taken from test_shallow_water
-        """
-        quantity = Quantity(self.mesh4)
-        quantity.domain.beta_w = 0.9
-        
-        #Test centroids
-        quantity.set_values([2.,4.,8.,2.], location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [2, 4, 8, 2]) #Centroid
-
-
-        #Extrapolate
-        quantity.extrapolate_second_order()
-
-        assert num.allclose(quantity.vertex_values[1,:], [0.0, 6, 6])
-
-        #Limit
-        quantity.limit()
-
-        # limited value for beta_w = 0.9
-        
-        assert num.allclose(quantity.vertex_values[1,:], [2.2, 4.9, 4.9])
-        # limited values for beta_w = 0.5
-        #assert allclose(quantity.vertex_values[1,:], [3.0, 4.5, 4.5])
-
-
-        #Assert that quantities are conserved
-        for k in range(quantity.centroid_values.shape[0]):
-            assert num.allclose (quantity.centroid_values[k],
-                                 num.sum(quantity.vertex_values[k,:])/3)
-
-
-
-
-
-    def test_distribute_first_order(self):
-        quantity = Quantity(self.mesh4)
-
-        #Test centroids
-        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
-
-
-        #Extrapolate from centroid to vertices and edges
-        quantity.extrapolate_first_order()
-
-        #Interpolate
-        #quantity.interpolate_from_vertices_to_edges()
-
-        assert num.allclose(quantity.vertex_values,
-                            [[1,1,1], [2,2,2], [3,3,3], [4, 4, 4]])
-        assert num.allclose(quantity.edge_values, [[1,1,1], [2,2,2],
-                                                   [3,3,3], [4, 4, 4]])
-
-
-    def test_interpolate_from_vertices_to_edges(self):
-        quantity = Quantity(self.mesh4)
-
-        quantity.vertex_values = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.float)
-
-        quantity.interpolate_from_vertices_to_edges()
-
-        assert num.allclose(quantity.edge_values, [[1., 1.5, 0.5],
-                                                   [3., 2.5, 1.5],
-                                                   [3.5, 4.5, 3.],
-                                                   [2.5, 3.5, 2]])
-
-
-    def test_interpolate_from_edges_to_vertices(self):
-        quantity = Quantity(self.mesh4)
-
-        quantity.edge_values = num.array([[1., 1.5, 0.5],
-                                          [3., 2.5, 1.5],
-                                          [3.5, 4.5, 3.],
-                                          [2.5, 3.5, 2]], num.float)
-
-        quantity.interpolate_from_edges_to_vertices()
-
-        assert num.allclose(quantity.vertex_values,
-                            [[1,0,2], [1,2,4], [4,2,5], [3,1,4]])
-
-
-
-    def test_distribute_second_order(self):
-        quantity = Quantity(self.mesh4)
-
-        #Test centroids
-        quantity.set_values([2.,4.,8.,2.], location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [2, 4, 8, 2]) #Centroid
-
-
-        #Extrapolate
-        quantity.extrapolate_second_order()
-
-        assert num.allclose(quantity.vertex_values[1,:], [0.0, 6, 6])
-
-
-    def test_update_explicit(self):
-        quantity = Quantity(self.mesh4)
-
-        #Test centroids
-        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
-
-        #Set explicit_update
-        quantity.explicit_update = num.array( [1.,1.,1.,1.] )
-
-        #Update with given timestep
-        quantity.update(0.1)
-
-        x = num.array([1, 2, 3, 4]) + num.array( [.1,.1,.1,.1] )
-        assert num.allclose( quantity.centroid_values, x)
-
-    def test_update_semi_implicit(self):
-        quantity = Quantity(self.mesh4)
-
-        #Test centroids
-        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
-
-        #Set semi implicit update
-        quantity.semi_implicit_update = num.array([1.,1.,1.,1.])
-
-        #Update with given timestep
-        timestep = 0.1
-        quantity.update(timestep)
-
-        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
-        denom = num.ones(4, num.float)-timestep*sem
-
-        x = num.array([1, 2, 3, 4])/denom
-        assert num.allclose( quantity.centroid_values, x)
-
-
-    def test_both_updates(self):
-        quantity = Quantity(self.mesh4)
-
-        #Test centroids
-        quantity.set_values([1.,2.,3.,4.], location = 'centroids')
-        assert num.allclose(quantity.centroid_values, [1, 2, 3, 4]) #Centroid
-
-        #Set explicit_update
-        quantity.explicit_update = num.array( [4.,3.,2.,1.] )
-
-        #Set semi implicit update
-        quantity.semi_implicit_update = num.array( [1.,1.,1.,1.] )
-
-        #Update with given timestep
-        timestep = 0.1
-        quantity.update(0.1)
-
-        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
-        denom = num.ones(4, num.float)-timestep*sem
-
-        x = num.array([1., 2., 3., 4.])
-        x += timestep*num.array( [4.0, 3.0, 2.0, 1.0] )        
-        x /= denom
-
-
-        assert num.allclose( quantity.centroid_values, x)
-
-
-
-    def set_array_values_by_index(self):
-
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 1)
-
-        #Create shallow water domain
-        domain = Generic_Domain(points, vertices, boundary)
-        #print "domain.number_of_elements ",domain.number_of_elements
-        quantity = Quantity(domain,[[1,1,1],[2,2,2]])
-        value = [7]
-        indices = [1]
-        quantity.set_array_values_by_index(value,
-                                           location = 'centroids',
-                                           indices = indices)
-        #print "quantity.centroid_values",quantity.centroid_values
-
-        assert num.allclose(quantity.centroid_values, [1,7])
-
-        quantity.set_array_values([15,20,25], indices = indices)
-        assert num.allclose(quantity.centroid_values, [1,20])
-
-        quantity.set_array_values([15,20,25], indices = indices)
-        assert num.allclose(quantity.centroid_values, [1,20])
-
-    def test_setting_some_vertex_values(self):
-        """
-        set values based on triangle lists.
-        """
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-        #print "vertices",vertices
-        #Create shallow water domain
-        domain = Generic_Domain(points, vertices, boundary)
-        #print "domain.number_of_elements ",domain.number_of_elements
-        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5],[6,6,6]])
-
-
-        # Check that constants work
-        value = 7
-        indices = [1]
-        quantity.set_values(value,
-                            location = 'centroids',
-                            indices = indices)
-        #print "quantity.centroid_values",quantity.centroid_values
-        assert num.allclose(quantity.centroid_values, [1,7,3,4,5,6])
-        
-        value = [7]
-        indices = [1]
-        quantity.set_values(value,
-                            location = 'centroids',
-                            indices = indices)
-        #print "quantity.centroid_values",quantity.centroid_values
-        assert num.allclose(quantity.centroid_values, [1,7,3,4,5,6])
-
-        value = [[15,20,25]]
-        quantity.set_values(value, indices = indices)
-        #print "1 quantity.vertex_values",quantity.vertex_values
-        assert num.allclose(quantity.vertex_values[1], value[0])
-
-
-        #print "quantity",quantity.vertex_values
-        values = [10,100,50]
-        quantity.set_values(values, indices = [0,1,5], location = 'centroids')
-        #print "2 quantity.vertex_values",quantity.vertex_values
-        assert num.allclose(quantity.vertex_values[0], [10,10,10])
-        assert num.allclose(quantity.vertex_values[5], [50,50,50])
-        #quantity.interpolate()
-        #print "quantity.centroid_values",quantity.centroid_values
-        assert num.allclose(quantity.centroid_values, [10,100,3,4,5,50])
-
-
-        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5],[6,6,6]])
-        values = [10,100,50]
-        #this will be per unique vertex, indexing the vertices
-        #print "quantity.vertex_values",quantity.vertex_values
-        quantity.set_values(values, indices = [0,1,5])
-        #print "quantity.vertex_values",quantity.vertex_values
-        assert num.allclose(quantity.vertex_values[0], [1,50,10])
-        assert num.allclose(quantity.vertex_values[5], [6,6,6])
-        assert num.allclose(quantity.vertex_values[1], [100,10,50])
-
-        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5],[6,6,6]])
-        values = [[31,30,29],[400,400,400],[1000,999,998]]
-        quantity.set_values(values, indices = [3,3,5])
-        quantity.interpolate()
-        assert num.allclose(quantity.centroid_values, [1,2,3,400,5,999])
-
-        values = [[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5],[6,6,6]]
-        quantity.set_values(values)
-
-        # testing the standard set values by vertex
-        # indexed by vertex_id in general_mesh.coordinates
-        values = [0,1,2,3,4,5,6,7]
-
-        quantity.set_values(values)
-        #print "1 quantity.vertex_values",quantity.vertex_values
-        assert num.allclose(quantity.vertex_values,[[ 4.,  5.,  0.],
-                                                    [ 1.,  0.,  5.],
-                                                    [ 5.,  6.,  1.],
-                                                    [ 2.,  1.,  6.],
-                                                    [ 6.,  7.,  2.],
-                                                    [ 3.,  2.,  7.]])
-
-    def test_setting_unique_vertex_values(self):
-        """
-        set values based on unique_vertex lists.
-        """
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-        #print "vertices",vertices
-        #Create shallow water domain
-        domain = Generic_Domain(points, vertices, boundary)
-        #print "domain.number_of_elements ",domain.number_of_elements
-        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5]])
-        value = 7
-        indices = [1,5]
-        quantity.set_values(value,
-                            location='unique vertices',
-                            indices=indices)
-        #print "quantity.centroid_values",quantity.centroid_values
-        assert num.allclose(quantity.vertex_values[0], [0,7,0])
-        assert num.allclose(quantity.vertex_values[1], [7,1,7])
-        assert num.allclose(quantity.vertex_values[2], [7,2,7])
-
-
-    def test_get_values(self):
-        """
-        get values based on triangle lists.
-        """
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #print "points",points
-        #print "vertices",vertices
-        #print "boundary",boundary
-
-        #Create shallow water domain
-        domain = Generic_Domain(points, vertices, boundary)
-        #print "domain.number_of_elements ",domain.number_of_elements
-        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5]])
-
-        #print "quantity.get_values(location = 'unique vertices')", \
-        #      quantity.get_values(location = 'unique vertices')
-
-        #print "quantity.get_values(location = 'unique vertices')", \
-        #      quantity.get_values(indices=[0,1,2,3,4,5,6,7], \
-        #                          location = 'unique vertices')
-
-        answer = [0.5,2,4,5,0,1,3,4.5]
-        assert num.allclose(answer,
-                            quantity.get_values(location='unique vertices'))
-
-        indices = [0,5,3]
-        answer = [0.5,1,5]
-        assert num.allclose(answer,
-                            quantity.get_values(indices=indices,
-                                                location='unique vertices'))
-        #print "quantity.centroid_values",quantity.centroid_values
-        #print "quantity.get_values(location = 'centroids') ",\
-        #      quantity.get_values(location = 'centroids')
-
-
-
-
-    def test_get_values_2(self):
-        """Different mesh (working with domain object) - also check centroids.
-        """
-
-        
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        domain = Generic_Domain(points, vertices)
-
-        quantity = Quantity(domain)
-        quantity.set_values(lambda x, y: x+2*y) #2 4 4 6
-        
-        assert num.allclose(quantity.get_values(location='centroids'), 
-                            [2,4,4,6])
-                            
-        assert num.allclose(quantity.get_values(location='centroids', 
-                                                indices=[1,3]), [4,6])
-
-
-        assert num.allclose(quantity.get_values(location='vertices'), 
-                            [[4,0,2],
-                             [4,2,6],
-                             [6,2,4],
-                             [8,4,6]])
-        
-        assert num.allclose(quantity.get_values(location='vertices', 
-                                                indices=[1,3]), [[4,2,6],
-                                                                 [8,4,6]])
-
-
-        assert num.allclose(quantity.get_values(location='edges'), 
-                            [[1,3,2],
-                             [4,5,3],
-                             [3,5,4],
-                             [5,7,6]])
-        assert num.allclose(quantity.get_values(location='edges', 
-                                                indices=[1,3]),
-                            [[4,5,3],
-                             [5,7,6]])        
-
-        # Check averaging over vertices
-        #a: 0
-        #b: (4+4+4)/3
-        #c: (2+2+2)/3
-        #d: 8
-        #e: (6+6+6)/3        
-        #f: 4
-        assert num.allclose(quantity.get_values(location='unique vertices'), 
-                            [0, 4, 2, 8, 6, 4]) 
-
-
-
-    def test_get_interpolated_values(self):
-
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-        domain = Generic_Domain(points, vertices, boundary)
-
-        #Constant values
-        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5]])
-
-        
-
-        # Get interpolated values at centroids
-        interpolation_points = domain.get_centroid_coordinates()
-        answer = quantity.get_values(location='centroids')
-
-        
-        #print quantity.get_values(points=interpolation_points)
-        assert num.allclose(answer, quantity.get_values(interpolation_points=interpolation_points))
-
-
-        #Arbitrary values
-        quantity = Quantity(domain,[[0,1,2],[3,1,7],[2,1,2],[3,3,7],
-                                    [1,4,-9],[2,5,0]])
-
-
-        # Get interpolated values at centroids
-        interpolation_points = domain.get_centroid_coordinates()
-        answer = quantity.get_values(location='centroids')
-        #print answer
-        #print quantity.get_values(interpolation_points=interpolation_points)
-        assert num.allclose(answer, 
-                            quantity.get_values(interpolation_points=interpolation_points,
-                                                verbose=False))        
-                        
-
-        #FIXME TODO
-        #indices = [0,5,3]
-        #answer = [0.5,1,5]
-        #assert allclose(answer,
-        #                quantity.get_values(indices=indices, \
-        #                                    location = 'unique vertices'))
-
-
-
-
-    def test_get_interpolated_values_2(self):
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        domain = Generic_Domain(points, vertices)
-
-        quantity = Quantity(domain)
-        quantity.set_values(lambda x, y: x+2*y) #2 4 4 6
-
-        #First pick one point
-        x, y = 2.0/3, 8.0/3
-        v = quantity.get_values(interpolation_points = [[x,y]])
-        assert num.allclose(v, 6)        
-
-        # Then another to test that algorithm won't blindly
-        # reuse interpolation matrix
-        x, y = 4.0/3, 4.0/3
-        v = quantity.get_values(interpolation_points = [[x,y]])
-        assert num.allclose(v, 4)        
-
-
-
-    def test_get_interpolated_values_with_georef(self):
-    
-        zone = 56
-        xllcorner = 308500
-        yllcorner = 6189000
-        a = [0.0, 0.0]
-        b = [0.0, 2.0]
-        c = [2.0,0.0]
-        d = [0.0, 4.0]
-        e = [2.0, 2.0]
-        f = [4.0,0.0]
-
-        points = [a, b, c, d, e, f]
-        #bac, bce, ecf, dbe
-        vertices = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
-
-        domain = Generic_Domain(points, vertices,
-                        geo_reference=Geo_reference(zone,xllcorner,yllcorner))
-
-        quantity = Quantity(domain)
-        quantity.set_values(lambda x, y: x+2*y) #2 4 4 6
-
-        #First pick one point (and turn it into absolute coordinates)
-        x, y = 2.0/3, 8.0/3
-        v = quantity.get_values(interpolation_points = [[x+xllcorner,y+yllcorner]])
-        assert num.allclose(v, 6)
-        
-
-        # Then another to test that algorithm won't blindly
-        # reuse interpolation matrix 
-        x, y = 4.0/3, 4.0/3
-        v = quantity.get_values(interpolation_points = [[x+xllcorner,y+yllcorner]])
-        assert num.allclose(v, 4)        
-        
-        # Try two points
-        pts = [[2.0/3 + xllcorner, 8.0/3 + yllcorner], 
-               [4.0/3 + xllcorner, 4.0/3 + yllcorner]]         
-        v = quantity.get_values(interpolation_points=pts)
-        assert num.allclose(v, [6, 4])               
-        
-        # Test it using the geospatial data format with absolute input points and default georef
-        pts = Geospatial_data(data_points=pts)
-        v = quantity.get_values(interpolation_points=pts)
-        assert num.allclose(v, [6, 4])                                
-        
-        
-        # Test it using the geospatial data format with relative input points
-        pts = Geospatial_data(data_points=[[2.0/3, 8.0/3], [4.0/3, 4.0/3]], 
-                              geo_reference=Geo_reference(zone,xllcorner,yllcorner))
-        v = quantity.get_values(interpolation_points=pts)
-        assert num.allclose(v, [6, 4])                        
-        
-        
-        
-
-    def test_getting_some_vertex_values(self):
-        """
-        get values based on triangle lists.
-        """
-        from mesh_factory import rectangular
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #print "points",points
-        #print "vertices",vertices
-        #print "boundary",boundary
-
-        #Create shallow water domain
-        domain = Generic_Domain(points, vertices, boundary)
-        #print "domain.number_of_elements ",domain.number_of_elements
-        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5],[6,6,6]])
-        value = [7]
-        indices = [1]
-        quantity.set_values(value,
-                            location = 'centroids',
-                            indices = indices)
-        #print "quantity.centroid_values",quantity.centroid_values
-        #print "quantity.get_values(location = 'centroids') ",\
-        #      quantity.get_values(location = 'centroids')
-        assert num.allclose(quantity.centroid_values,
-                            quantity.get_values(location = 'centroids'))
-
-
-        value = [[15,20,25]]
-        quantity.set_values(value, indices = indices)
-        #print "1 quantity.vertex_values",quantity.vertex_values
-        assert num.allclose(quantity.vertex_values, quantity.get_values())
-
-        assert num.allclose(quantity.edge_values,
-                            quantity.get_values(location = 'edges'))
-
-        # get a subset of elements
-        subset = quantity.get_values(location='centroids', indices=[0,5])
-        answer = [quantity.centroid_values[0],quantity.centroid_values[5]]
-        assert num.allclose(subset, answer)
-
-
-        subset = quantity.get_values(location='edges', indices=[0,5])
-        answer = [quantity.edge_values[0],quantity.edge_values[5]]
-        #print "subset",subset
-        #print "answer",answer
-        assert num.allclose(subset, answer)
-
-        subset = quantity.get_values( indices=[1,5])
-        answer = [quantity.vertex_values[1],quantity.vertex_values[5]]
-        #print "subset",subset
-        #print "answer",answer
-        assert num.allclose(subset, answer)
-
-    def test_smooth_vertex_values(self):
-        """
-        get values based on triangle lists.
-        """
-        from mesh_factory import rectangular
-      #  from anuga.shallow_water.shallow_water_domain import Domain
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(2, 2)
-
-        #print "points",points
-        #print "vertices",vertices
-        #print "boundary",boundary
-
-        #Create shallow water domain
-        domain = Generic_Domain(points, vertices, boundary)
-        #print "domain.number_of_elements ",domain.number_of_elements
-        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
-                                    [4,4,4],[5,5,5],[6,6,6],[7,7,7]])
-
-        #print "quantity.get_values(location = 'unique vertices')", \
-        #      quantity.get_values(location = 'unique vertices')
-
-        #print "quantity.get_values(location = 'unique vertices')", \
-        #      quantity.get_values(indices=[0,1,2,3,4,5,6,7], \
-        #                          location = 'unique vertices')
-
-        #print quantity.get_values(location = 'unique vertices')
-        #print quantity.domain.number_of_triangles_per_node
-        #print quantity.vertex_values
-        
-        #answer = [0.5, 2, 3, 3, 3.5, 4, 4, 5, 6.5]
-        #assert allclose(answer,
-        #                quantity.get_values(location = 'unique vertices'))
-
-        quantity.smooth_vertex_values()
-
-        #print quantity.vertex_values
-
-
-        answer_vertex_values = [[3,3.5,0.5],[2,0.5,3.5],[3.5,4,2],[3,2,4],
-                                [4,5,3],[3.5,3,5],[5,6.5,3.5],[4,3.5,6.5]]
-        
-        assert num.allclose(answer_vertex_values,
-                            quantity.vertex_values)
-                            
-        # Just another (slightly larger) test of get_values
-
-        assert num.allclose(quantity.get_values(location='centroids'),
-                            quantity.centroid_values)
-                            
-                            
-        assert num.allclose(quantity.get_values(location='vertices'),
-                            quantity.vertex_values)                            
-                            
-        assert num.allclose(quantity.get_values(location='edges'),
-                            quantity.edge_values)
-                            
-
-    def test_maximum(self):
-        quantity = Quantity(self.mesh4)
-
-        # get referece to data arrays
-        centroid_values = quantity.centroid_values
-        vertex_values = quantity.vertex_values
-        edge_values = quantity.edge_values
-
-        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
-                            location = 'vertices')
-        assert num.allclose(quantity.vertex_values,
-                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-
-        assert id(vertex_values) == id(quantity.vertex_values)
-        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
-        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
-                                                   [5., 5., 5.],
-                                                   [4.5, 4.5, 0.],
-                                                   [3.0, -1.5, -1.5]])
-
-
-
-        other_quantity = Quantity(self.mesh4)
-
-        other_quantity.set_values([[0,0,0], [1,1,6], [10,10,10], [0,0,4]],
-                            location = 'vertices')
-
- 
-        #===============================
-        quantity.maximum(other_quantity)
-        #===============================
-
-        exact_vertex_values = num.array([[  1.,   2.,   3.],
-                                         [  5.,   5.,  6.],
-                                         [ 10.,  10.,  10.],
-                                         [  0.,   3.,  4.]])
-        exact_centroid_values = num.array([  2.,  5., 10.,  1.33333333])
-        exact_edge_values = num.array([[  2.5,   2.,    1.5],
-                                       [  5.,   5.,   5., ],
-                                       [ 10.,   10.,  10. ],
-                                       [  3.,    2.,    0. ]])
-
-
-        
-        assert num.allclose(quantity.vertex_values,
-                            exact_vertex_values)
-        assert num.allclose(quantity.centroid_values, exact_centroid_values) #Centroid
-        assert num.allclose(quantity.edge_values, exact_edge_values)
-
-    def test_minimum(self):
-        quantity = Quantity(self.mesh4)
-
-        # get referece to data arrays
-        centroid_values = quantity.centroid_values
-        vertex_values = quantity.vertex_values
-        edge_values = quantity.edge_values
-
-        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]],
-                            location = 'vertices')
-        assert num.allclose(quantity.vertex_values,
-                            [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
-
-        assert id(vertex_values) == id(quantity.vertex_values)
-        assert num.allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
-        assert num.allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
-                                                   [5., 5., 5.],
-                                                   [4.5, 4.5, 0.],
-                                                   [3.0, -1.5, -1.5]])
-
-
-
-        other_quantity = Quantity(self.mesh4)
-
-        other_quantity.set_values([[0,0,0], [1,1,6], [10,10,10], [0,0,4]],
-                            location = 'vertices')
-
-
-        #===============================
-        quantity.minimum(other_quantity)
-        #===============================
-
-        exact_vertex_values = num.array([[  0.,   0.,   0.],
-                                         [  1.,   1.,  5.],
-                                         [  0.,   0.,  9.],
-                                         [ -6.,   0.,  3.]])
-        exact_centroid_values = num.array([  0.,  2.66666667, 3.,  0.])
-        exact_edge_values = num.array([[  0.,   0.,   0.],
-                                       [  3.5,   3.5,   1., ],
-                                       [  4.5,   4.5,   0. ],
-                                       [  2.,   -1.5,  -1.5 ]])
-
-
-        assert num.allclose(quantity.vertex_values,
-                            exact_vertex_values)
-        assert num.allclose(quantity.centroid_values, exact_centroid_values) #Centroid
-        assert num.allclose(quantity.edge_values, exact_edge_values)
-
-
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_Quantity, 'test') #_set_values_from_asc')
-    runner = unittest.TextTestRunner(verbosity=1)
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_region.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_region.py	(revision 9459)
+++ 	(revision )
@@ -1,99 +1,0 @@
-#!/usr/bin/env python
-
-import unittest
-from math import sqrt
-
-from mesh_factory import rectangular
-from anuga.shallow_water.shallow_water_domain import Domain
-from generic_domain import Generic_Domain
-from region import *
-#from anuga.config import epsilon
-
-import numpy as num
-
-
-"""
-This is what the mesh in these tests look like;
-
-3---7
-|5 /|
-| /6|
-2---6
-|3 /|
-| /2|
-1---5
-|1 /|
-| /0|
-0---4
-"""
-
-def add_x_y(x, y):
-    return x+y
-
-def give_me_23(x, y):
-    return 23.0
-
-class Test_region(unittest.TestCase):
-    def setUp(self):
-        pass
-
-
-    def tearDown(self):
-        pass
-
-
-    def test_region_indices(self):
-        """create region based on triangle lists."""
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #Create shallow water domain
-        domain = Domain(points, vertices, boundary)
-        
-        region = Region(domain, indices=[0,2,3])
-
-        expected_indices = [0,2,3]  
-        assert num.allclose(region.indices, expected_indices)
-        
-
-    def test_region_polygon(self):
-        """create region based on triangle lists."""
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #Create shallow water domain
-        domain = Domain(points, vertices, boundary)
-        
-        poly = [[0.0,0.0], [0.5,0.0], [0.5,0.5]]
-        
-        #print poly
-        region = Region(domain, polygon=poly)
-        
-        expected_indices = [1]
-        assert num.allclose(region.indices, expected_indices)
-
-
-    def test_region_polygon_expanded(self):
-        """create region based on triangle lists."""
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #Create shallow water domain
-        domain = Domain(points, vertices, boundary)
-        
-        region = Region(domain, polygon=[[0.0,0.0], [0.5,0.0], [0.5,0.5]], expand_polygon=True)
-        
-        expected_indices = [0,1,2,3]
-        assert num.allclose(region.indices, expected_indices)
-
-        
-                  
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_region, 'test')    
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_tag_region.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_tag_region.py	(revision 9459)
+++ 	(revision )
@@ -1,258 +1,0 @@
-#!/usr/bin/env python
-
-import unittest
-from math import sqrt
-
-from mesh_factory import rectangular
-from anuga.shallow_water.shallow_water_domain import Domain
-from generic_domain import Generic_Domain
-from tag_region import *
-#from anuga.config import epsilon
-
-import numpy as num
-
-
-"""
-This is what the mesh in these tests look like;
-
-3---7
-|5 /|
-| /6|
-2---6
-|3 /|
-| /2|
-1---5
-|1 /|
-| /0|
-0---4
-"""
-
-def add_x_y(x, y):
-    return x+y
-
-def give_me_23(x, y):
-    return 23.0
-
-class Test_tag_region(unittest.TestCase):
-    def setUp(self):
-        pass
-
-
-    def tearDown(self):
-        pass
-
-
-    def test_region_tags(self):
-        """get values based on triangle lists."""
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #Create shallow water domain
-        domain = Domain(points, vertices, boundary)
-        domain.build_tagged_elements_dictionary({'bottom': [0,1],
-                                                 'top': [4,5],
-                                                 'all': [0,1,2,3,4,5]})
-
-        #Set friction
-        manning = 0.07
-        domain.set_quantity('friction', manning)
-
-        a = Set_tag_region('bottom', 'friction', 0.09)
-        b = Set_tag_region('top', 'friction', 1.0)
-        domain.set_tag_region([a, b])
-
-        expected = [[ 0.09,  0.09,  0.09],
-                    [ 0.09,  0.09,  0.09],
-                    [ 0.07,  0.07,  0.07],
-                    [ 0.07,  0.07,  0.07],
-                    [ 1.0,   1.0,   1.0],
-                    [ 1.0,   1.0,   1.0]]
-        msg = ("\ndomain.quantities['friction']=%s\nexpected value=%s"
-               % (str(domain.quantities['friction'].get_values()),
-                  str(expected)))
-        assert num.allclose(domain.quantities['friction'].get_values(),
-                            expected), msg
-
-        #c = Add_Value_To_region('all', 'friction', 10.0)
-        domain.set_tag_region(Add_value_to_region('all', 'friction', 10.0))
-        #print domain.quantities['friction'].get_values()
-        assert num.allclose(domain.quantities['friction'].get_values(),
-                            [[ 10.09, 10.09, 10.09],
-                             [ 10.09, 10.09, 10.09],
-                             [ 10.07, 10.07, 10.07],
-                             [ 10.07, 10.07, 10.07],
-                             [ 11.0,  11.0,  11.0],
-                             [ 11.0,  11.0,  11.0]])
-
-        # trying a function
-        domain.set_tag_region(Set_tag_region('top', 'friction', add_x_y))
-        #print domain.quantities['friction'].get_values()
-        assert num.allclose(domain.quantities['friction'].get_values(),
-                            [[ 10.09, 10.09, 10.09],
-                             [ 10.09, 10.09, 10.09],
-                             [ 10.07, 10.07, 10.07],
-                             [ 10.07, 10.07, 10.07],
-                             [ 5./3,  2.0,  2./3],
-                             [ 1.0,  2./3,  2.0]])
-
-        domain.set_quantity('elevation', 10.0)
-        domain.set_quantity('stage', 10.0)
-        domain.set_tag_region(Add_value_to_region('top', 'stage', 1.0,initial_quantity='elevation'))
-        #print domain.quantities['stage'].get_values()
-        assert num.allclose(domain.quantities['stage'].get_values(),
-                            [[ 10., 10., 10.],
-                             [ 10., 10., 10.],
-                             [ 10., 10., 10.],
-                             [ 10., 10., 10.],
-                             [ 11.0,  11.0,  11.0],
-                             [ 11.0,  11.0,  11.0]])
-
-        
-        domain.set_quantity('elevation', 10.0)
-        domain.set_quantity('stage', give_me_23)
-        #this works as well, (is cleaner, but doesn't work for regions)
-        #domain.set_quantity('stage',
-        #                    domain.quantities['stage'].vertex_values+ \
-        #                    domain.quantities['elevation'].vertex_values)
-        domain.set_tag_region(Add_quantities('top', 'elevation','stage'))
-        #print domain.quantities['stage'].get_values()
-        assert num.allclose(domain.quantities['elevation'].get_values(),
-                            [[ 10., 10., 10.],
-                             [ 10., 10., 10.],
-                             [ 10., 10., 10.],
-                             [ 10., 10., 10.],
-                             [ 33.,  33.0,  33.],
-                             [ 33.0,  33.,  33.]])
-        
-    def test_unique_vertices(self):
-        """get values based on triangle lists."""
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #Create shallow water domain
-        domain = Domain(points, vertices, boundary)
-        domain.build_tagged_elements_dictionary({'bottom':[0,1],
-                                                 'top':[4,5],
-                                                 'all':[0,1,2,3,4,5]})
-
-        #Set friction
-        manning = 0.07
-        domain.set_quantity('friction', manning)
-
-        a = Set_tag_region('bottom', 'friction', 0.09, location = 'unique vertices')
-        domain.set_tag_region(a)
-        assert num.allclose(domain.quantities['friction'].get_values(),
-                            [[ 0.09,  0.09,  0.09],
-                             [ 0.09,  0.09,  0.09],
-                             [ 0.09,  0.07,  0.09],
-                             [ 0.07,  0.09,  0.07],
-                             [ 0.07,  0.07,  0.07],
-                             [ 0.07,  0.07,  0.07]])
-
-
-    def test_unique_verticesII(self):
-        """
-        get values based on triangle lists.
-        """
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #Create shallow water domain
-        domain = Domain(points, vertices, boundary)
-        domain.build_tagged_elements_dictionary({'bottom':[0,1],
-                                                 'top':[4,5],
-                                                 'all':[0,1,2,3,4,5]})
-
-        #Set friction
-        manning = 0.07
-        domain.set_quantity('friction', manning)
-
-        domain.set_tag_region(Add_value_to_region('bottom', 'friction', 1.0,initial_quantity='friction', location = 'unique vertices'))
-
-        #print domain.quantities['friction'].get_values()
-        assert num.allclose(domain.quantities['friction'].get_values(),\
-                            [[ 1.07,  1.07,  1.07],
-                             [ 1.07,  1.07,  1.07],
-                             [ 1.07,  0.07,  1.07],
-                             [ 0.07,  1.07,  0.07],
-                             [ 0.07,  0.07,  0.07],
-                             [ 0.07,  0.07,  0.07]])
-                         
-    def test_unique_vertices_average_loc_vert(self):
-        """Get values based on triangle lists."""
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-
-        #Create shallow water domain
-        domain = Domain(points, vertices, boundary)
-        domain.build_tagged_elements_dictionary({'bottom': [0, 1],
-                                                 'top': [4, 5],
-                                                 'not_bottom': [2, 3, 4, 5]})
-
-        #Set friction
-        domain.set_quantity('friction', add_x_y)
-        av_bottom = 2.0 / 3.0
-        add = 60.0
-        calc_frict = av_bottom + add
-        domain.set_tag_region(Add_value_to_region('bottom', 'friction', add,
-                                              initial_quantity='friction',
-                                              location='vertices',
-                                              average=True))
-
-        frict_points = domain.quantities['friction'].get_values()
-
-        expected = [calc_frict, calc_frict, calc_frict]
-        msg = ('frict_points[0]=%s\nexpected=%s'
-               % (str(frict_points[0]), str(expected)))
-        assert num.allclose(frict_points[0], expected), msg
-
-        msg = ('frict_points[1]=%s\nexpected=%s'
-               % (str(frict_points[1]), str(expected)))
-        assert num.allclose(frict_points[1], expected), msg
-  
-    def test_unique_vertices_average_loc_unique_vert(self):
-        """
-        get values based on triangle lists.
-        """
-
-        #Create basic mesh
-        points, vertices, boundary = rectangular(1, 3)
-        #Create shallow water domain
-        domain = Domain(points, vertices, boundary)
-        domain.build_tagged_elements_dictionary({'bottom':[0,1],
-                                                 'top':[4,5],
-                                                 'not_bottom':[2,3,4,5]})
-
-        #Set friction
-        domain.set_quantity('friction', add_x_y)
-        av_bottom = 2.0/3.0
-        add = 60.0
-        calc_frict = av_bottom + add
-        domain.set_tag_region(Add_value_to_region('bottom', 'friction', add,
-                          initial_quantity='friction',
-                           location='unique vertices',
-                           average=True
-                          ))
-
-        #print domain.quantities['friction'].get_values()
-        frict_points = domain.quantities['friction'].get_values()
-        assert num.allclose(frict_points[0],\
-                            [ calc_frict, calc_frict, calc_frict])
-        assert num.allclose(frict_points[1],\
-                            [ calc_frict, calc_frict, calc_frict])
-        assert num.allclose(frict_points[2],\
-                            [ calc_frict, 1.0 + 2.0/3.0, calc_frict])
-        assert num.allclose(frict_points[3],\
-                            [ 2.0/3.0,calc_frict, 1.0 + 2.0/3.0])
-                                                
-                         
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_tag_region, 'test')    
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
Index: unk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_util.py
===================================================================
--- /trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_util.py	(revision 9459)
+++ 	(revision )
@@ -1,1624 +1,0 @@
-#!/usr/bin/env python
-
-
-import unittest
-from math import sqrt, pi
-import tempfile, os
-from os import access, F_OK,sep, removedirs,remove,mkdir,getcwd
-
-from anuga.abstract_2d_finite_volumes.util import *
-from anuga.config import epsilon
-from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
-from anuga.file_conversion.file_conversion import timefile2netcdf
-from anuga.utilities.file_utils import del_dir
-
-from anuga.utilities.numerical_tools import NAN
-
-from sys import platform 
-
-from anuga.pmesh.mesh import Mesh
-import time
-from mesh_factory import rectangular
-from anuga.coordinate_transforms.geo_reference import Geo_reference
-from anuga.shallow_water.shallow_water_domain import Domain
-from generic_boundary_conditions import \
-                                Transmissive_boundary, Dirichlet_boundary
-from anuga.file.sww import SWW_file
-from csv import reader,writer
-import time
-import string
-
-import numpy as num
-
-
-def simple_function(x, y):
-    return x+y
-
-class Test_Util(unittest.TestCase):
-    def setUp(self):
-        pass
-
-    def tearDown(self):
-        pass
-
-
-
-
-    #Geometric
-    #def test_distance(self):
-    #    from anuga.abstract_2d_finite_volumes.util import distance#
-    #
-    #    self.failUnless( distance([4,2],[7,6]) == 5.0,
-    #                     'Distance is wrong!')
-    #    self.failUnless( allclose(distance([7,6],[9,8]), 2.82842712475),
-    #                    'distance is wrong!')
-    #    self.failUnless( allclose(distance([9,8],[4,2]), 7.81024967591),
-    #                    'distance is wrong!')
-    #
-    #    self.failUnless( distance([9,8],[4,2]) == distance([4,2],[9,8]),
-    #                    'distance is wrong!')
-
-
-    def test_file_function_time1(self):
-        """Test that File function interpolates correctly
-        between given times. No x,y dependency here.
-        """
-
-        #Write file
-        import os, time
-        from anuga.config import time_format
-        from math import sin, pi
-
-        #Typical ASCII file
-        finaltime = 1200
-        filename = 'test_file_function'
-        fid = open(filename + '.txt', 'w')
-        start = time.mktime(time.strptime('2000', '%Y'))
-        dt = 60  #One minute intervals
-        t = 0.0
-        while t <= finaltime:
-            t_string = time.strftime(time_format, time.gmtime(t+start))
-            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
-            t += dt
-
-        fid.close()
-
-        #Convert ASCII file to NetCDF (Which is what we really like!)
-        timefile2netcdf(filename+'.txt')
-
-
-        #Create file function from time series
-        F = file_function(filename + '.tms',
-                          quantities = ['Attribute0',
-                                        'Attribute1',
-                                        'Attribute2'])
-        
-        #Now try interpolation
-        for i in range(20):
-            t = i*10
-            q = F(t)
-
-            #Exact linear intpolation
-            assert num.allclose(q[0], 2*t)
-            if i%6 == 0:
-                assert num.allclose(q[1], t**2)
-                assert num.allclose(q[2], sin(t*pi/600))
-
-        #Check non-exact
-
-        t = 90 #Halfway between 60 and 120
-        q = F(t)
-        assert num.allclose( (120**2 + 60**2)/2, q[1] )
-        assert num.allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
-
-
-        t = 100 #Two thirds of the way between between 60 and 120
-        q = F(t)
-        assert num.allclose( 2*120**2/3 + 60**2/3, q[1] )
-        assert num.allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
-
-        os.remove(filename + '.txt')
-        os.remove(filename + '.tms')        
-
-
-        
-    def test_spatio_temporal_file_function_basic(self):
-        """Test that spatio temporal file function performs the correct
-        interpolations in both time and space
-        NetCDF version (x,y,t dependency)        
-        """
-        import time
-
-        #Create sww file of simple propagation from left to right
-        #through rectangular domain
-
-        #Create basic mesh and shallow water domain
-        points, vertices, boundary = rectangular(3, 3)
-        domain1 = Domain(points, vertices, boundary)
-
-        from anuga.utilities.numerical_tools import mean
-        domain1.reduction = mean
-        domain1.smooth = True #NOTE: Mimic sww output where each vertex has
-                              # only one value.
-
-        domain1.default_order = 2
-        domain1.store = True
-        domain1.set_datadir('.')
-        sww_file = 'spatio_temporal_boundary_source_%d' %(id(self))
-        domain1.set_name(sww_file)
-
-        #Bed-slope, friction and IC at vertices (and interpolated elsewhere)
-        domain1.set_quantity('elevation', 0)
-        domain1.set_quantity('friction', 0)
-        domain1.set_quantity('stage', 0)
-
-        # Boundary conditions
-        B0 = Dirichlet_boundary([0,0,0])
-        B6 = Dirichlet_boundary([0.6,0,0])
-        domain1.set_boundary({'left': B6, 'top': B6, 'right': B0, 'bottom': B0})
-        domain1.check_integrity()
-
-        finaltime = 8
-        #Evolution
-        t0 = -1
-        for t in domain1.evolve(yieldstep = 0.1, finaltime = finaltime):
-            #print 'Timesteps: %.16f, %.16f' %(t0, t)
-            #if t == t0:
-            #    msg = 'Duplicate timestep found: %f, %f' %(t0, t)
-            #   raise Exception(msg)
-            t0 = t
-             
-            #domain1.write_time()
-
-
-        #Now read data from sww and check
-        from anuga.file.netcdf import NetCDFFile
-        filename = domain1.get_name() + '.sww'
-        fid = NetCDFFile(filename)
-
-        x = fid.variables['x'][:]
-        y = fid.variables['y'][:]
-        stage = fid.variables['stage'][:]
-        xmomentum = fid.variables['xmomentum'][:]
-        ymomentum = fid.variables['ymomentum'][:]
-        time = fid.variables['time'][:]
-
-        #Take stage vertex values at last timestep on diagonal
-        #Diagonal is identified by vertices: 0, 5, 10, 15
-
-        last_time_index = len(time)-1 #Last last_time_index
-        d_stage = num.reshape(num.take(stage[last_time_index, :],
-                                       [0,5,10,15],
-                                       axis=0),
-                              (4,1))
-        d_uh = num.reshape(num.take(xmomentum[last_time_index, :],
-                                    [0,5,10,15],
-                                   axis=0),
-                           (4,1))
-        d_vh = num.reshape(num.take(ymomentum[last_time_index, :],
-                                    [0,5,10,15],
-                                   axis=0),
-                           (4,1))
-        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0 = (D[0] + D[1])/2
-        r1 = (D[1] + D[2])/2
-        r2 = (D[2] + D[3])/2
-
-        #And the midpoints are found now
-        Dx = num.take(num.reshape(x, (16,1)), [0,5,10,15], axis=0)
-        Dy = num.take(num.reshape(y, (16,1)), [0,5,10,15], axis=0)
-
-        diag = num.concatenate( (Dx, Dy), axis=1)
-        d_midpoints = (diag[1:] + diag[:-1])/2
-
-        #Let us see if the file function can find the correct
-        #values at the midpoints at the last timestep:
-        f = file_function(filename, domain1,
-                          interpolation_points = d_midpoints)
-
-        T = f.get_time()
-        msg = 'duplicate timesteps: %.16f and %.16f' %(T[-1], T[-2])
-        assert not T[-1] == T[-2], msg
-        t = time[last_time_index]
-        q = f(t, point_id=0); assert num.allclose(r0, q)
-        q = f(t, point_id=1); assert num.allclose(r1, q)
-        q = f(t, point_id=2); assert num.allclose(r2, q)
-
-
-        ##################
-        #Now do the same for the first timestep
-
-        timestep = 0 #First timestep
-        d_stage = num.reshape(num.take(stage[timestep, :], [0,5,10,15], axis=0), (4,1))
-        d_uh = num.reshape(num.take(xmomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
-        d_vh = num.reshape(num.take(ymomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
-        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0 = (D[0] + D[1])/2
-        r1 = (D[1] + D[2])/2
-        r2 = (D[2] + D[3])/2
-
-        #Let us see if the file function can find the correct
-        #values
-        q = f(0, point_id=0); assert num.allclose(r0, q)
-        q = f(0, point_id=1); assert num.allclose(r1, q)
-        q = f(0, point_id=2); assert num.allclose(r2, q)
-
-
-        ##################
-        #Now do it again for a timestep in the middle
-
-        timestep = 33
-        d_stage = num.reshape(num.take(stage[timestep, :], [0,5,10,15], axis=0), (4,1))
-        d_uh = num.reshape(num.take(xmomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
-        d_vh = num.reshape(num.take(ymomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
-        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0 = (D[0] + D[1])/2
-        r1 = (D[1] + D[2])/2
-        r2 = (D[2] + D[3])/2
-
-        q = f(timestep/10., point_id=0); assert num.allclose(r0, q)
-        q = f(timestep/10., point_id=1); assert num.allclose(r1, q)
-        q = f(timestep/10., point_id=2); assert num.allclose(r2, q)
-
-
-        ##################
-        #Now check temporal interpolation
-        #Halfway between timestep 15 and 16
-
-        timestep = 15
-        d_stage = num.reshape(num.take(stage[timestep, :], [0,5,10,15], axis=0), (4,1))
-        d_uh = num.reshape(num.take(xmomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
-        d_vh = num.reshape(num.take(ymomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
-        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0_0 = (D[0] + D[1])/2
-        r1_0 = (D[1] + D[2])/2
-        r2_0 = (D[2] + D[3])/2
-
-        #
-        timestep = 16
-        d_stage = num.reshape(num.take(stage[timestep, :], [0,5,10,15], axis=0), (4,1))
-        d_uh = num.reshape(num.take(xmomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
-        d_vh = num.reshape(num.take(ymomentum[timestep, :], [0,5,10,15], axis=0), (4,1))
-        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0_1 = (D[0] + D[1])/2
-        r1_1 = (D[1] + D[2])/2
-        r2_1 = (D[2] + D[3])/2
-
-        # The reference values are
-        r0 = (r0_0 + r0_1)/2
-        r1 = (r1_0 + r1_1)/2
-        r2 = (r2_0 + r2_1)/2
-
-        q = f((timestep - 0.5)/10., point_id=0); assert num.allclose(r0, q)
-        q = f((timestep - 0.5)/10., point_id=1); assert num.allclose(r1, q)
-        q = f((timestep - 0.5)/10., point_id=2); assert num.allclose(r2, q)
-
-        ##################
-        #Finally check interpolation 2 thirds of the way
-        #between timestep 15 and 16
-
-        # The reference values are
-        r0 = (r0_0 + 2*r0_1)/3
-        r1 = (r1_0 + 2*r1_1)/3
-        r2 = (r2_0 + 2*r2_1)/3
-
-        #And the file function gives
-        q = f((timestep - 1.0/3)/10., point_id=0); assert num.allclose(r0, q)
-        q = f((timestep - 1.0/3)/10., point_id=1); assert num.allclose(r1, q)
-        q = f((timestep - 1.0/3)/10., point_id=2); assert num.allclose(r2, q)
-
-        fid.close()
-        import os
-        os.remove(filename)
-
-
-
-    def test_spatio_temporal_file_function_different_origin(self):
-        """Test that spatio temporal file function performs the correct
-        interpolations in both time and space where space is offset by
-        xllcorner and yllcorner
-        NetCDF version (x,y,t dependency)        
-        """
-        xllcorner = 2048
-        yllcorner = 11000
-        zone = 2
-
-        #Create basic mesh and shallow water domain
-        points, vertices, boundary = rectangular(3, 3)
-        domain1 = Domain(points, vertices, boundary,
-                         geo_reference = Geo_reference(xllcorner = xllcorner,
-                                                       yllcorner = yllcorner))
-        
-
-        from anuga.utilities.numerical_tools import mean        
-        domain1.reduction = mean
-        domain1.smooth = True #NOTE: Mimic sww output where each vertex has
-                              # only one value.
-
-        domain1.default_order = 2
-        domain1.store = True
-        domain1.set_datadir('.')
-        domain1.set_name('spatio_temporal_boundary_source_%d' %(id(self)))
-
-        #Bed-slope, friction and IC at vertices (and interpolated elsewhere)
-        domain1.set_quantity('elevation', 0)
-        domain1.set_quantity('friction', 0)
-        domain1.set_quantity('stage', 0)
-
-        # Boundary conditions
-        B0 = Dirichlet_boundary([0,0,0])
-        B6 = Dirichlet_boundary([0.6,0,0])
-        domain1.set_boundary({'left': B6, 'top': B6, 'right': B0, 'bottom': B0})
-        domain1.check_integrity()
-
-        finaltime = 8
-        #Evolution
-        for t in domain1.evolve(yieldstep = 0.1, finaltime = finaltime):
-            pass
-            #domain1.write_time()
-
-
-        #Now read data from sww and check
-        from anuga.file.netcdf import NetCDFFile
-        filename = domain1.get_name() + '.sww'
-        fid = NetCDFFile(filename)
-
-        x = fid.variables['x'][:]
-        y = fid.variables['y'][:]
-        # we 'cast' to 64 bit floats to pass this test
-        # SWW file quantities are stored as 32 bits
-        x = num.array(x, num.float)
-        y = num.array(y, num.float)
-
-        stage = fid.variables['stage'][:]
-        xmomentum = fid.variables['xmomentum'][:]
-        ymomentum = fid.variables['ymomentum'][:]
-        time = fid.variables['time'][:]
-
-        #Take stage vertex values at last timestep on diagonal
-        #Diagonal is identified by vertices: 0, 5, 10, 15
-
-        last_time_index = len(time)-1 #Last last_time_index     
-        d_stage = num.reshape(num.take(stage[last_time_index, :],
-                                       [0,5,10,15],
-                                       axis=0),
-                              (4,1))
-        d_uh = num.reshape(num.take(xmomentum[last_time_index, :],
-                                    [0,5,10,15],
-                                   axis=0),
-                           (4,1))
-        d_vh = num.reshape(num.take(ymomentum[last_time_index, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        D = num.concatenate((d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0 = (D[0] + D[1])/2
-        r1 = (D[1] + D[2])/2
-        r2 = (D[2] + D[3])/2
-
-        #And the midpoints are found now
-        Dx = num.take(num.reshape(x, (16,1)), [0,5,10,15], axis=0)
-        Dy = num.take(num.reshape(y, (16,1)), [0,5,10,15], axis=0)
-
-        diag = num.concatenate((Dx, Dy), axis=1)
-        d_midpoints = (diag[1:] + diag[:-1])/2
-
-
-        #Adjust for georef - make interpolation points absolute
-        d_midpoints[:,0] += xllcorner
-        d_midpoints[:,1] += yllcorner                
-
-        #Let us see if the file function can find the correct
-        #values at the midpoints at the last timestep:
-        f = file_function(filename, domain1,
-                          interpolation_points = d_midpoints)
-
-        t = time[last_time_index]                         
-
-        q = f(t, point_id=0)
-        msg = '\nr0=%s\nq=%s' % (str(r0), str(q))
-        assert num.allclose(r0, q), msg
-
-        q = f(t, point_id=1)
-        msg = '\nr1=%s\nq=%s' % (str(r1), str(q))
-        assert num.allclose(r1, q), msg
-
-        q = f(t, point_id=2)
-        msg = '\nr2=%s\nq=%s' % (str(r2), str(q))
-        assert num.allclose(r2, q), msg
-
-
-        ##################
-        #Now do the same for the first timestep
-
-        timestep = 0 #First timestep
-        d_stage = num.reshape(num.take(stage[timestep, :],
-                                       [0,5,10,15],
-                                       axis=0),
-                              (4,1))
-        d_uh = num.reshape(num.take(xmomentum[timestep, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        d_vh = num.reshape(num.take(ymomentum[timestep, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        D = num.concatenate( (d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0 = (D[0] + D[1])/2
-        r1 = (D[1] + D[2])/2
-        r2 = (D[2] + D[3])/2
-
-        #Let us see if the file function can find the correct
-        #values
-        q = f(0, point_id=0); assert num.allclose(r0, q)
-        q = f(0, point_id=1); assert num.allclose(r1, q)
-        q = f(0, point_id=2); assert num.allclose(r2, q)
-
-
-        ##################
-        #Now do it again for a timestep in the middle
-
-        timestep = 33
-        d_stage = num.reshape(num.take(stage[timestep, :],
-                                       [0,5,10,15],
-                                       axis=0),
-                              (4,1))
-        d_uh = num.reshape(num.take(xmomentum[timestep, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        d_vh = num.reshape(num.take(ymomentum[timestep, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        D = num.concatenate( (d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0 = (D[0] + D[1])/2
-        r1 = (D[1] + D[2])/2
-        r2 = (D[2] + D[3])/2
-
-        q = f(timestep/10., point_id=0); assert num.allclose(r0, q)
-        q = f(timestep/10., point_id=1); assert num.allclose(r1, q)
-        q = f(timestep/10., point_id=2); assert num.allclose(r2, q)
-
-
-        ##################
-        #Now check temporal interpolation
-        #Halfway between timestep 15 and 16
-
-        timestep = 15
-        d_stage = num.reshape(num.take(stage[timestep, :],
-                                       [0,5,10,15],
-                                       axis=0),
-                              (4,1))
-        d_uh = num.reshape(num.take(xmomentum[timestep, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        d_vh = num.reshape(num.take(ymomentum[timestep, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        D = num.concatenate( (d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0_0 = (D[0] + D[1])/2
-        r1_0 = (D[1] + D[2])/2
-        r2_0 = (D[2] + D[3])/2
-
-        #
-        timestep = 16
-        d_stage = num.reshape(num.take(stage[timestep, :],
-                                       [0,5,10,15],
-                                       axis=0),
-                              (4,1))
-        d_uh = num.reshape(num.take(xmomentum[timestep, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        d_vh = num.reshape(num.take(ymomentum[timestep, :],
-                                    [0,5,10,15],
-                                    axis=0),
-                           (4,1))
-        D = num.concatenate( (d_stage, d_uh, d_vh), axis=1)
-
-        #Reference interpolated values at midpoints on diagonal at
-        #this timestep are
-        r0_1 = (D[0] + D[1])/2
-        r1_1 = (D[1] + D[2])/2
-        r2_1 = (D[2] + D[3])/2
-
-        # The reference values are
-        r0 = (r0_0 + r0_1)/2
-        r1 = (r1_0 + r1_1)/2
-        r2 = (r2_0 + r2_1)/2
-
-        q = f((timestep - 0.5)/10., point_id=0); assert num.allclose(r0, q)
-        q = f((timestep - 0.5)/10., point_id=1); assert num.allclose(r1, q)
-        q = f((timestep - 0.5)/10., point_id=2); assert num.allclose(r2, q)
-
-        ##################
-        #Finally check interpolation 2 thirds of the way
-        #between timestep 15 and 16
-
-        # The reference values are
-        r0 = (r0_0 + 2*r0_1)/3
-        r1 = (r1_0 + 2*r1_1)/3
-        r2 = (r2_0 + 2*r2_1)/3
-
-        #And the file function gives
-        q = f((timestep - 1.0/3)/10., point_id=0); assert num.allclose(r0, q)
-        q = f((timestep - 1.0/3)/10., point_id=1); assert num.allclose(r1, q)
-        q = f((timestep - 1.0/3)/10., point_id=2); assert num.allclose(r2, q)
-
-        fid.close()
-        import os
-        os.remove(filename)
-
-        
-
-
-    def test_spatio_temporal_file_function_time(self):
-        """Test that File function interpolates correctly
-        between given times.
-        NetCDF version (x,y,t dependency)
-        """
-
-        #Create NetCDF (sww) file to be read
-        # x: 0, 5, 10, 15
-        # y: -20, -10, 0, 10
-        # t: 0, 60, 120, ...., 1200
-        #
-        # test quantities (arbitrary but non-trivial expressions):
-        #
-        #   stage     = 3*x - y**2 + 2*t
-        #   xmomentum = exp( -((x-7)**2 + (y+5)**2)/20 ) * t**2
-        #   ymomentum = x**2 + y**2 * sin(t*pi/600)
-
-        #NOTE: Nice test that may render some of the others redundant.
-
-        import os, time
-        from anuga.config import time_format
-        from mesh_factory import rectangular
-        from anuga.shallow_water.shallow_water_domain import Domain
-
-        finaltime = 1200
-        filename = 'test_file_function'
-
-        #Create a domain to hold test grid
-        #(0:15, -20:10)
-        points, vertices, boundary =\
-                rectangular(4, 4, 15, 30, origin = (0, -20))
-        #print "points", points
-
-        #print 'Number of elements', len(vertices)
-        domain = Domain(points, vertices, boundary)
-        domain.smooth = False
-        domain.default_order = 2
-        domain.set_datadir('.')
-        domain.set_name(filename)
-        domain.store = True
-
-        #print points
-        start = time.mktime(time.strptime('2000', '%Y'))
-        domain.starttime = start
-
-
-        #Store structure
-        domain.initialise_storage()
-
-        #Compute artificial time steps and store
-        dt = 60  #One minute intervals
-        t = 0.0
-        while t <= finaltime:
-            #Compute quantities
-            f1 = lambda x,y: 3*x - y**2 + 2*t + 4
-            domain.set_quantity('stage', f1)
-
-            f2 = lambda x,y: x+y+t**2
-            domain.set_quantity('xmomentum', f2)
-
-            f3 = lambda x,y: x**2 + y**2 * num.sin(t*num.pi/600)
-            domain.set_quantity('ymomentum', f3)
-
-            #Store and advance time
-            domain.time = t
-            domain.store_timestep()
-            t += dt
-
-
-        interpolation_points = [[0,-20], [1,0], [0,1], [1.1, 3.14], [10,-12.5]]
-      
-        #Deliberately set domain.starttime to too early
-        domain.starttime = start - 1
-
-        #Create file function
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)
-
-        #Check that FF updates fixes domain starttime
-        assert num.allclose(domain.starttime, start)
-
-        #Check that domain.starttime isn't updated if later
-        domain.starttime = start + 1
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)
-        assert num.allclose(domain.starttime, start+1)
-        domain.starttime = start
-
-
-        #Check linear interpolation in time
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)                
-        for id in range(len(interpolation_points)):
-            x = interpolation_points[id][0]
-            y = interpolation_points[id][1]
-
-            for i in range(20):
-                t = i*10
-                k = i%6
-
-                if k == 0:
-                    q0 = F(t, point_id=id)
-                    q1 = F(t+60, point_id=id)
-
-                if num.alltrue(q0 == NAN):
-                    actual = q0
-                else:
-                    actual = (k*q1 + (6-k)*q0)/6
-                q = F(t, point_id=id)
-                #print i, k, t, q
-                #print ' ', q0
-                #print ' ', q1
-                #print "q",q
-                #print "actual", actual
-                #print
-                if num.alltrue(q0 == NAN):
-                     self.failUnless(num.alltrue(q == actual), 'Fail!')
-                else:
-                    assert num.allclose(q, actual)
-
-
-        #Another check of linear interpolation in time
-        for id in range(len(interpolation_points)):
-            q60 = F(60, point_id=id)
-            q120 = F(120, point_id=id)
-
-            t = 90 #Halfway between 60 and 120
-            q = F(t, point_id=id)
-            assert num.allclose( (q120+q60)/2, q )
-
-            t = 100 #Two thirds of the way between between 60 and 120
-            q = F(t, point_id=id)
-            assert num.allclose(q60/3 + 2*q120/3, q)
-
-
-
-        #Check that domain.starttime isn't updated if later than file starttime but earlier
-        #than file end time
-        delta = 23
-        domain.starttime = start + delta
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)
-        assert num.allclose(domain.starttime, start+delta)
-
-
-
-
-        #Now try interpolation with delta offset
-        for id in range(len(interpolation_points)):            
-            x = interpolation_points[id][0]
-            y = interpolation_points[id][1]
-
-            for i in range(20):
-                t = i*10
-                k = i%6
-
-                if k == 0:
-                    q0 = F(t-delta, point_id=id)
-                    q1 = F(t+60-delta, point_id=id)
-
-                q = F(t-delta, point_id=id)
-                assert num.allclose(q, (k*q1 + (6-k)*q0)/6)
-
-
-        os.remove(filename + '.sww')
-
-
-
-    def Xtest_spatio_temporal_file_function_time(self):
-        # FIXME: This passes but needs some TLC
-        # Test that File function interpolates correctly
-        # When some points are outside the mesh
-
-        import os, time
-        from anuga.config import time_format
-        from mesh_factory import rectangular
-        from shallow_water import Domain
-        import anuga.shallow_water.data_manager 
-        from anuga.pmesh.mesh_interface import create_mesh_from_regions
-        finaltime = 1200
-        
-        filename = tempfile.mktemp()
-        #print "filename",filename 
-        filename = 'test_file_function'
-
-        meshfilename = tempfile.mktemp(".tsh")
-
-        boundary_tags = {'walls':[0,1],'bom':[2]}
-        
-        polygon_absolute = [[0,-20],[10,-20],[10,15],[-20,15]]
-        
-        create_mesh_from_regions(polygon_absolute,
-                                 boundary_tags,
-                                 10000000,
-                                 filename=meshfilename)
-        domain = Domain(mesh_filename=meshfilename)
-        domain.smooth = False
-        domain.default_order = 2
-        domain.set_datadir('.')
-        domain.set_name(filename)
-        domain.store = True
-
-        #print points
-        start = time.mktime(time.strptime('2000', '%Y'))
-        domain.starttime = start
-        
-
-        #Store structure
-        domain.initialise_storage()
-
-        #Compute artificial time steps and store
-        dt = 60  #One minute intervals
-        t = 0.0
-        while t <= finaltime:
-            #Compute quantities
-            f1 = lambda x,y: 3*x - y**2 + 2*t + 4
-            domain.set_quantity('stage', f1)
-
-            f2 = lambda x,y: x+y+t**2
-            domain.set_quantity('xmomentum', f2)
-
-            f3 = lambda x,y: x**2 + y**2 * num.sin(t*num.pi/600)
-            domain.set_quantity('ymomentum', f3)
-
-            #Store and advance time
-            domain.time = t
-            domain.store_timestep()
-            t += dt
-
-        interpolation_points = [[1,0]]
-        interpolation_points = [[100,1000]]
-        
-        interpolation_points = [[0,-20], [1,0], [0,1], [1.1, 3.14], [10,-12.5],
-                                [78787,78787],[7878,3432]]
-            
-        #Deliberately set domain.starttime to too early
-        domain.starttime = start - 1
-
-        #Create file function
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)
-
-        #Check that FF updates fixes domain starttime
-        assert num.allclose(domain.starttime, start)
-
-        #Check that domain.starttime isn't updated if later
-        domain.starttime = start + 1
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)
-        assert num.allclose(domain.starttime, start+1)
-        domain.starttime = start
-
-
-        #Check linear interpolation in time
-        # checking points inside and outside the mesh
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)
-        
-        for id in range(len(interpolation_points)):
-            x = interpolation_points[id][0]
-            y = interpolation_points[id][1]
-
-            for i in range(20):
-                t = i*10
-                k = i%6
-
-                if k == 0:
-                    q0 = F(t, point_id=id)
-                    q1 = F(t+60, point_id=id)
-
-                if q0 == NAN:
-                    actual = q0
-                else:
-                    actual = (k*q1 + (6-k)*q0)/6
-                q = F(t, point_id=id)
-                #print i, k, t, q
-                #print ' ', q0
-                #print ' ', q1
-                #print "q",q
-                #print "actual", actual
-                #print
-                if q0 == NAN:
-                     self.failUnless( q == actual, 'Fail!')
-                else:
-                    assert num.allclose(q, actual)
-
-        # now lets check points inside the mesh
-        interpolation_points = [[0,-20], [1,0], [0,1], [1.1, 3.14]] #, [10,-12.5]] - this point doesn't work WHY?
-        interpolation_points = [[10,-12.5]]
-            
-        print "len(interpolation_points)",len(interpolation_points) 
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)
-
-        domain.starttime = start
-
-
-        #Check linear interpolation in time
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)                
-        for id in range(len(interpolation_points)):
-            x = interpolation_points[id][0]
-            y = interpolation_points[id][1]
-
-            for i in range(20):
-                t = i*10
-                k = i%6
-
-                if k == 0:
-                    q0 = F(t, point_id=id)
-                    q1 = F(t+60, point_id=id)
-
-                if q0 == NAN:
-                    actual = q0
-                else:
-                    actual = (k*q1 + (6-k)*q0)/6
-                q = F(t, point_id=id)
-                print "############"
-                print "id, x, y ", id, x, y #k, t, q
-                print "t", t
-                #print ' ', q0
-                #print ' ', q1
-                print "q",q
-                print "actual", actual
-                #print
-                if q0 == NAN:
-                     self.failUnless( q == actual, 'Fail!')
-                else:
-                    assert num.allclose(q, actual)
-
-
-        #Another check of linear interpolation in time
-        for id in range(len(interpolation_points)):
-            q60 = F(60, point_id=id)
-            q120 = F(120, point_id=id)
-
-            t = 90 #Halfway between 60 and 120
-            q = F(t, point_id=id)
-            assert num.allclose( (q120+q60)/2, q )
-
-            t = 100 #Two thirds of the way between between 60 and 120
-            q = F(t, point_id=id)
-            assert num.allclose(q60/3 + 2*q120/3, q)
-
-
-
-        #Check that domain.starttime isn't updated if later than file starttime but earlier
-        #than file end time
-        delta = 23
-        domain.starttime = start + delta
-        F = file_function(filename + '.sww', domain,
-                          quantities = domain.conserved_quantities,
-                          interpolation_points = interpolation_points)
-        assert num.allclose(domain.starttime, start+delta)
-
-
-
-
-        #Now try interpolation with delta offset
-        for id in range(len(interpolation_points)):            
-            x = interpolation_points[id][0]
-            y = interpolation_points[id][1]
-
-            for i in range(20):
-                t = i*10
-                k = i%6
-
-                if k == 0:
-                    q0 = F(t-delta, point_id=id)
-                    q1 = F(t+60-delta, point_id=id)
-
-                q = F(t-delta, point_id=id)
-                assert num.allclose(q, (k*q1 + (6-k)*q0)/6)
-
-
-        os.remove(filename + '.sww')
-
-    def test_file_function_time_with_domain(self):
-        """Test that File function interpolates correctly
-        between given times. No x,y dependency here.
-        Use domain with starttime
-        """
-
-        #Write file
-        import os, time, calendar
-        from anuga.config import time_format
-        from math import sin, pi
-
-        finaltime = 1200
-        filename = 'test_file_function'
-        fid = open(filename + '.txt', 'w')
-        start = time.mktime(time.strptime('2000', '%Y'))
-        
-        #print 'start ',start
-        
-        dt = 60  #One minute intervals
-        t = 0.0
-        while t <= finaltime:
-            t_string = time.strftime(time_format, time.gmtime(t+start))
-            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
-            t += dt
-
-        fid.close()
-
-
-        #Convert ASCII file to NetCDF (Which is what we really like!)
-        timefile2netcdf(filename+'.txt')
-
-
-
-        a = [0.0, 0.0]
-        b = [4.0, 0.0]
-        c = [0.0, 3.0]
-
-        points = [a, b, c]
-        vertices = [[0,1,2]]
-        domain = Domain(points, vertices)
-        #print domain.starttime, start
-		
-        # Check that domain.starttime is updated if non-existing
-        F = file_function(filename + '.tms',
-                          domain,
-                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'])  
-                          
-                          
-        #print domain.starttime, start
-        assert num.allclose(domain.starttime, start)
-
-        # Check that domain.starttime is updated if too early
-        domain.starttime = start - 1
-        F = file_function(filename + '.tms',
-                          domain,
-                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'])
-        assert num.allclose(domain.starttime, start)
-
-        # Check that domain.starttime isn't updated if later
-        domain.starttime = start + 1
-        F = file_function(filename + '.tms',
-                          domain,
-                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'])
-        assert num.allclose(domain.starttime, start+1)
-
-        domain.starttime = start
-        F = file_function(filename + '.tms',
-                          domain,
-                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'],
-                          use_cache=True)
-        
-
-        #print F.precomputed_values
-        #print 'F(60)', F(60)
-        
-        #Now try interpolation
-        for i in range(20):
-            t = i*10
-            q = F(t)
-
-            #Exact linear intpolation
-            assert num.allclose(q[0], 2*t)
-            if i%6 == 0:
-                assert num.allclose(q[1], t**2)
-                assert num.allclose(q[2], sin(t*pi/600))
-
-        #Check non-exact
-
-        t = 90 #Halfway between 60 and 120
-        q = F(t)
-        assert num.allclose( (120**2 + 60**2)/2, q[1] )
-        assert num.allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
-
-
-        t = 100 #Two thirds of the way between between 60 and 120
-        q = F(t)
-        assert num.allclose( 2*120**2/3 + 60**2/3, q[1] )
-        assert num.allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
-
-        os.remove(filename + '.tms')
-        os.remove(filename + '.txt')        
-
-    def test_file_function_time_with_domain_different_start(self):
-        """Test that File function interpolates correctly
-        between given times. No x,y dependency here.
-        Use domain with a starttime later than that of file
-
-        ASCII version
-        """
-
-        #Write file
-        import os, time, calendar
-        from anuga.config import time_format
-        from math import sin, pi
-
-        finaltime = 1200
-        filename = 'test_file_function'
-        fid = open(filename + '.txt', 'w')
-        start = time.mktime(time.strptime('2000', '%Y'))
-        dt = 60  #One minute intervals
-        t = 0.0
-        while t <= finaltime:
-            t_string = time.strftime(time_format, time.gmtime(t+start))
-            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
-            t += dt
-
-        fid.close()
-
-        #Convert ASCII file to NetCDF (Which is what we really like!)
-        timefile2netcdf(filename+'.txt')        
-
-        a = [0.0, 0.0]
-        b = [4.0, 0.0]
-        c = [0.0, 3.0]
-
-        points = [a, b, c]
-        vertices = [[0,1,2]]
-        domain = Domain(points, vertices)
-
-        #Check that domain.starttime isn't updated if later than file starttime but earlier
-        #than file end time
-        delta = 23
-        domain.starttime = start + delta
-        F = file_function(filename + '.tms', domain,
-                          quantities = ['Attribute0', 'Attribute1', 'Attribute2'])        
-        assert num.allclose(domain.starttime, start+delta)
-
-        assert num.allclose(F.get_time(), [-23., 37., 97., 157., 217.,
-                                            277., 337., 397., 457., 517.,
-                                            577., 637., 697., 757., 817.,
-                                            877., 937., 997., 1057., 1117.,
-                                            1177.])
-
-
-        #Now try interpolation with delta offset
-        for i in range(20):
-            t = i*10
-            q = F(t-delta)
-
-            #Exact linear intpolation
-            assert num.allclose(q[0], 2*t)
-            if i%6 == 0:
-                assert num.allclose(q[1], t**2)
-                assert num.allclose(q[2], sin(t*pi/600))
-
-        #Check non-exact
-
-        t = 90 #Halfway between 60 and 120
-        q = F(t-delta)
-        assert num.allclose( (120**2 + 60**2)/2, q[1] )
-        assert num.allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
-
-
-        t = 100 #Two thirds of the way between between 60 and 120
-        q = F(t-delta)
-        assert num.allclose( 2*120**2/3 + 60**2/3, q[1] )
-        assert num.allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
-
-
-        os.remove(filename + '.tms')
-        os.remove(filename + '.txt')                
-
-        
-
-    def test_file_function_time_with_domain_different_start_and_time_limit(self):
-        """Test that File function interpolates correctly
-        between given times. No x,y dependency here.
-        Use domain with a starttime later than that of file
-
-        ASCII version
-        
-        This test also tests that time can be truncated.
-        """
-
-        # Write file
-        import os, time, calendar
-        from anuga.config import time_format
-        from math import sin, pi
-
-        finaltime = 1200
-        filename = 'test_file_function'
-        fid = open(filename + '.txt', 'w')
-        start = time.mktime(time.strptime('2000', '%Y'))
-        dt = 60  #One minute intervals
-        t = 0.0
-        while t <= finaltime:
-            t_string = time.strftime(time_format, time.gmtime(t+start))
-            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
-            t += dt
-
-        fid.close()
-
-        # Convert ASCII file to NetCDF (Which is what we really like!)
-        timefile2netcdf(filename + '.txt')        
-
-        a = [0.0, 0.0]
-        b = [4.0, 0.0]
-        c = [0.0, 3.0]
-
-        points = [a, b, c]
-        vertices = [[0,1,2]]
-        domain = Domain(points, vertices)
-
-        # Check that domain.starttime isn't updated if later than file starttime but earlier
-        # than file end time
-        delta = 23
-        domain.starttime = start + delta
-        time_limit = domain.starttime + 600
-        F = file_function(filename + '.tms', domain,
-                          time_limit=time_limit,
-                          quantities=['Attribute0', 'Attribute1', 'Attribute2'])        
-        assert num.allclose(domain.starttime, start+delta)
-
-        assert num.allclose(F.get_time(), [-23., 37., 97., 157., 217.,
-                                            277., 337., 397., 457., 517.,
-                                            577.])        
-
-
-
-        # Now try interpolation with delta offset
-        for i in range(20):
-            t = i*10
-            q = F(t-delta)
-
-            #Exact linear intpolation
-            assert num.allclose(q[0], 2*t)
-            if i%6 == 0:
-                assert num.allclose(q[1], t**2)
-                assert num.allclose(q[2], sin(t*pi/600))
-
-        # Check non-exact
-        t = 90 #Halfway between 60 and 120
-        q = F(t-delta)
-        assert num.allclose( (120**2 + 60**2)/2, q[1] )
-        assert num.allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
-
-
-        t = 100 # Two thirds of the way between between 60 and 120
-        q = F(t-delta)
-        assert num.allclose( 2*120**2/3 + 60**2/3, q[1] )
-        assert num.allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
-
-
-        os.remove(filename + '.tms')
-        os.remove(filename + '.txt')                
-
-        
-        
-        
-
-
-    def test_apply_expression_to_dictionary(self):
-
-        #FIXME: Division is not expected to work for integers.
-        #This must be caught.
-        foo = num.array([[1,2,3], [4,5,6]], num.float)
-
-        bar = num.array([[-1,0,5], [6,1,1]], num.float)                  
-
-        D = {'X': foo, 'Y': bar}
-
-        Z = apply_expression_to_dictionary('X+Y', D)        
-        assert num.allclose(Z, foo+bar)
-
-        Z = apply_expression_to_dictionary('X*Y', D)        
-        assert num.allclose(Z, foo*bar)        
-
-        Z = apply_expression_to_dictionary('4*X+Y', D)        
-        assert num.allclose(Z, 4*foo+bar)        
-
-        # test zero division is OK
-        Z = apply_expression_to_dictionary('X/Y', D)
-        assert num.allclose(1/Z, 1/(foo/bar)) # can't compare inf to inf
-
-        # make an error for zero on zero
-        # this is really an error in numeric, SciPy core can handle it
-        # Z = apply_expression_to_dictionary('0/Y', D)
-
-        #Check exceptions
-        try:
-            #Wrong name
-            Z = apply_expression_to_dictionary('4*X+A', D)        
-        except NameError:
-            pass
-        else:
-            msg = 'Should have raised a NameError Exception'
-            raise Exception(msg)
-
-
-        try:
-            #Wrong order
-            Z = apply_expression_to_dictionary(D, '4*X+A')        
-        except AssertionError:
-            pass
-        else:
-            msg = 'Should have raised a AssertionError Exception'
-            raise Exception(msg)
-        
-
-    def test_multiple_replace(self):
-        """Hard test that checks a true word-by-word simultaneous replace
-        """
-        
-        D = {'x': 'xi', 'y': 'eta', 'xi':'lam'}
-        exp = '3*x+y + xi'
-        
-        new = multiple_replace(exp, D)
-        
-        assert new == '3*xi+eta + lam'
-                          
-   
-    def test_get_revision_number(self):
-        """test_get_revision_number(self):
-
-        Test that revision number can be retrieved.
-        """
-        if os.environ.has_key('USER') and os.environ['USER'] == 'dgray':
-            # I have a known snv incompatability issue,
-            # so I'm skipping this test.
-            # FIXME when SVN is upgraded on our clusters
-            pass
-        else:    
-            n = get_revision_number()
-            assert n>=0
-
-
-        
-    def test_add_directories(self):
-        
-        import tempfile
-        root_dir = tempfile.mkdtemp('_test_util', 'test_util_')
-        directories = ['ja','ne','ke']
-        kens_dir = add_directories(root_dir, directories)
-        assert kens_dir == root_dir + sep + 'ja' + sep + 'ne' + \
-               sep + 'ke'
-        assert access(root_dir,F_OK)
-
-        add_directories(root_dir, directories)
-        assert access(root_dir,F_OK)
-        
-        #clean up!
-        os.rmdir(kens_dir)
-        os.rmdir(root_dir + sep + 'ja' + sep + 'ne')
-        os.rmdir(root_dir + sep + 'ja')
-        os.rmdir(root_dir)
-
-    def test_add_directories_bad(self):
-        
-        import tempfile
-        root_dir = tempfile.mkdtemp('_test_util', 'test_util_')
-        directories = ['/\/!@#@#$%^%&*((*:*:','ne','ke']
-        
-        try:
-            kens_dir = add_directories(root_dir, directories)
-        except OSError:
-            pass
-        else:
-            msg = 'bad dir name should give OSError'
-            raise Exception(msg)    
-            
-        #clean up!
-        os.rmdir(root_dir)
-
-    def test_check_list(self):
-
-        check_list(['stage','xmomentum'])
-
-        
-    def test_add_directories(self):
-        
-        import tempfile
-        root_dir = tempfile.mkdtemp('_test_util', 'test_util_')
-        directories = ['ja','ne','ke']
-        kens_dir = add_directories(root_dir, directories)
-        assert kens_dir == root_dir + sep + 'ja' + sep + 'ne' + \
-               sep + 'ke'
-        assert access(root_dir,F_OK)
-
-        add_directories(root_dir, directories)
-        assert access(root_dir,F_OK)
-        
-        #clean up!
-        os.rmdir(kens_dir)
-        os.rmdir(root_dir + sep + 'ja' + sep + 'ne')
-        os.rmdir(root_dir + sep + 'ja')
-        os.rmdir(root_dir)
-
-    def test_add_directories_bad(self):
-        
-        import tempfile
-        root_dir = tempfile.mkdtemp('_test_util', 'test_util_')
-        directories = ['/\/!@#@#$%^%&*((*:*:','ne','ke']
-        
-        try:
-            kens_dir = add_directories(root_dir, directories)
-        except OSError:
-            pass
-        else:
-            msg = 'bad dir name should give OSError'
-            raise Exception(msg)    
-            
-        #clean up!
-        os.rmdir(root_dir)
-
-    def test_check_list(self):
-
-        check_list(['stage','xmomentum'])
-
-######
-# Test the remove_lone_verts() function
-######
-        
-    def test_remove_lone_verts_a(self):
-        verts = [[0,0],[1,0],[0,1]]
-        tris = [[0,1,2]]
-        new_verts, new_tris = remove_lone_verts(verts, tris)
-        self.failUnless(new_verts.tolist() == verts)
-        self.failUnless(new_tris.tolist() == tris)
-
-    def test_remove_lone_verts_b(self):
-        verts = [[0,0],[1,0],[0,1],[99,99]]
-        tris = [[0,1,2]]
-        new_verts, new_tris = remove_lone_verts(verts, tris)
-        self.failUnless(new_verts.tolist() == verts[0:3])
-        self.failUnless(new_tris.tolist() == tris)
-        
-    def test_remove_lone_verts_c(self):
-        verts = [[99,99],[0,0],[1,0],[99,99],[0,1],[99,99]]
-        tris = [[1,2,4]]
-        new_verts, new_tris = remove_lone_verts(verts, tris)
-        self.failUnless(new_verts.tolist() == [[0,0],[1,0],[0,1]])
-        self.failUnless(new_tris.tolist() == [[0,1,2]])
-     
-    def test_remove_lone_verts_d(self):
-        verts = [[0,0],[1,0],[99,99],[0,1]]
-        tris = [[0,1,3]]
-        new_verts, new_tris = remove_lone_verts(verts, tris)
-        self.failUnless(new_verts.tolist() == [[0,0],[1,0],[0,1]])
-        self.failUnless(new_tris.tolist() == [[0,1,2]])
-        
-    def test_remove_lone_verts_e(self):
-        verts = [[0,0],[1,0],[0,1],[99,99],[99,99],[99,99]]
-        tris = [[0,1,2]]
-        new_verts, new_tris = remove_lone_verts(verts, tris)
-        self.failUnless(new_verts.tolist() == verts[0:3])
-        self.failUnless(new_tris.tolist() == tris)
-     
-    def test_remove_lone_verts_f(self):
-        verts = [[0,0],[1,0],[99,99],[0,1],[99,99],[1,1],[99,99]]
-        tris = [[0,1,3],[0,1,5]]
-        new_verts, new_tris = remove_lone_verts(verts, tris)
-        self.failUnless(new_verts.tolist() == [[0,0],[1,0],[0,1],[1,1]])
-        self.failUnless(new_tris.tolist() == [[0,1,2],[0,1,3]])
-        
-######
-# 
-######
-        
-    def test_get_min_max_values(self):
-        
-        list=[8,9,6,1,4]
-        min1, max1 = get_min_max_values(list)
-        
-        assert min1==1 
-        assert max1==9
-        
-    def test_get_min_max_values1(self):
-        
-        list=[-8,-9,-6,-1,-4]
-        min1, max1 = get_min_max_values(list)
-        
-#        print 'min1,max1',min1,max1
-        assert min1==-9 
-        assert max1==-1
-
-#    def test_get_min_max_values2(self):
-#        '''
-#        The min and max supplied are greater than the ones in the 
-#        list and therefore are the ones returned
-#        '''
-#        list=[-8,-9,-6,-1,-4]
-#        min1, max1 = get_min_max_values(list,-10,10)
-#        
-##        print 'min1,max1',min1,max1
-#        assert min1==-10 
-#        assert max1==10
-        
-    def test_make_plots_from_csv_files(self):
-        
-        #if sys.platform == 'win32':  #Windows
-            try: 
-                import pylab
-            except ImportError:
-                #ANUGA don't need pylab to work so the system doesn't 
-                #rely on pylab being installed 
-                return
-            
-        
-            current_dir=getcwd()+sep+'abstract_2d_finite_volumes'
-            temp_dir = tempfile.mkdtemp('','figures')
-    #        print 'temp_dir',temp_dir
-            fileName = temp_dir+sep+'time_series_3.csv'
-            file = open(fileName,"w")
-            file.write("time,stage,speed,momentum,elevation\n\
-1.0, 0, 0, 0, 10 \n\
-2.0, 5, 2, 4, 10 \n\
-3.0, 3, 3, 5, 10 \n")
-            file.close()
-    
-            fileName1 = temp_dir+sep+'time_series_4.csv'
-            file1 = open(fileName1,"w")
-            file1.write("time,stage,speed,momentum,elevation\n\
-1.0, 0, 0, 0, 5 \n\
-2.0, -5, -2, -4, 5 \n\
-3.0, -4, -3, -5, 5 \n")
-            file1.close()
-    
-            fileName2 = temp_dir+sep+'time_series_5.csv'
-            file2 = open(fileName2,"w")
-            file2.write("time,stage,speed,momentum,elevation\n\
-1.0, 0, 0, 0, 7 \n\
-2.0, 4, -0.45, 57, 7 \n\
-3.0, 6, -0.5, 56, 7 \n")
-            file2.close()
-            
-            dir, name=os.path.split(fileName)
-            csv2timeseries_graphs(directories_dic={dir:['gauge', 0, 0]},
-                                  output_dir=temp_dir,
-                                  base_name='time_series_',
-                                  plot_numbers=['3-5'],
-                                  quantities=['speed','stage','momentum'],
-                                  assess_all_csv_files=True,
-                                  extra_plot_name='test')
-            
-            #print dir+sep+name[:-4]+'_stage_test.png'
-            assert(access(dir+sep+name[:-4]+'_stage_test.png',F_OK)==True)
-            assert(access(dir+sep+name[:-4]+'_speed_test.png',F_OK)==True)
-            assert(access(dir+sep+name[:-4]+'_momentum_test.png',F_OK)==True)
-    
-            dir1, name1=os.path.split(fileName1)
-            assert(access(dir+sep+name1[:-4]+'_stage_test.png',F_OK)==True)
-            assert(access(dir+sep+name1[:-4]+'_speed_test.png',F_OK)==True)
-            assert(access(dir+sep+name1[:-4]+'_momentum_test.png',F_OK)==True)
-    
-    
-            dir2, name2=os.path.split(fileName2)
-            assert(access(dir+sep+name2[:-4]+'_stage_test.png',F_OK)==True)
-            assert(access(dir+sep+name2[:-4]+'_speed_test.png',F_OK)==True)
-            assert(access(dir+sep+name2[:-4]+'_momentum_test.png',F_OK)==True)
-    
-            del_dir(temp_dir)
-        
-
-
-    def test_greens_law(self):
-
-        from math import sqrt
-        
-        d1 = 80.0
-        d2 = 20.0
-        h1 = 1.0
-        h2 = greens_law(d1,d2,h1)
-
-        assert h2==sqrt(2.0)
-        
-    def test_calc_bearings(self):
- 
-        from math import atan, degrees
-        #Test East
-        uh = 1
-        vh = 1.e-15
-        angle = calc_bearing(uh, vh)
-        if 89 < angle < 91: v=1
-        assert v==1
-        #Test West
-        uh = -1
-        vh = 1.e-15
-        angle = calc_bearing(uh, vh)
-        if 269 < angle < 271: v=1
-        assert v==1
-        #Test North
-        uh = 1.e-15
-        vh = 1
-        angle = calc_bearing(uh, vh)
-        if -1 < angle < 1: v=1
-        assert v==1
-        #Test South
-        uh = 1.e-15
-        vh = -1
-        angle = calc_bearing(uh, vh)
-        if 179 < angle < 181: v=1
-        assert v==1
-        #Test South-East
-        uh = 1
-        vh = -1
-        angle = calc_bearing(uh, vh)
-        if 134 < angle < 136: v=1
-        assert v==1
-        #Test North-East
-        uh = 1
-        vh = 1
-        angle = calc_bearing(uh, vh)
-        if 44 < angle < 46: v=1
-        assert v==1
-        #Test South-West
-        uh = -1
-        vh = -1
-        angle = calc_bearing(uh, vh)
-        if 224 < angle < 226: v=1
-        assert v==1
-        #Test North-West
-        uh = -1
-        vh = 1
-        angle = calc_bearing(uh, vh)
-        if 314 < angle < 316: v=1
-        assert v==1
-       
-    def test_calc_bearings_zero_vector(self): 
-        from math import atan, degrees
-
-        uh = 0
-        vh = 0
-        angle = calc_bearing(uh, vh)
-
-        assert angle == NAN
-        
-#-------------------------------------------------------------
-
-if __name__ == "__main__":
-    suite = unittest.makeSuite(Test_Util, 'test')
-#    runner = unittest.TextTestRunner(verbosity=2)
-    runner = unittest.TextTestRunner(verbosity=1)
-    runner.run(suite)
