def test_unequal_lines(self):
     test_path = aust.get_pathname_from_package('anuga.lib.tests')
     in_file = os.path.join(test_path, 'test1.asc')
     expected_file = os.path.join(test_path, 'test1_bad_num_lines.asc')
     self.assertRaises(RuntimeError, MaxAsc,
                           'test.out.asc',
                           [in_file, expected_file])
    def setUp(self):

        path = get_pathname_from_package('anuga.structures')
        self.input_hecras_file = os.path.join(path, 'tests', 'data',
                                              'hecras_bridge_table.csv')

        return
 def test_different_input2(self):
     test_path = aust.get_pathname_from_package('anuga.lib.tests')
     in_file = os.path.join(test_path, 'test1.asc')
     in_file2 = os.path.join(test_path, 'test2.asc')
     expected_file = os.path.join(test_path, 'test2.expected.asc')
     MaxAsc('test2.out.asc', [in_file, in_file2])
     self.assertTrue(FilesEqual('test2.out.asc', expected_file))
Esempio n. 4
0
 def test_different_input2(self):
     test_path = aust.get_pathname_from_package('anuga.lib.tests')
     in_file = os.path.join(test_path, 'test1.asc')
     in_file2 = os.path.join(test_path, 'test2.asc')
     expected_file = os.path.join(test_path, 'test2.expected.asc')
     MaxAsc('test2.out.asc', [in_file, in_file2])
     self.assertTrue(FilesEqual('test2.out.asc', expected_file))
Esempio n. 5
0
    def test_inlet_variable_Q(self):
        """test_inlet_Q
        
        This tests that the inlet operator adds the correct amount of water
        """

        stage_0 = 11.0
        stage_1 = 10.0
        elevation_0 = 10.0
        elevation_1 = 10.0

        domain_length = 200.0
        domain_width = 200.0

        domain = self._create_domain(d_length=domain_length,
                                     d_width=domain_width,
                                     dx=10.0,
                                     dy=10.0,
                                     elevation_0=elevation_0,
                                     elevation_1=elevation_1,
                                     stage_0=stage_0,
                                     stage_1=stage_1)

        vol0 = domain.compute_total_volume()

        finaltime = 3.0

        #Make sure we are inthe right directory to find the
        #time series data for the inlets
        import os

        path = get_pathname_from_package('anuga.structures')
        filename1 = os.path.join(path, 'tests', 'data',
                                 'inlet_operator_test1.tms')
        filename2 = os.path.join(path, 'tests', 'data',
                                 'inlet_operator_test2.tms')

        line1 = [[95.0, 10.0], [105.0, 10.0]]
        Q1 = file_function(filename=filename1, quantities=['hydrograph'])

        line2 = [[10.0, 90.0], [20.0, 90.0]]
        Q2 = file_function(filename=filename2, quantities=['hydrograph'])

        Inlet_operator(domain, line1, Q1)
        Inlet_operator(domain, line2, Q2)

        for t in domain.evolve(yieldstep=1.0, finaltime=finaltime):
            #domain.write_time()
            #print domain.volumetric_balance_statistics()
            pass

        vol1 = domain.compute_total_volume()

        #print vol1-vol0

        assert numpy.allclose(13.5, vol1 - vol0, rtol=1.0e-8)
        assert numpy.allclose(vol1 - vol0,
                              domain.fractional_step_volume_integral,
                              rtol=1.0e-8)
    def test_inlet_variable_Q(self):
        """test_inlet_Q
        
        This tests that the inlet operator adds the correct amount of water
        """

        stage_0 = 11.0
        stage_1 = 10.0
        elevation_0 = 10.0
        elevation_1 = 10.0

        domain_length = 200.0
        domain_width = 200.0
        

        domain = self._create_domain(d_length=domain_length,
                                     d_width=domain_width,
                                     dx = 10.0,
                                     dy = 10.0,
                                     elevation_0 = elevation_0,
                                     elevation_1 = elevation_1,
                                     stage_0 = stage_0,
                                     stage_1 = stage_1)

        vol0 = domain.compute_total_volume()

        finaltime = 3.0

        #Make sure we are inthe right directory to find the
        #time series data for the inlets
        import os
        
        path = get_pathname_from_package('anuga.structures')
        filename1 = os.path.join(path, 'tests', 'data', 'inlet_operator_test1.tms')
        filename2 = os.path.join(path, 'tests', 'data', 'inlet_operator_test2.tms')

        line1 = [[95.0, 10.0], [105.0, 10.0]]
        Q1 = file_function(filename=filename1, quantities=['hydrograph'])
        
        line2 = [[10.0, 90.0], [20.0, 90.0]]
        Q2 = file_function(filename=filename2, quantities=['hydrograph'])

        
        Inlet_operator(domain, line1, Q1)
        Inlet_operator(domain, line2, Q2)

        for t in domain.evolve(yieldstep = 1.0, finaltime = finaltime):
            #domain.write_time()
            #print domain.volumetric_balance_statistics()
            pass
 

        vol1 = domain.compute_total_volume()

        #print vol1-vol0
        
        assert numpy.allclose(13.5, vol1-vol0, rtol=1.0e-8) 
        assert numpy.allclose(vol1-vol0, domain.fractional_step_volume_integral, rtol=1.0e-8) 
    def test_csv2polygons_with_clipping(self):
        """test_csv2polygons with optional clipping
        """
        #FIXME(Ole): Not Done!!

        path = get_pathname_from_package('anuga.shallow_water')
        testfile = os.path.join(path, 'tests', 'data',
                                'polygon_values_example.csv')

        polygons, values = load_csv_as_polygons(testfile,
                                                value_name='floors',
                                                clipping_polygons=None)

        assert len(polygons) == 7, 'Must have seven polygons'
        assert len(values) == 7, 'Must have seven values'

        # Known floor values
        floors = {'1': 2, '2': 0, '3': 1, '4': 2, '5': 0, '8': 1, '9': 1}

        # Known polygon values
        known_polys = {
            '1': [[422681.61, 871117.55], [422691.02, 871117.60],
                  [422690.87, 871084.23], [422649.36, 871081.85],
                  [422649.36, 871080.39], [422631.86, 871079.50],
                  [422631.72, 871086.75], [422636.75, 871087.20],
                  [422636.75, 871091.50], [422649.66, 871092.09],
                  [422649.83, 871084.91], [422652.94, 871084.90],
                  [422652.84, 871092.39], [422681.83, 871093.73],
                  [422681.61, 871117.55]],
            '2': [[422664.22, 870785.46], [422672.48, 870780.14],
                  [422668.17, 870772.62], [422660.35, 870777.17],
                  [422664.22, 870785.46]],
            '3': [[422661.30, 871215.06], [422667.50, 871215.70],
                  [422668.30, 871204.86], [422662.21, 871204.33],
                  [422661.30, 871215.06]],
            '4': [[422473.44, 871191.22], [422478.33, 871192.26],
                  [422479.52, 871186.03], [422474.78, 871185.14],
                  [422473.44, 871191.22]],
            '5': [[422369.69, 871049.29], [422378.63, 871053.58],
                  [422383.91, 871044.51], [422374.97, 871040.32],
                  [422369.69, 871049.29]],
            '8': [[422730.56, 871203.13], [422734.10, 871204.90],
                  [422735.26, 871202.18], [422731.87, 871200.58],
                  [422730.56, 871203.13]],
            '9': [[422659.85, 871213.80], [422660.91, 871210.97],
                  [422655.42, 871208.85], [422654.36, 871211.68],
                  [422659.85, 871213.80]]
        }

        for id in ['1', '2', '3', '4', '5', '8', '9']:
            assert id in list(polygons.keys())
            assert id in list(values.keys())

            assert int(values[id]) == int(floors[id])
            assert len(polygons[id]) == len(known_polys[id])
            assert num.allclose(polygons[id], known_polys[id])
Esempio n. 8
0
    def test_run_via_commandline(self):
        """
        Make sure that the python file functions as a command-line tool.
        """

        # Look for script in same dir as this unit test.
        path = os.path.dirname( os.path.realpath( __file__ ) )

        path = get_pathname_from_package( 'anuga.file_conversion' )
        
        cmd = 'python ' + os.path.join( path, 'csv2sts.py') + ' --latitude ' 
        cmd += '%s --lon %s %s %s' % (str(lat), str(lon), testfile_csv, sts_out)
        
        os.system(cmd)
        self._check_generated_sts()
    def test_run_via_commandline(self):
        """
        Make sure that the python file functions as a command-line tool.
        """

        # Look for script in same dir as this unit test.
        path = os.path.dirname( os.path.realpath( __file__ ) )

        path = get_pathname_from_package( 'anuga.file_conversion' )
        
        cmd = 'python ' + os.path.join( path, 'csv2sts.py') + ' --latitude ' 
        cmd += '%s --lon %s %s %s' % (str(lat), str(lon), testfile_csv, sts_out)
        
        os.system(cmd)
        self._check_generated_sts()
Esempio n. 10
0
    def test_against_octave_code(self):
        # This test runs a test case from
        # DENYS DUTYKH , DIMITRIOS MITSOTAKIS, XAVIER GARDEIL, AND FREDERIC DIAS
        # ON THE USE OF THE FINITE FAULT SOLUTION FOR TSUNAMI
        # GENERATION PROBLEMS
        # The copy I have seems to be a pre-print, not sure of the journal
        # We compare the results of our code with another code written purely in matlab
        # This code is by 'Francois Beauducel', and was obtained from matlab central (July 2012)
        # See: http://www.mathworks.com/matlabcentral/fileexchange/25982
        slip = 2.5
        rake = 95.
        dis1 = slip * numpy.cos(rake / 180. * numpy.pi)
        dis2 = slip * numpy.sin(rake / 180. * numpy.pi)
        strike = 289.
        dip = 10.
        length = 80.9
        width = 40.0
        focal_depth = 20.
        depth = focal_depth + width / 2.0 * numpy.sin(
            dip / 180. * numpy.pi)  # T

        source = numpy.array(
            [0., 0., depth, strike, dip, length, width, dis1, dis2, 0.0])

        tsunami_fun = okada_tsunami.earthquake_source(source=source,
                                                      verbose=False)

        # Make a grid
        mygrid = numpy.lib.index_tricks.nd_grid()
        grid_width = 400000
        n = 101
        grid2 = mygrid[0:grid_width:(n * 1j), 0:grid_width:(n * 1j)]

        # Centre grid
        x = (grid2[0, :, :].reshape((n * n)) - grid_width / 2.)
        y = (grid2[1, :, :].reshape((n * n)) - grid_width / 2.)

        eq_source = tsunami_fun(x, y)

        ## Now read the same event from an octave code, which is completely
        ## independent of this one (i.e. they don't call okada's fortran)
        path = get_pathname_from_package('anuga.tsunami_source')
        octave = numpy.genfromtxt(path + sep + 'tests' + sep +
                                  'okada_tsunami_octave_95.txt')
        octave_asvec = numpy.transpose(octave).reshape((1, 101 * 101))

        # Estimate the differences between the 2 codes
        assert (abs(octave_asvec - eq_source)).max() < 1.0e-04
Esempio n. 11
0
    def test_nonstandard_meridian(self):
        """test_nonstandard_meridian

        This test will verify that redfearn can be used to project
        points using an arbitrary central meridian.
        """

        # The file projection_test_points.csv contains 10 points
        # which straddle the boundary between UTM zones 53 and 54.
        # They have been projected using a central meridian of 137.5
        # degrees (the boundary is 138 so it is pretty much right
        # in the middle of zones 53 and 54).

        path = get_pathname_from_package('anuga.coordinate_transforms')
        datafile = join(path, 'tests', 'data', 'projection_test_points.csv')
        fid = open(datafile)

        for line in fid.readlines()[1:]:
            fields = line.strip().split(',')

            lon = float(fields[1])
            lat = float(fields[2])
            x = float(fields[3])
            y = float(fields[4])

            zone, easting, northing = redfearn(lat,
                                               lon,
                                               central_meridian=137.5,
                                               scale_factor=0.9996)

            assert zone == -1  # Indicates non UTM projection
            assert num.allclose(x, easting)
            assert num.allclose(y, northing)

        # Test that zone and meridian can't both be specified
        try:
            zone, easting, northing = redfearn(lat,
                                               lon,
                                               zone=50,
                                               central_meridian=137.5)
        except:
            pass
        else:
            msg = 'Should have raised exception'
            raise Exception, msg
Esempio n. 12
0
    def test_against_octave_code(self):
        # This test runs a test case from
        # DENYS DUTYKH , DIMITRIOS MITSOTAKIS, XAVIER GARDEIL, AND FREDERIC DIAS
        # ON THE USE OF THE FINITE FAULT SOLUTION FOR TSUNAMI
        # GENERATION PROBLEMS
        # The copy I have seems to be a pre-print, not sure of the journal
        # We compare the results of our code with another code written purely in matlab
        # This code is by 'Francois Beauducel', and was obtained from matlab central (July 2012)
        # See: http://www.mathworks.com/matlabcentral/fileexchange/25982
        slip = 2.5
        rake = 95.0
        dis1 = slip * numpy.cos(rake / 180.0 * numpy.pi)
        dis2 = slip * numpy.sin(rake / 180.0 * numpy.pi)
        strike = 289.0
        dip = 10.0
        length = 80.9
        width = 40.0
        focal_depth = 20.0
        depth = focal_depth + width / 2.0 * numpy.sin(dip / 180.0 * numpy.pi)  # T

        source = numpy.array([0.0, 0.0, depth, strike, dip, length, width, dis1, dis2, 0.0])

        tsunami_fun = okada_tsunami.earthquake_source(source=source, verbose=False)

        # Make a grid
        mygrid = numpy.lib.index_tricks.nd_grid()
        grid_width = 400000
        n = 101
        grid2 = mygrid[0 : grid_width : (n * 1j), 0 : grid_width : (n * 1j)]

        # Centre grid
        x = grid2[0, :, :].reshape((n * n)) - grid_width / 2.0
        y = grid2[1, :, :].reshape((n * n)) - grid_width / 2.0

        eq_source = tsunami_fun(x, y)

        ## Now read the same event from an octave code, which is completely
        ## independent of this one (i.e. they don't call okada's fortran)
        path = get_pathname_from_package("anuga.tsunami_source")
        octave = numpy.genfromtxt(path + sep + "tests" + sep + "okada_tsunami_octave_95.txt")
        octave_asvec = numpy.transpose(octave).reshape((1, 101 * 101))

        # Estimate the differences between the 2 codes
        assert (abs(octave_asvec - eq_source)).max() < 1.0e-04
    def test_nonstandard_meridian(self):
        """test_nonstandard_meridian

        This test will verify that redfearn can be used to project
        points using an arbitrary central meridian.
        """

        # The file projection_test_points.csv contains 10 points
        # which straddle the boundary between UTM zones 53 and 54.
        # They have been projected using a central meridian of 137.5
        # degrees (the boundary is 138 so it is pretty much right
        # in the middle of zones 53 and 54).

        path = get_pathname_from_package('anuga.coordinate_transforms')
        datafile = join(path, 'tests', 'data', 'projection_test_points.csv')
        fid = open(datafile)

        for line in fid.readlines()[1:]:
            fields = line.strip().split(',')

            lon = float(fields[1])
            lat = float(fields[2])
            x = float(fields[3])
            y = float(fields[4])            

            zone, easting, northing = redfearn(lat, lon,
                                               central_meridian=137.5,
                                               scale_factor=0.9996)

            assert zone == -1 # Indicates non UTM projection
            assert num.allclose(x, easting)
            assert num.allclose(y, northing)

        # Test that zone and meridian can't both be specified
        try:
            zone, easting, northing = redfearn(lat, lon,
                                               zone=50, 
                                               central_meridian=137.5)
        except:
            pass
        else:
            msg = 'Should have raised exception'
            raise Exception, msg
Esempio n. 14
0
    def test_csv2building_polygons(self):
        """test_csv2building_polygons
        """
        
        path = get_pathname_from_package('anuga.shallow_water')                
        testfile = os.path.join(path, 'tests', 'data', 'polygon_values_example.csv')                

        polygons, values = load_csv_as_building_polygons(testfile, 
                                                 floor_height=3)

        assert len(polygons) == 7, 'Must have seven polygons'
        assert len(values) == 7, 'Must have seven values'
            
        # Known floor values
        floors = {'1': 6, '2': 0, '3': 3, '4': 6, '5': 0, '8': 3, '9': 3}
        
                
        for id in ['1', '2', '3', '4', '5' ,'8' ,'9']:
            assert id in polygons.keys()
            assert id in values.keys()            

            assert float(values[id]) == float(floors[id])
    def test_nonstandard_meridian_coinciding_with_native(self):
        """test_nonstandard_meridian_coinciding_with_native

        This test will verify that redfearn can be used to project
        points using an arbitrary central meridian that happens to 
        coincide with the standard meridian at the center of a UTM zone.
        This is a preliminary test before testing this functionality
        with a truly arbitrary non-standard meridian.
        """

        # The file projection_test_points_z53.csv contains 10 points
        # which straddle the boundary between UTM zones 53 and 54.
        # They have been projected to zone 53 irrespective of where they
        # belong.

        path = get_pathname_from_package('anuga.coordinate_transforms')
        
        for forced_zone in [53, 54]:
        
            datafile = join(path, 'tests', 'data', 'projection_test_points_z%d.csv' % forced_zone)
            fid = open(datafile)

            for line in fid.readlines()[1:]:
                fields = line.strip().split(',')
                
                lon = float(fields[1])
                lat = float(fields[2])
                x = float(fields[3])
                y = float(fields[4])            

                zone, easting, northing = redfearn(lat, lon,
                                                   zone=forced_zone)
                
                # Check calculation
                assert zone == forced_zone
                assert num.allclose(x, easting)
                assert num.allclose(y, northing)
Esempio n. 16
0
    def test_nonstandard_meridian_coinciding_with_native(self):
        """test_nonstandard_meridian_coinciding_with_native

        This test will verify that redfearn can be used to project
        points using an arbitrary central meridian that happens to 
        coincide with the standard meridian at the center of a UTM zone.
        This is a preliminary test before testing this functionality
        with a truly arbitrary non-standard meridian.
        """

        # The file projection_test_points_z53.csv contains 10 points
        # which straddle the boundary between UTM zones 53 and 54.
        # They have been projected to zone 53 irrespective of where they
        # belong.

        path = get_pathname_from_package('anuga.coordinate_transforms')
        
        for forced_zone in [53, 54]:
        
            datafile = join(path, 'tests', 'data', 'projection_test_points_z%d.csv' % forced_zone)
            fid = open(datafile)

            for line in fid.readlines()[1:]:
                fields = line.strip().split(',')
                
                lon = float(fields[1])
                lat = float(fields[2])
                x = float(fields[3])
                y = float(fields[4])            

                zone, easting, northing = redfearn(lat, lon,
                                                   zone=forced_zone)
                
                # Check calculation
                assert zone == forced_zone
                assert num.allclose(x, easting)
                assert num.allclose(y, northing)
import numpy as num
#from parallel_inlet_operator import Parallel_Inlet_operator
from anuga.parallel import distribute, myid, numprocs, finalize
from anuga.geometry.polygon import inside_polygon, is_inside_polygon, line_intersect

#from parallel_operator_factory import Inlet_operator, Boyd_box_operator
from anuga.utilities import parallel_abstraction as pypar
import random
"""test_that_culvert_runs_rating

This test exercises the culvert and checks values outside rating curve
are dealt with       
"""
verbose = False
path = get_pathname_from_package('anuga.culvert_flows')

length = 40.
width = 15.

dx = dy = 0.5  # Resolution: Length of subdivisions on both axes

#----------------------------------------------------------------------
# Setup initial conditions
#----------------------------------------------------------------------


def topography(x, y):
    """Set up a weir
    
    A culvert will connect either side
    def test_predicted_boyd_flow(self):
        """test_predicted_boyd_flow
        
        Test that flows predicted by the boyd method are consistent with what what
        is calculated in engineering codes.
        The data was supplied by Petar Milevski
        """

        # FIXME(Ole) this is nowhere near finished
        path = get_pathname_from_package('anuga.culvert_flows')

        length = 12.
        width = 5.

        dx = dy = 0.5  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)

        domain.set_name('test_culvert')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            # General Slope of Topography
            z = -x / 10

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity('stage', expression='elevation')

        Q0 = domain.get_quantity('stage')
        Q1 = Quantity(domain)

        # Add depths to stage
        head_water_depth = 0.169
        tail_water_depth = 0.089

        inlet_poly = [[0, 0], [6, 0], [6, 5], [0, 5]]
        outlet_poly = [[6, 0], [12, 0], [12, 5], [6, 5]]

        Q1.set_values(
            Polygon_function([(inlet_poly, head_water_depth),
                              (outlet_poly, tail_water_depth)]))

        domain.set_quantity('stage', Q0 + Q1)

        culvert = Culvert_flow(domain,
                               label='Test culvert',
                               description='4 m test culvert',
                               end_point0=[4.0, 2.5],
                               end_point1=[8.0, 2.5],
                               width=1.20,
                               height=0.75,
                               culvert_routine=boyd_generalised_culvert_model,
                               number_of_barrels=1,
                               verbose=False)

        domain.forcing_terms.append(culvert)

        # Call
        culvert(domain)
Esempio n. 19
0
    def test_csv2polygons_with_clipping(self):
        """test_csv2polygons with optional clipping
        """
        #FIXME(Ole): Not Done!!
        
        path = get_pathname_from_package('anuga.shallow_water')                
        testfile = os.path.join(path, 'tests', 'data', 'polygon_values_example.csv')                

        polygons, values = load_csv_as_polygons(testfile, 
                                        value_name='floors',
                                        clipping_polygons=None)

        assert len(polygons) == 7, 'Must have seven polygons'
        assert len(values) == 7, 'Must have seven values'
            
        # Known floor values
        floors = {'1': 2, '2': 0, '3': 1, '4': 2, '5': 0, '8': 1, '9': 1}
        
        # Known polygon values
        known_polys = {'1': [[422681.61,871117.55],
                             [422691.02,871117.60],
                             [422690.87,871084.23],
                             [422649.36,871081.85],
                             [422649.36,871080.39],
                             [422631.86,871079.50],
                             [422631.72,871086.75],
                             [422636.75,871087.20],
                             [422636.75,871091.50],
                             [422649.66,871092.09],
                             [422649.83,871084.91],
                             [422652.94,871084.90],
                             [422652.84,871092.39],
                             [422681.83,871093.73],
                             [422681.61,871117.55]],
                       '2': [[422664.22,870785.46],
                             [422672.48,870780.14],
                             [422668.17,870772.62],
                             [422660.35,870777.17],
                             [422664.22,870785.46]],
                       '3': [[422661.30,871215.06],
                             [422667.50,871215.70],
                             [422668.30,871204.86],
                             [422662.21,871204.33],
                             [422661.30,871215.06]],
                       '4': [[422473.44,871191.22],
                             [422478.33,871192.26],
                             [422479.52,871186.03],
                             [422474.78,871185.14],
                             [422473.44,871191.22]],
                       '5': [[422369.69,871049.29],
                             [422378.63,871053.58],
                             [422383.91,871044.51],
                             [422374.97,871040.32],
                             [422369.69,871049.29]],
                       '8': [[422730.56,871203.13],
                             [422734.10,871204.90],
                             [422735.26,871202.18],
                             [422731.87,871200.58],
                             [422730.56,871203.13]],
                       '9': [[422659.85,871213.80],
                             [422660.91,871210.97],
                             [422655.42,871208.85],
                             [422654.36,871211.68],
                             [422659.85,871213.80]]
                       }        
        

        
                
        for id in ['1', '2', '3', '4', '5' ,'8' ,'9']:
            assert id in polygons.keys()
            assert id in values.keys()            

            assert int(values[id]) == int(floors[id])
            assert len(polygons[id]) == len(known_polys[id])
            assert num.allclose(polygons[id], known_polys[id])
 def test_same_input_equals_outputN(self):
     test_path = aust.get_pathname_from_package('anuga.lib.tests')
     in_file = os.path.join(test_path, 'test1.asc')
     MaxAsc('test1.out.asc', [in_file] * 30)
     self.assertTrue(FilesEqual('test1.out.asc', in_file))
Esempio n. 21
0
from anuga.structures.boyd_box_operator import Boyd_box_operator
from anuga.structures.inlet_operator import Inlet_operator

#from anuga.culvert_flows.culvert_routines import boyd_generalised_culvert_model

from math import pi, pow, sqrt

import numpy as num
"""test_that_culvert_runs_rating

This test exercises the culvert and checks values outside rating curve
are dealt with       
"""

path = get_pathname_from_package('anuga.culvert_flows')

length = 40.
width = 15.

dx = dy = 0.5  # Resolution: Length of subdivisions on both axes

points, vertices, boundary = rectangular_cross(int(length / dx),
                                               int(width / dy),
                                               len1=length,
                                               len2=width)
domain = anuga.Domain(points, vertices, boundary)
domain.set_name('Test_gate_operator')  # Output name
domain.set_default_order(2)
#domain.set_beta(1.5)
    def test_predicted_boyd_flow(self):
        """test_predicted_boyd_flow
        
        Test that flows predicted by the boyd method are consistent with what what
        is calculated in engineering codes.
        The data was supplied by Petar Milevski
        """

        # FIXME(Ole) this is nowhere near finished
        path = get_pathname_from_package('anuga.culvert_flows')    
        
        length = 12.
        width = 5.

        dx = dy = 0.5           # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length/dx),
                                                       int(width/dy),
                                                       len1=length, 
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)   
        
        domain.set_name('test_culvert')                 # Output name
        domain.set_default_order(2)


        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            # General Slope of Topography
            z=-x/10
            
            return z


        domain.set_quantity('elevation', topography) 
        domain.set_quantity('friction', 0.01)         # Constant friction 
        domain.set_quantity('stage', expression='elevation')


        Q0 = domain.get_quantity('stage')
        Q1 = Quantity(domain)
        
        # Add depths to stage        
        head_water_depth = 0.169
        tail_water_depth = 0.089
        
        inlet_poly = [[0,0], [6,0], [6,5], [0,5]]
        outlet_poly = [[6,0], [12,0], [12,5], [6,5]]        
        
        Q1.set_values(Polygon_function([(inlet_poly, head_water_depth),
                                        (outlet_poly, tail_water_depth)]))
        
        domain.set_quantity('stage', Q0 + Q1)



        culvert = Culvert_flow(domain,
                               label='Test culvert',
                               description='4 m test culvert',   
                               end_point0=[4.0, 2.5], 
                               end_point1=[8.0, 2.5],
                               width=1.20, 
                               height=0.75,
                               culvert_routine=boyd_generalised_culvert_model,        
                               number_of_barrels=1,
                               verbose=False)
                               
        
        domain.forcing_terms.append(culvert)
        
        # Call
        culvert(domain)
    def OBSOLETE_XXXtest_that_culvert_rating_limits_flow_in_shallow_inlet_condition(self):
        """test_that_culvert_rating_limits_flow_in_shallow_inlet_condition
        
        Test that culvert on a sloping dry bed limits flows when very little water
        is present at inlet

        This one is using the rating curve variant
        """

        

        path = get_pathname_from_package('anuga.culvert_flows')    
        
        length = 40.
        width = 5.

        dx = dy = 1           # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length/dx),
                                                       int(width/dy),
                                                       len1=length, 
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)   
        domain.set_name('Test_culvert_shallow') # Output name
        domain.set_default_order(2)


        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z=-x/1000
            
            N = len(x)
            for i in range(N):

               # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face                
                    if  1.0+(x[i]-5.0)/5.0 <  y[i]  < 4.0 - (x[i]-5.0)/5.0: 
                       z[i]=z[i]
                    else:
                       z[i] +=  0.5*(x[i] -5.0)    # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                   z[i] +=  2.5                    # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face                
                    if  2.0-(x[i]-12.0)/2.5 <  y[i]  < 3.0 + (x[i]-12.0)/2.5:
                       z[i]=z[i]
                    else:
                       z[i] +=  2.5-1.0*(x[i] -12.0) # Sloping D/S Face
                		   
        		
            return z


        domain.set_quantity('elevation', topography) 
        domain.set_quantity('friction', 0.01)         # Constant friction 
        domain.set_quantity('stage',
                            expression='elevation + 0.1') # Shallow initial condition

        # Boyd culvert
        culvert = Culvert_flow(domain,
                               label='Culvert No. 1',
                               description='This culvert is a test unit 1.2m Wide by 0.75m High',   
                               end_point0=[9.0, 2.5], 
                               end_point1=[13.0, 2.5],
                               width=1.20, height=0.75,
                               culvert_routine=boyd_generalised_culvert_model,
                               number_of_barrels=1,
                               update_interval=2,
                               verbose=False)
        
        # Rating curve
        #filename = os.path.join(path, 'example_rating_curve.csv')
        #culvert = Culvert_flow(domain,
        #                       culvert_description_filename=filename,
        #                       end_point0=[9.0, 2.5], 
        #                       end_point1=[13.0, 2.5],
        #                       trigger_depth=0.01,
        #                       verbose=False)

        domain.forcing_terms.append(culvert)
        

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum

        Br = anuga.Reflective_boundary(domain)              # Solid reflective wall
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})


        
        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        print 'depth', 0.1
        ref_volume = domain.get_quantity('stage').get_integral()
        for t in domain.evolve(yieldstep = 0.1, finaltime = 25):
            new_volume = domain.get_quantity('stage').get_integral()

            msg = ('Total volume has changed: Is %.8f m^3 should have been %.8f m^3'
                   % (new_volume, ref_volume))
            assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg        
        
        
        return
        # Now try this again for a depth of 10 cm and for a range of other depths
        for depth in [0.1, 0.2, 0.5, 1.0]:
            print 'depth', depth
            domain.set_time(0.0)
            
            domain.set_quantity('elevation', topography) 
            domain.set_quantity('friction', 0.01)         # Constant friction 
            domain.set_quantity('stage',
                                expression='elevation + %f' % depth)
            
        
            ref_volume = domain.get_quantity('stage').get_integral()
            for t in domain.evolve(yieldstep = 0.1, finaltime = 25):
                new_volume = domain.get_quantity('stage').get_integral()
            
                msg = 'Total volume has changed: Is %.8f m^3 should have been %.8f m^3'\
                    % (new_volume, ref_volume)

                assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
Esempio n. 24
0
                z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
        if 10.0 < x[i] < 12.1:
            z[i] += 2.5  # Flat Crest of Embankment
        if 12.0 < x[i] < 14.5:
            # Cut Out Segment for Culvert face
            if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] - 12.0) / 2.5:
                z[i] = z[i]
            else:
                z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

    return z


#filename=os.path.join(path, 'example_rating_curve.csv')

mod_path = get_pathname_from_package('anuga.parallel')
line0 = [[10.0, 10.0], [30.0, 10.0]]
#line0 = [[29.0, 10.0], [30.0, 10.0]]
line1 = [[0.0, 10.0], [0.0, 15.0]]
Q0 = file_function(os.path.join(mod_path, 'data', 'test_hydrograph.tms'),
                   quantities=['hydrograph'])
Q1 = 5.0

samples = 50


def run_simulation(parallel=False,
                   control_data=None,
                   test_points=None,
                   verbose=False):
    success = True
Esempio n. 25
0
from anuga import Time_boundary
from anuga import Transmissive_boundary
from anuga import Transmissive_n_momentum_zero_t_momentum_set_stage_boundary

from anuga import rectangular_cross
from anuga import create_domain_from_file

from anuga import distribute, myid, numprocs, finalize, barrier

from anuga.utilities.system_tools import get_pathname_from_package

#--------------------------------------------------------------------------
# Setup parameters
#--------------------------------------------------------------------------

DATA_DIR = get_pathname_from_package('anuga.parallel')

mesh_filename = anuga.join(DATA_DIR, "data/merimbula_10785_1.tsh")
x0 = 756000.0
x1 = 756500.0
yieldstep = 10
finaltime = 100
#mesh_filename = anuga.join(DATA_DIR,"data/merimbula_17156.tsh")   ; x0 = 756000.0 ; x1 = 756500.0; yieldstep = 50; finaltime = 500
#mesh_filename = anuga.join(DATA_DIR,"data/merimbula_43200_1.tsh")   ; x0 = 756000.0 ; x1 = 756500.0; yieldstep = 50; finaltime = 500
#mesh_filename = anuga.join(DATA_DIR,"data/test-100.tsh") ; x0 = 200.0 ; x1 = 300.0; yieldstep = 1; finaltime = 10
#mesh_filename = anuga.join(DATA_DIR,"data/test-20.tsh") ; x0 = 250.0 ; x1 = 350.0; yieldstep = 1; finaltime = 50

verbose = False


#--------------------------------------------------------------------------
    def setUp(self):

        path = get_pathname_from_package('anuga.structures')
        self.input_hecras_file = os.path.join(path, 'tests', 'data', 'hecras_bridge_table.csv')

        return
Esempio n. 27
0
#from parallel_inlet_operator import Parallel_Inlet_operator
from anuga.parallel import distribute, myid, numprocs, finalize
from anuga.geometry.polygon import inside_polygon, is_inside_polygon, line_intersect

#from parallel_operator_factory import Inlet_operator, Boyd_box_operator
import pypar
import random


"""test_that_culvert_runs_rating

This test exercises the culvert and checks values outside rating curve
are dealt with       
"""
verbose = False
path = get_pathname_from_package('anuga.culvert_flows')    

length = 40.
width = 15.

dx = dy = 0.5          # Resolution: Length of subdivisions on both axes

#----------------------------------------------------------------------
# Setup initial conditions
#----------------------------------------------------------------------

def topography(x, y):
    """Set up a weir
    
    A culvert will connect either side
    """
    def test_Okada_func(self):
        from os import sep, getenv
        import sys
        from anuga.abstract_2d_finite_volumes.mesh_factory \
        import rectangular_cross

        from anuga.abstract_2d_finite_volumes.quantity import Quantity
        from anuga.utilities.system_tools import get_pathname_from_package
        """
        Pick the test you want to do; T= 0 test a point source,
        T= 1  test single rectangular source, T= 2 test multiple
        rectangular sources
        """
        # Get path where this test is run
        path = get_pathname_from_package('anuga.tsunami_source')

        # Choose what test to proceed
        T = 1

        if T == 0:
            # Fortran output file
            filename = path + sep + 'tests' + sep + 'data' + sep + 'fullokada_SP.txt'

            # Initial condition of earthquake for multiple source
            x0 = 7000.0
            y0 = 10000.0
            length = 0
            width = 0
            strike = 0.0
            depth = 15.0
            slip = 10.0
            dip = 15.0
            rake = 90.0
            ns = 1
            NSMAX = 1
        elif T == 1:
            # Fortran output file
            filename = path + sep + 'tests' + sep + 'data' + sep + 'fullokada_SS.txt'

            # Initial condition of earthquake for multiple source
            x0 = 7000.0
            y0 = 10000.0
            length = 10.0
            width = 6.0
            strike = 0.0
            depth = 15.0
            slip = 10.0
            dip = 15.0
            rake = 90.0
            ns = 1
            NSMAX = 1

        elif T == 2:

            # Fortran output file
            filename = path + sep + 'tests' + sep + 'data' + sep + 'fullokada_MS.txt'

            # Initial condition of earthquake for multiple source
            x0 = [7000.0, 10000.0]
            y0 = [10000.0, 7000.0]
            length = [10.0, 10.0]
            width = [6.0, 6.0]
            strike = [0.0, 0.0]
            depth = [15.0, 15.0]
            slip = [10.0, 10.0]
            dip = [15.0, 15.0]
            rake = [90.0, 90.0]
            ns = 2
            NSMAX = 2

        # Get output file from original okada fortran script.
        # Vertical displacement is listed under tmp.
        polyline_file = open(filename, 'r')
        lines = polyline_file.readlines()
        polyline_file.close()
        tmp = []
        stage = []
        for line in lines[0:]:
            field = line.split('    ')
            z = float(field[2])
            tmp.append(z)

        #create domain
        dx = dy = 4000
        l = 100000
        w = 100000

        #create topography
        def topography(x, y):
            el = -1000
            return el

        #print int(l/dx)
        #print int(w/dy)
        points, vertices, boundary = rectangular_cross(int(old_div(l, dx)),
                                                       int(old_div(w, dy)),
                                                       len1=l,
                                                       len2=w)
        domain = Domain(points, vertices, boundary)
        domain.set_name('test')
        domain.set_quantity('elevation', topography)

        #create variable with elevation data to implement in okada
        zrec0 = Quantity(domain)
        zrec0.set_values(0.0)
        zrec = zrec0.get_vertex_values(xy=True)
        # call okada
        Ts= Okada_func(ns=ns, NSMAX=NSMAX,length=length, width=width, dip=dip, \
                       x0=x0, y0=y0, strike=strike, depth=depth, \
                       slip=slip, rake=rake,zrec=zrec)

        #create a variable to store vertical displacement throughout the domain
        tsunami = Quantity(domain)
        tsunami.set_values(Ts)

        # get vertical displacement at each point of the domain respecting
        # original script's order
        interpolation_points = []
        k = 0.0
        for i in range(0, 6):
            for j in range(0, 6):
                p = j * 4000
                Yt = p
                Xt = k
                interpolation_points.append([Xt, Yt])

            k = k + 4000
        Z = tsunami.get_values(interpolation_points=interpolation_points,
                               location='edges')

        stage = -Z  # FIXME(Ole): Why the sign flip?
        # Displacement in fortran code is looking downward
        #print tmp
        #print 'hello',stage
        assert num.allclose(stage, tmp, atol=1.e-3)
from anuga import Transmissive_boundary
from anuga import Transmissive_n_momentum_zero_t_momentum_set_stage_boundary

from anuga import rectangular_cross
from anuga import create_domain_from_file


from anuga import distribute, myid, numprocs, finalize, barrier

from anuga.utilities.system_tools import get_pathname_from_package

#--------------------------------------------------------------------------
# Setup parameters
#--------------------------------------------------------------------------

DATA_DIR = get_pathname_from_package('anuga.parallel')

mesh_filename = anuga.join(DATA_DIR,"data/merimbula_10785_1.tsh") ; x0 = 756000.0 ; x1 = 756500.0; yieldstep = 10; finaltime = 100
#mesh_filename = anuga.join(DATA_DIR,"data/merimbula_17156.tsh")   ; x0 = 756000.0 ; x1 = 756500.0; yieldstep = 50; finaltime = 500
#mesh_filename = anuga.join(DATA_DIR,"data/merimbula_43200_1.tsh")   ; x0 = 756000.0 ; x1 = 756500.0; yieldstep = 50; finaltime = 500
#mesh_filename = anuga.join(DATA_DIR,"data/test-100.tsh") ; x0 = 200.0 ; x1 = 300.0; yieldstep = 1; finaltime = 10
#mesh_filename = anuga.join(DATA_DIR,"data/test-20.tsh") ; x0 = 250.0 ; x1 = 350.0; yieldstep = 1; finaltime = 50

verbose = False

#--------------------------------------------------------------------------
# Setup procedures
#--------------------------------------------------------------------------
class Set_Stage:
    """Set an initial condition with constant water height, for x0<x<x1
    """
    def test_that_culvert_runs_rating(self):
        """test_that_culvert_runs_rating
        
        This test exercises the culvert and checks values outside rating curve
        are dealt with       
        """

        path = get_pathname_from_package('anuga.culvert_flows')    
        path = os.path.join(path, 'tests', 'data')
        
        length = 40.
        width = 5.

        dx = dy = 1           # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length/dx),
                                                       int(width/dy),
                                                       len1=length, 
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)   
        domain.set_name('Test_culvert')                 # Output name
        domain.set_default_order(2)


        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z=-x/1000
            
            N = len(x)
            for i in range(N):

               # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face                
                    if  1.0+(x[i]-5.0)/5.0 <  y[i]  < 4.0 - (x[i]-5.0)/5.0: 
                       z[i]=z[i]
                    else:
                       z[i] +=  0.5*(x[i] -5.0)    # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                   z[i] +=  2.5                    # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face                
                    if  2.0-(x[i]-12.0)/2.5 <  y[i]  < 3.0 + (x[i]-12.0)/2.5:
                       z[i]=z[i]
                    else:
                       z[i] +=  2.5-1.0*(x[i] -12.0) # Sloping D/S Face
                		   
        		
            return z


        domain.set_quantity('elevation', topography) 
        domain.set_quantity('friction', 0.01)         # Constant friction 
        domain.set_quantity('stage',
                            expression='elevation')   # Dry initial condition

        filename=os.path.join(path, 'example_rating_curve.csv')
        culvert = Culvert_flow(domain,
                               culvert_description_filename=filename,        
                               end_point0=[9.0, 2.5], 
                               end_point1=[13.0, 2.5],
                               width=1.00,
                               use_velocity_head=True,
                               verbose=False)

        domain.forcing_terms.append(culvert)
        

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum
        Bi = anuga.Dirichlet_boundary([0.0, 0.0, 0.0])
        Br = anuga.Reflective_boundary(domain)              # Solid reflective wall
        Bo = anuga.Dirichlet_boundary([-5, 0, 0])           # Outflow
        
        # Upstream and downstream conditions that will exceed the rating curve
        # I.e produce delta_h outside the range [0, 10] specified in the the 
        # file example_rating_curve.csv
        Btus = anuga.Time_boundary(domain, \
                    lambda t: [100*num.sin(2*pi*(t-4)/10), 0.0, 0.0])
        Btds = anuga.Time_boundary(domain, \
                    lambda t: [-5*(num.cos(2*pi*(t-4)/20)), 0.0, 0.0])
        domain.set_boundary({'left': Btus, 'right': Btds, 'top': Br, 'bottom': Br})


        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        min_delta_w = sys.maxint 
        max_delta_w = -min_delta_w
        for t in domain.evolve(yieldstep = 1, finaltime = 25):
            delta_w = culvert.inlet.stage - culvert.outlet.stage
            
            if delta_w > max_delta_w: max_delta_w = delta_w
            if delta_w < min_delta_w: min_delta_w = delta_w            
            
            pass

        # Check that extreme values in rating curve have been exceeded
        # so that we know that condition has been exercised
        assert min_delta_w < 0
        assert max_delta_w > 10        


        os.remove('Test_culvert.sww')
from anuga import Dirichlet_boundary
from anuga import Time_boundary
from anuga import Transmissive_boundary

from anuga import rectangular_cross
from anuga import create_domain_from_file


from anuga import distribute, myid, numprocs, finalize


#--------------------------------------------------------------------------
# Setup parameters
#--------------------------------------------------------------------------

mod_path = get_pathname_from_package('anuga.parallel')

mesh_filename = os.path.join(mod_path,'data','merimbula_10785_1.tsh')
#mesh_filename = os.path.join('..','data','test-100.tsh')
yieldstep = 1
finaltime = 1
quantity = 'stage'
nprocs = 2
verbose = False

#--------------------------------------------------------------------------
# Setup procedures
#--------------------------------------------------------------------------
class Set_Stage:
    """Set an initial condition with constant water height, for x<x0
    """
    def test_that_culvert_dry_bed_boyd_does_not_produce_flow(self):
        """test_that_culvert_in_dry_bed_boyd_does_not_produce_flow(self):
        
        Test that culvert on a sloping dry bed doesn't produce flows
        although there will be a 'pressure' head due to delta_w > 0

        This one is using the 'Boyd' variant        
        """

        path = get_pathname_from_package('anuga.culvert_flows')    
        
        length = 40.
        width = 5.

        dx = dy = 1           # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length/dx),
                                                       int(width/dy),
                                                       len1=length, 
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)   
        domain.set_name('Test_culvert_dry') # Output name
        domain.set_default_order(2)


        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z=-x/1000
            
            N = len(x)
            for i in range(N):

               # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face                
                    if  1.0+(x[i]-5.0)/5.0 <  y[i]  < 4.0 - (x[i]-5.0)/5.0: 
                       z[i]=z[i]
                    else:
                       z[i] +=  0.5*(x[i] -5.0)    # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                   z[i] +=  2.5                    # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face                
                    if  2.0-(x[i]-12.0)/2.5 <  y[i]  < 3.0 + (x[i]-12.0)/2.5:
                       z[i]=z[i]
                    else:
                       z[i] +=  2.5-1.0*(x[i] -12.0) # Sloping D/S Face
                		   
        		
            return z


        domain.set_quantity('elevation', topography) 
        domain.set_quantity('friction', 0.01)         # Constant friction 
        domain.set_quantity('stage',
                            expression='elevation')   # Dry initial condition


        filename = os.path.join(path, 'example_rating_curve.csv')


        culvert = Culvert_flow(domain,
                               label='Culvert No. 1',
                               description='This culvert is a test unit 1.2m Wide by 0.75m High',   
                               end_point0=[9.0, 2.5], 
                               end_point1=[13.0, 2.5],
                               width=1.20, height=0.75,
                               culvert_routine=boyd_generalised_culvert_model,
                               number_of_barrels=1,
                               update_interval=2,
                               verbose=False)
        
        domain.forcing_terms.append(culvert)
        

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum

        Br = anuga.Reflective_boundary(domain)              # Solid reflective wall
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})


        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        ref_volume = domain.get_quantity('stage').get_integral()
        for t in domain.evolve(yieldstep = 1, finaltime = 25):
            
            new_volume = domain.get_quantity('stage').get_integral()

            msg = 'Total volume has changed'
            assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
            pass
     
from math import pi, pow, sqrt

import numpy as num





"""test_that_culvert_runs_rating

This test exercises the culvert and checks values outside rating curve
are dealt with       
"""

path = get_pathname_from_package('anuga.culvert_flows')    

length = 40.
width = 15.

dx = dy = 0.5          # Resolution: Length of subdivisions on both axes

points, vertices, boundary = rectangular_cross(int(length/dx),
                                               int(width/dy),
                                               len1=length, 
                                               len2=width)
domain = anuga.Domain(points, vertices, boundary)   
domain.set_name('run_gate_operator')                 # Output name
domain.set_default_order(2)
#domain.set_beta(1.5)
    def test_earthquake_tsunami(self):
        from os import sep, getenv
        import sys
        from anuga.abstract_2d_finite_volumes.mesh_factory \
                        import rectangular_cross
        from anuga.abstract_2d_finite_volumes.quantity import Quantity
        from anuga.utilities.system_tools import get_pathname_from_package
        """
        Pick the test you want to do; T= 0 test a point source,
        T= 1  test single rectangular source, T= 2 test multiple
        rectangular sources
        """

        # Get path where this test is run
        path= get_pathname_from_package('anuga.tsunami_source')
        
        # Choose what test to proceed
        T=1

        if T==0:
            # Fortran output file
            filename = path+sep+'tests'+sep+'data'+sep+'fullokada_SP.txt'
            
            # Initial condition of earthquake for multiple source
            x0 = 7000.0
            y0 = 10000.0
            length = 0
            width =0
            strike = 0.0
            depth = 15.0
            slip = 10.0
            dip =15.0
            rake =90.0
            ns=1
            NSMAX=1
        elif T==1:
            # Fortran output file
            filename = path+sep+'tests'+sep+'data'+sep+'fullokada_SS.txt'
            
            # Initial condition of earthquake for multiple source
            x0 = 7000.0
            y0 = 10000.0
            length = 10.0
            width =6.0
            strike = 0.0
            depth = 15.0
            slip = 10.0
            dip =15.0
            rake =90.0
            ns=1
            NSMAX=1
            
        elif T==2:

            # Fortran output file
            filename = path+sep+'tests'+sep+'data'+sep+'fullokada_MS.txt'
            
            # Initial condition of earthquake for multiple source
            x0 = [7000.0,10000.0]
            y0 = [10000.0,7000.0]
            length = [10.0,10.0]
            width =[6.0,6.0]
            strike = [0.0,0.0]
            depth = [15.0,15.0]
            slip = [10.0,10.0]
            dip = [15.0,15.0]
            rake = [90.0,90.0]
            ns=2
            NSMAX=2



        # Get output file from original okada fortran script.
        # Vertical displacement is listed under tmp.
        polyline_file=open(filename,'r')
        lines=polyline_file.readlines()
        polyline_file.close()
        tmp=[]
        stage=[]
        for line in lines [0:]:
            field = line.split('    ')
            z=float(field[2])
            tmp.append(z)

         
        # Create domain 
        dx = dy = 4000
        l=20000
        w=20000
        
        # Create topography
        def topography(x,y):
            el=-1000
            return el
        
        points, vertices, boundary = rectangular_cross(int(l/dx), int(w/dy),
                                               len1=l, len2=w)
        domain = Domain(points, vertices, boundary)   
        domain.set_name('test')
        domain.set_quantity('elevation',topography)
        Ts = earthquake_tsunami(ns=ns,NSMAX=NSMAX,length=length, width=width, strike=strike,\
                                depth=depth,dip=dip, xi=x0, yi=y0,z0=0, slip=slip, rake=rake,\
                                domain=domain, verbose=False)
        
        # Create a variable to store vertical displacement throughout the domain
        tsunami = Quantity(domain)
        tsunami.set_values(Ts)
        interpolation_points=[]

        #k=0.0
        #for i in range(0,6):
        #    for j in range(0,6):
        #        p=j*4000
        #        Yt=p
        #        Xt=k
        #        Z=tsunami.get_values(interpolation_points=[[Xt,Yt]]
        #                             ,location='edges')
        #        stage.append(-Z[0])
        #    k=k+4000
        #
        #assert allclose(stage,tmp,atol=1.e-3)

        # Here's a faster way - try that in the first test
        interpolation_points=[]
        k=0.0
        for i in range(0,6):
            for j in range(0,6):
                p=j*4000
                Yt=p
                Xt=k
                interpolation_points.append([Xt, Yt])

            k=k+4000
        Z=tsunami.get_values(interpolation_points=interpolation_points,
                             location='edges')

        stage = -Z # FIXME(Ole): Why the sign flip?
                   # Displacement in fortran code is looking downward
        #print 'c est fini'
        #print tmp
        #print 'hello',stage   
        assert num.allclose(stage,tmp,atol=1.e-3)
    def test_that_culvert_runs_rating(self):
        """test_that_culvert_runs_rating
        
        This test exercises the culvert and checks values outside rating curve
        are dealt with       
        """

        path = get_pathname_from_package('anuga.culvert_flows')
        path = os.path.join(path, 'tests', 'data')

        length = 40.
        width = 5.

        dx = dy = 1  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)
        domain.set_name('Test_culvert')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z = -x / 1000

            N = len(x)
            for i in range(N):

                # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face
                    if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] -
                                                                5.0) / 5.0:
                        z[i] = z[i]
                    else:
                        z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                    z[i] += 2.5  # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face
                    if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] -
                                                                 12.0) / 2.5:
                        z[i] = z[i]
                    else:
                        z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity('stage',
                            expression='elevation')  # Dry initial condition

        filename = os.path.join(path, 'example_rating_curve.csv')
        culvert = Culvert_flow(domain,
                               culvert_description_filename=filename,
                               end_point0=[9.0, 2.5],
                               end_point1=[13.0, 2.5],
                               width=1.00,
                               use_velocity_head=True,
                               verbose=False)

        domain.forcing_terms.append(culvert)

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum
        Bi = anuga.Dirichlet_boundary([0.0, 0.0, 0.0])
        Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
        Bo = anuga.Dirichlet_boundary([-5, 0, 0])  # Outflow

        # Upstream and downstream conditions that will exceed the rating curve
        # I.e produce delta_h outside the range [0, 10] specified in the the
        # file example_rating_curve.csv
        Btus = anuga.Time_boundary(
            domain, lambda t: [100 * num.sin(2 * pi * (t - 4) / 10), 0.0, 0.0])
        Btds = anuga.Time_boundary(
            domain,
            lambda t: [-5 * (num.cos(2 * pi * (t - 4) / 20)), 0.0, 0.0])
        domain.set_boundary({
            'left': Btus,
            'right': Btds,
            'top': Br,
            'bottom': Br
        })

        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        min_delta_w = sys.maxint
        max_delta_w = -min_delta_w
        for t in domain.evolve(yieldstep=1, finaltime=25):
            delta_w = culvert.inlet.stage - culvert.outlet.stage

            if delta_w > max_delta_w: max_delta_w = delta_w
            if delta_w < min_delta_w: min_delta_w = delta_w

            pass

        # Check that extreme values in rating curve have been exceeded
        # so that we know that condition has been exercised
        assert min_delta_w < 0
        assert max_delta_w > 10

        os.remove('Test_culvert.sww')
Esempio n. 36
0
 def test_same_input_equals_outputN(self):
     test_path = aust.get_pathname_from_package('anuga.lib.tests')
     in_file = os.path.join(test_path, 'test1.asc')
     MaxAsc('test1.out.asc', [in_file] * 30)
     self.assertTrue(FilesEqual('test1.out.asc', in_file))
    def OBSOLETE_XXXtest_that_culvert_rating_limits_flow_in_shallow_inlet_condition(
            self):
        """test_that_culvert_rating_limits_flow_in_shallow_inlet_condition
        
        Test that culvert on a sloping dry bed limits flows when very little water
        is present at inlet

        This one is using the rating curve variant
        """

        path = get_pathname_from_package('anuga.culvert_flows')

        length = 40.
        width = 5.

        dx = dy = 1  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)
        domain.set_name('Test_culvert_shallow')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z = -x / 1000

            N = len(x)
            for i in range(N):

                # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face
                    if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] -
                                                                5.0) / 5.0:
                        z[i] = z[i]
                    else:
                        z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                    z[i] += 2.5  # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face
                    if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] -
                                                                 12.0) / 2.5:
                        z[i] = z[i]
                    else:
                        z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity(
            'stage', expression='elevation + 0.1')  # Shallow initial condition

        # Boyd culvert
        culvert = Culvert_flow(
            domain,
            label='Culvert No. 1',
            description='This culvert is a test unit 1.2m Wide by 0.75m High',
            end_point0=[9.0, 2.5],
            end_point1=[13.0, 2.5],
            width=1.20,
            height=0.75,
            culvert_routine=boyd_generalised_culvert_model,
            number_of_barrels=1,
            update_interval=2,
            verbose=False)

        # Rating curve
        #filename = os.path.join(path, 'example_rating_curve.csv')
        #culvert = Culvert_flow(domain,
        #                       culvert_description_filename=filename,
        #                       end_point0=[9.0, 2.5],
        #                       end_point1=[13.0, 2.5],
        #                       trigger_depth=0.01,
        #                       verbose=False)

        domain.forcing_terms.append(culvert)

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum

        Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        print 'depth', 0.1
        ref_volume = domain.get_quantity('stage').get_integral()
        for t in domain.evolve(yieldstep=0.1, finaltime=25):
            new_volume = domain.get_quantity('stage').get_integral()

            msg = (
                'Total volume has changed: Is %.8f m^3 should have been %.8f m^3'
                % (new_volume, ref_volume))
            assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg

        return
        # Now try this again for a depth of 10 cm and for a range of other depths
        for depth in [0.1, 0.2, 0.5, 1.0]:
            print 'depth', depth
            domain.set_time(0.0)

            domain.set_quantity('elevation', topography)
            domain.set_quantity('friction', 0.01)  # Constant friction
            domain.set_quantity('stage', expression='elevation + %f' % depth)

            ref_volume = domain.get_quantity('stage').get_integral()
            for t in domain.evolve(yieldstep=0.1, finaltime=25):
                new_volume = domain.get_quantity('stage').get_integral()

                msg = 'Total volume has changed: Is %.8f m^3 should have been %.8f m^3'\
                    % (new_volume, ref_volume)

                assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
Esempio n. 38
0
 def test_unequal_lines(self):
     test_path = aust.get_pathname_from_package('anuga.lib.tests')
     in_file = os.path.join(test_path, 'test1.asc')
     expected_file = os.path.join(test_path, 'test1_bad_num_lines.asc')
     self.assertRaises(RuntimeError, MaxAsc, 'test.out.asc',
                       [in_file, expected_file])
    def test_that_culvert_dry_bed_boyd_does_not_produce_flow(self):
        """test_that_culvert_in_dry_bed_boyd_does_not_produce_flow(self):
        
        Test that culvert on a sloping dry bed doesn't produce flows
        although there will be a 'pressure' head due to delta_w > 0

        This one is using the 'Boyd' variant        
        """

        path = get_pathname_from_package('anuga.culvert_flows')

        length = 40.
        width = 5.

        dx = dy = 1  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)
        domain.set_name('Test_culvert_dry')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z = -x / 1000

            N = len(x)
            for i in range(N):

                # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face
                    if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] -
                                                                5.0) / 5.0:
                        z[i] = z[i]
                    else:
                        z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                    z[i] += 2.5  # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face
                    if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] -
                                                                 12.0) / 2.5:
                        z[i] = z[i]
                    else:
                        z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity('stage',
                            expression='elevation')  # Dry initial condition

        filename = os.path.join(path, 'example_rating_curve.csv')

        culvert = Culvert_flow(
            domain,
            label='Culvert No. 1',
            description='This culvert is a test unit 1.2m Wide by 0.75m High',
            end_point0=[9.0, 2.5],
            end_point1=[13.0, 2.5],
            width=1.20,
            height=0.75,
            culvert_routine=boyd_generalised_culvert_model,
            number_of_barrels=1,
            update_interval=2,
            verbose=False)

        domain.forcing_terms.append(culvert)

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum

        Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        ref_volume = domain.get_quantity('stage').get_integral()
        for t in domain.evolve(yieldstep=1, finaltime=25):

            new_volume = domain.get_quantity('stage').get_integral()

            msg = 'Total volume has changed'
            assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
            pass