def test_create_mesh_from_regions_check_segs(self):
        '''Test that create_mesh_from_regions fails
        when an interior region is outside bounding polygon.
        '''

        # These are the absolute values
        min_x = 10
        min_y = 88
        polygon = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]]
        boundary_tags = {'walls': [0,1,3], 'bom': [2]}

        # This one is inside bounding polygon - should pass
        inner_polygon = [[800,400], [900,500], [800,600]]
        interior_regions = [(inner_polygon, 5)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions)

        boundary_tags = {'walls': [0,1,3,4], 'bom': [2]}
        try:
            m = create_mesh_from_regions(polygon,
                                         boundary_tags,
                                         10000000,
                                         interior_regions=interior_regions)
        except:
            pass
        else:
            msg = 'Segment out of bounds not caught '
            raise Exception, msg
    def test_create_mesh_from_regions5(self):
        file_name = tempfile.mktemp('.tsh')

        # These are the absolute values
        density_outer = 10000000
        min_outer = 0
        max_outer = 1000
        polygon_outer = [[min_outer,min_outer], [max_outer,min_outer],
                         [max_outer,max_outer], [min_outer,max_outer]]

        density_inner1 = 1000
        inner_buffer = 100
        min_inner1 = min_outer + inner_buffer
        max_inner1 = max_outer - inner_buffer
        inner1_polygon = [[min_inner1,min_inner1], [max_inner1,min_inner1],
                          [max_inner1,max_inner1], [min_inner1,max_inner1]]

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}

        interior_regions = [(inner1_polygon, density_inner1)]
        create_mesh_from_regions(polygon_outer,
                                 boundary_tags,
                                 density_outer,
                                 interior_regions=interior_regions,
                                 filename=file_name,
                                 verbose=False)

        m = importMeshFromFile(file_name)
        self.assertTrue(len(m.getTriangulation()) <= 2000,
                        'Test mesh interface failed!')
        self.assertTrue(len(m.getTriangulation()) >= 900,
                        'Test mesh interface failed!')

        os.remove(file_name)
Exemplo n.º 3
0
    def test_slide_tsunami_domain(self):

        if anuga_installed:
            pass
        else:
            print 'Note: test_slide_tsunami_domain not tested as ANUGA '\
                'is not installed'
            return
        length = 600.0
        dep = 150.0
        th = 9.0
        thk = 15.0
        wid = 340.0
        kappa = 3.0
        kappad = 0.8
        x0 = 100000.
        y0 = x0
        
        from anuga.pmesh.mesh_interface import create_mesh_from_regions
        polygon = [[0,0],[200000,0],[200000,200000],[0,200000]]
        create_mesh_from_regions(polygon,
                                 {'e0': [0], 'e1': [1], 'e2': [2], 'e3': [3]},
                                 maximum_triangle_area=5000000000,
                                 filename='test.msh',
                                 verbose = False)

        domain = Domain('test.msh', use_cache = True, verbose = False)

        slide = slide_tsunami(length, dep, th, x0, y0, \
                              wid, thk, kappa, kappad, \
                              domain=domain,verbose=False)

        domain.set_quantity('stage', slide)
        stage = domain.get_quantity('stage')
        w = stage.get_values()

##        check = [[-0.0 -0.0 -0.0],
##                 [-.189709745 -517.877716 -0.0],
##                 [-0.0 -0.0 -2.7695931e-08],
##                 [-0.0 -2.7695931e-08 -1.897097e-01]
##                 [-0.0 -517.877716 -0.0],
##                 [-0.0 -0.0 -0.0],
##                 [-0.0 -0.0 -0.0],
##                 [-0.0 -0.0 -0.0]]

        assert num.allclose(num.min(w), -517.877771593)
        assert num.allclose(num.max(w), 0.0)
        assert num.allclose(slide.a3D, 518.38797486)
    def test_create_mesh_with_segments_out_of_bounds(self):
        """Test that create_mesh_from_regions fails when a segment is out of bounds.
        """
        
        # These are the absolute values
        min_x = 10 
        min_y = 88
        polygon = [[min_x,min_y],[1000,100],[1000,1000],[100,1000]]

        
        boundary_tags = {'walls': [0,1], 'bom':[2,3], 'out': [5]}

        # This one is inside bounding polygon - should pass
        inner_polygon = [[800,400],[900,500],[800,600]]
        
        interior_regions = [(inner_polygon, 5)]


        try:
            m = create_mesh_from_regions(polygon,
                                         boundary_tags,
                                         10000000,
                                         interior_regions=interior_regions)
        except:
            pass
        else:
            msg = 'Tags are listed repeatedly, but create mesh from regions '
            msg += 'does not cause an Exception to be raised'
            raise Exception, msg
    def test_create_mesh_with_interior_holes_and_tags(self):
        # These are the absolute values
        polygon = [[100,100], [1000,100], [1000,1000], [100,1000]]
        
        interior_poly1 = [[101,101],[200,200], [101,200]]
        interior_poly2 = [[300,300],[500,500], [400,200]]

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}


        # This should work with one hole
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_holes=[interior_poly1],
                                     hole_tags=[{'edge0' : [0], 'edge1': [1], 'edge2': [2]}])

        self.assertTrue(len(m.getUserSegments()) == 7, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 7, 'FAILED!')

        m.generate_mesh()
        
        tags_list = m.getMeshSegmentTags()
        
        assert len([x for x in tags_list if x == 'edge0']) == 7
        assert len([x for x in tags_list if x == 'edge1']) == 6
        assert len([x for x in tags_list if x == 'edge2']) == 54              
Exemplo n.º 6
0
def create_mesh(elevation_in_mesh=False, verbose=False):
    # Prepare time boundary
    prepare_timeboundary(project.boundary_filename, verbose)

    

    

    meshname = project.mesh_filename + '.msh'
    m = create_mesh_from_regions(bounding_polygon,
                                 boundary_tags={'wall': [0, 1, 3],
                                                'wave': [2]},     
                                 maximum_triangle_area=0.1*base_resolution,
                                 interior_regions=interior_regions,
                                 filename=project.mesh_filename,
                                 use_cache=False,
                                 verbose=verbose)


    
    if elevation_in_mesh is True:
        from anuga.fit_interpolate.fit import fit_to_mesh_file


        if verbose: print 'Reading xya from zip'
        import zipfile as zf
        zf.ZipFile(project.bathymetry_filename_stem+'.zip').\
          extract(project.bathymetry_filename_stem+'.xya')

        if verbose: print 'Reading pts from xya'
        anuga.xya2pts(project.bathymetry_filename_stem+'.xya',\
                      verbose = verbose)
        
        fit_to_mesh_file(project.mesh_filename, project.bathymetry_filename,
                         project.mesh_filename, verbose = verbose)
def _create_domain_from_regions_sed(bounding_polygon,
                                boundary_tags,
                                maximum_triangle_area=None,
                                mesh_filename=None,                           
                                interior_regions=None,
                                interior_holes=None,
                                hole_tags=None,
                                poly_geo_reference=None,
                                mesh_geo_reference=None,
                                minimum_triangle_angle=28.0,
                                conserved_quantities=None,
                                evolved_quantities=None,
                                other_quantities=None,
                                fail_if_polygons_outside=True,
                                verbose=True):
    """_create_domain_from_regions_sed - internal function.

    See create_domain_from_regions in anuga/__init__.py for documentation.
    """

    from anuga.pmesh.mesh_interface import create_mesh_from_regions
    
    create_mesh_from_regions(bounding_polygon,
                             boundary_tags,
                             maximum_triangle_area=maximum_triangle_area,
                             interior_regions=interior_regions,
                             filename=mesh_filename,
                             interior_holes=interior_holes,
                             hole_tags=hole_tags,
                             poly_geo_reference=poly_geo_reference,
                             mesh_geo_reference=mesh_geo_reference,
                             minimum_triangle_angle=minimum_triangle_angle,
                             fail_if_polygons_outside=fail_if_polygons_outside,
                             use_cache=False,
                             verbose=verbose)

    domain = Domain(mesh_filename, 
                    conserved_quantities=conserved_quantities, 
                    evolved_quantities=evolved_quantities, 
                    other_quantities=other_quantities, 
                    use_cache=False, 
                    verbose=verbose)


    return domain
    def test_create_mesh_from_regions7(self):
        file_name = tempfile.mktemp('.tsh')

        # These are the absolute values
        density_outer = 1001
        min_outer = 0
        max_outer = 1000
        polygon_outer = [[min_outer,min_outer], [max_outer,min_outer],
                         [max_outer,max_outer], [min_outer,max_outer]]

        delta = 10
        density_inner1 = 100000000
        min_inner1 = min_outer + delta
        max_inner1 = max_outer - delta
        inner1_polygon = [[min_inner1,min_inner1], [max_inner1,min_inner1],
                          [max_inner1,max_inner1], [min_inner1,max_inner1]]

        density_inner2 = 1000
        min_inner2 = min_outer +  2*delta
        max_inner2 = max_outer -  2*delta
        inner2_polygon = [[min_inner2,min_inner2], [max_inner2,min_inner2],
                          [max_inner2,max_inner2], [min_inner2,max_inner2]]

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}

        # Note the list order is important
        # The last region added will be the region triangle uses,
        # if two regions points are in the same bounded area.
        interior_regions = [(inner2_polygon, density_inner2),
                            (inner1_polygon, density_inner1)]
        create_mesh_from_regions(polygon_outer,
                                 boundary_tags,
                                 density_outer,
                                 interior_regions=interior_regions,
                                 filename=file_name,
                                 verbose=False)

        m = importMeshFromFile(file_name)
        self.assertTrue(len(m.getTriangulation()) <= 3000,
                        'Test mesh interface failed!')
        self.assertTrue(len(m.getTriangulation()) >= 2000,
                        'Test mesh interface failed!')

        os.remove(file_name)
    def concept_create_mesh_from_regions_with_ungenerate(self):
        x=0
        y=0
        mesh_geo = geo_reference=Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0,0], [100,0], [100,100], [0,100]]
        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0,1], 'bom': [2]}

        inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]]
        inner2_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner2_polygon_absolute)

        max_area = 10000000
        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     max_area,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo)

        m.export_mesh_file('a_test_mesh_iknterface.tsh')

        fileName = tempfile.mktemp('.txt')
        file = open(fileName, 'w')
        file.write('         1       ??      ??\n\
       90.0       90.0\n\
       81.0       90.0\n\
       81.0       81.0\n\
       90.0       81.0\n\
       90.0       90.0\n\
END\n\
         2      ?? ??\n\
       10.0       80.0\n\
       10.0       90.0\n\
       20.0       90.0\n\
       10.0       80.0\n\
END\n\
END\n')
        file.close()

        m.import_ungenerate_file(fileName, tag='wall')
        os.remove(fileName)
        m.generate_mesh(maximum_triangle_area=max_area, verbose=False)
        m.export_mesh_file('b_test_mesh_iknterface.tsh')
Exemplo n.º 10
0
def _create_domain_from_regions(bounding_polygon,
                                boundary_tags,
                                maximum_triangle_area=None,
                                mesh_filename=None,                           
                                interior_regions=None,
                                interior_holes=None,
                                hole_tags=None,
                                poly_geo_reference=None,
                                mesh_geo_reference=None,
                                breaklines=None,
                                regionPtArea=None,
                                minimum_triangle_angle=28.0,
                                fail_if_polygons_outside=True,
                                verbose=True):
    """_create_domain_from_regions - internal function.

    See create_domain_from_regions for documentation.
    """

    #from anuga.shallow_water.shallow_water_domain import Domain
    from anuga.pmesh.mesh_interface import create_mesh_from_regions
    
    create_mesh_from_regions(bounding_polygon,
                             boundary_tags,
                             maximum_triangle_area=maximum_triangle_area,
                             interior_regions=interior_regions,
                             filename=mesh_filename,
                             interior_holes=interior_holes,
                             hole_tags=hole_tags,
                             poly_geo_reference=poly_geo_reference,
                             mesh_geo_reference=mesh_geo_reference,
                             breaklines=breaklines,
                             regionPtArea=regionPtArea,
                             minimum_triangle_angle=minimum_triangle_angle,
                             fail_if_polygons_outside=fail_if_polygons_outside,
                             use_cache=False,
                             verbose=verbose)

    domain = Domain(mesh_filename, use_cache=False, verbose=verbose)


    return domain
Exemplo n.º 11
0
def _create_domain_from_regions(bounding_polygon,
                                boundary_tags,
                                maximum_triangle_area=None,
                                mesh_filename=None,
                                interior_regions=None,
                                interior_holes=None,
                                hole_tags=None,
                                poly_geo_reference=None,
                                mesh_geo_reference=None,
                                breaklines=None,
                                regionPtArea=None,
                                minimum_triangle_angle=28.0,
                                fail_if_polygons_outside=True,
                                verbose=True):
    """_create_domain_from_regions - internal function.

    See create_domain_from_regions for documentation.
    """

    #from anuga.shallow_water.shallow_water_domain import Domain
    from anuga.pmesh.mesh_interface import create_mesh_from_regions

    create_mesh_from_regions(bounding_polygon,
                             boundary_tags,
                             maximum_triangle_area=maximum_triangle_area,
                             interior_regions=interior_regions,
                             filename=mesh_filename,
                             interior_holes=interior_holes,
                             hole_tags=hole_tags,
                             poly_geo_reference=poly_geo_reference,
                             mesh_geo_reference=mesh_geo_reference,
                             breaklines=breaklines,
                             regionPtArea=regionPtArea,
                             minimum_triangle_angle=minimum_triangle_angle,
                             fail_if_polygons_outside=fail_if_polygons_outside,
                             use_cache=False,
                             verbose=verbose)

    domain = Domain(mesh_filename, use_cache=False, verbose=verbose)

    return domain
Exemplo n.º 12
0
    def test_create_mesh_from_regions6(self):
        file_name = tempfile.mktemp('.tsh')

        # These are the absolute values
        density_outer = 1000
        min_outer = 0
        max_outer = 1000
        polygon_outer = [[min_outer, min_outer], [max_outer, min_outer],
                         [max_outer, max_outer], [min_outer, max_outer]]

        delta = 10
        density_inner1 = 1000
        min_inner1 = min_outer + delta
        max_inner1 = max_outer - delta
        inner1_polygon = [[min_inner1, min_inner1], [max_inner1, min_inner1],
                          [max_inner1, max_inner1], [min_inner1, max_inner1]]

        density_inner2 = 10000000
        min_inner2 = min_outer + 2 * delta
        max_inner2 = max_outer - 2 * delta
        inner2_polygon = [[min_inner2, min_inner2], [max_inner2, min_inner2],
                          [max_inner2, max_inner2], [min_inner2, max_inner2]]

        boundary_tags = {'walls': [0, 1], 'bom': [2, 3]}

        interior_regions = [(inner1_polygon, density_inner1),
                            (inner2_polygon, density_inner2)]
        create_mesh_from_regions(polygon_outer,
                                 boundary_tags,
                                 density_outer,
                                 interior_regions=interior_regions,
                                 filename=file_name,
                                 verbose=False)

        m = importMeshFromFile(file_name)
        self.assertTrue(
            len(m.getTriangulation()) <= 2000, 'Test mesh interface failed!')
        self.assertTrue(
            len(m.getTriangulation()) >= 900, 'Test mesh interface failed!')

        os.remove(file_name)
Exemplo n.º 13
0
    def concept_ungenerateIII(self):
        from anuga import Domain, Reflective_boundary, \
                            Dirichlet_boundary
        from anuga.pmesh.mesh_interface import create_mesh_from_regions

        # These are the absolute values
        polygon = [[0, 0], [100, 0], [100, 100], [0, 100]]

        boundary_tags = {'wall': [0, 1, 3], 'wave': [2]}
        inner1_polygon = [[10, 10], [20, 10], [20, 20], [10, 20]]
        inner2_polygon = [[30, 30], [40, 30], [40, 40], [30, 40]]

        max_area = 1
        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     max_area,
                                     interior_regions=interior_regions)

        fileName = tempfile.mktemp('.txt')
        file = open(fileName, 'w')
        file.write('         1       ??      ??\n\
       90.0       90.0\n\
       81.0       90.0\n\
       81.0       81.0\n\
       90.0       81.0\n\
       90.0       90.0\n\
END\n\
         2      ?? ??\n\
       10.0       80.0\n\
       10.0       90.0\n\
       20.0       90.0\n\
       10.0       80.0\n\
END\n\
END\n')
        file.close()

        m.import_ungenerate_file(fileName)
        os.remove(fileName)
        m.generate_mesh(maximum_triangle_area=max_area, verbose=False)
        mesh_filename = 'mesh.tsh'
        m.export_mesh_file(mesh_filename)

        domain = Domain(mesh_filename, use_cache=False)

        Br = Reflective_boundary(domain)
        Bd = Dirichlet_boundary([3, 0, 0])
        domain.set_boundary({'wall': Br, 'wave': Bd})
        yieldstep = 0.1
        finaltime = 10
        for t in domain.evolve(yieldstep, finaltime):
            domain.write_time()
    def concept_ungenerateIII(self):
        from anuga import Domain, Reflective_boundary, \
                            Dirichlet_boundary
        from anuga.pmesh.mesh_interface import create_mesh_from_regions

        # These are the absolute values
        polygon = [[0,0], [100,0], [100,100], [0,100]]

        boundary_tags = {'wall': [0,1,3], 'wave': [2]}
        inner1_polygon = [[10,10], [20,10], [20,20], [10,20]]
        inner2_polygon = [[30,30], [40,30], [40,40], [30,40]]

        max_area = 1
        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     max_area,
                                     interior_regions=interior_regions)

        fileName = tempfile.mktemp('.txt')
        file = open(fileName, 'w')
        file.write('         1       ??      ??\n\
       90.0       90.0\n\
       81.0       90.0\n\
       81.0       81.0\n\
       90.0       81.0\n\
       90.0       90.0\n\
END\n\
         2      ?? ??\n\
       10.0       80.0\n\
       10.0       90.0\n\
       20.0       90.0\n\
       10.0       80.0\n\
END\n\
END\n')
        file.close()

        m.import_ungenerate_file(fileName)
        os.remove(fileName)
        m.generate_mesh(maximum_triangle_area=max_area, verbose=False)
        mesh_filename = 'mesh.tsh'
        m.export_mesh_file(mesh_filename)

        domain = Domain(mesh_filename, use_cache=False)

        Br = Reflective_boundary(domain)
        Bd = Dirichlet_boundary([3, 0, 0])
        domain.set_boundary({'wall': Br, 'wave': Bd})
        yieldstep = 0.1
        finaltime = 10
        for t in domain.evolve(yieldstep, finaltime):
            domain.write_time()
Exemplo n.º 15
0
    def FIXMEtest_create_mesh_with_multiply_tagged_segments(self):
        '''Test that create_mesh_from_regions fails when
        segments are listed repeatedly in boundary_tags.
        '''

        # These are the absolute values
        min_x = 10
        min_y = 88
        polygon = [[min_x, min_y], [1000, 100], [1000, 1000], [100, 1000]]
        boundary_tags = {'walls': [0, 1], 'bom': [1, 2]}

        # This one is inside bounding polygon - should pass
        inner_polygon = [[800, 400], [900, 500], [800, 600]]
        interior_regions = [(inner_polygon, 5)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions,
                                     verbose=False)

        # This one sticks outside bounding polygon - should fail
        inner_polygon = [[800, 400], [900, 500], [800, 600]]
        interior_regions = [(inner_polygon, 5)]

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions)
        try:
            m = create_mesh_from_regions(polygon,
                                         boundary_tags,
                                         10000000,
                                         interior_regions=interior_regions)
        except:
            pass
        else:
            msg = 'Tags are listed repeatedly, but create mesh from regions '
            msg += 'does not cause an Exception to be raised'
            raise_(Exception, msg)
    def FIXMEtest_create_mesh_with_multiply_tagged_segments(self):
        '''Test that create_mesh_from_regions fails when
        segments are listed repeatedly in boundary_tags.
        '''

        # These are the absolute values
        min_x = 10
        min_y = 88
        polygon = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]]
        boundary_tags = {'walls': [0,1], 'bom': [1,2]}

        # This one is inside bounding polygon - should pass
        inner_polygon = [[800,400], [900,500], [800,600]]
        interior_regions = [(inner_polygon, 5)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions,
                                     verbose=False)

        # This one sticks outside bounding polygon - should fail
        inner_polygon = [[800,400], [900,500], [800,600]]
        interior_regions = [(inner_polygon, 5)]

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions)
        try:
            m = create_mesh_from_regions(polygon,
                                         boundary_tags,
                                         10000000,
                                         interior_regions=interior_regions)
        except:
            pass
        else:
            msg = 'Tags are listed repeatedly, but create mesh from regions '
            msg += 'does not cause an Exception to be raised'
            raise Exception, msg
Exemplo n.º 17
0
    def test_create_mesh_from_regions_interior_regions(self):
        '''Test that create_mesh_from_regions fails when an interior
        region is outside bounding polygon.
        '''

        # These are the absolute values
        min_x = 10
        min_y = 88
        polygon = [[min_x, min_y], [1000, 100], [1000, 1000], [100, 1000]]

        boundary_tags = {'walls': [0, 1], 'bom': [2, 3]}

        # This one is inside bounding polygon - should pass
        inner_polygon = [[800, 400], [900, 500], [800, 600]]

        interior_regions = [(inner_polygon, 5)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions)

        # This one sticks outside bounding polygon - should fail
        inner_polygon = [[800, 400], [900, 500], [800, 600], [200, 995]]
        inner_polygon1 = [[800, 400], [1100, 500], [800, 600]]
        interior_regions = [[inner_polygon, 50], [inner_polygon1, 50]]

        try:
            m = create_mesh_from_regions(polygon,
                                         boundary_tags,
                                         10000000,
                                         interior_regions=interior_regions,
                                         verbose=False)
        except:
            pass
        else:
            msg = 'Interior polygon sticking outside bounding polygon should '
            msg += 'cause an Exception to be raised'
            raise_(Exception, msg)
    def test_create_mesh_from_regions_interior_regions(self):
        '''Test that create_mesh_from_regions fails when an interior
        region is outside bounding polygon.
        '''

        # These are the absolute values
        min_x = 10
        min_y = 88
        polygon = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]]

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}

        # This one is inside bounding polygon - should pass
        inner_polygon = [[800,400], [900,500], [800,600]]

        interior_regions = [(inner_polygon, 5)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions)

        # This one sticks outside bounding polygon - should fail
        inner_polygon = [[800,400], [900,500], [800,600], [200, 995]]
        inner_polygon1 = [[800,400], [1100,500], [800,600]]
        interior_regions = [[inner_polygon, 50], [inner_polygon1, 50]]

        try:
            m = create_mesh_from_regions(polygon,
                                         boundary_tags,
                                         10000000,
                                         interior_regions=interior_regions,
                                         verbose=False)
        except:
            pass
        else:
            msg = 'Interior polygon sticking outside bounding polygon should '
            msg += 'cause an Exception to be raised'
            raise Exception, msg
    def test_create_mesh_with_breaklines(self):
        # These are the absolute values
        polygon = [[100,100], [1000,100], [1000,1000], [100,1000]]

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     breaklines=[[[50,50],[2000,2000]]])

        self.assertTrue(len(m.regions) == 1, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs) == 5, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 6, 'FAILED!')
Exemplo n.º 20
0
    def test_create_mesh_with_breaklines(self):
        # These are the absolute values
        polygon = [[100, 100], [1000, 100], [1000, 1000], [100, 1000]]

        boundary_tags = {'walls': [0, 1], 'bom': [2, 3]}

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     breaklines=[[[50, 50], [2000, 2000]]])

        self.assertTrue(len(m.regions) == 1, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs) == 5, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 6, 'FAILED!')
Exemplo n.º 21
0
    def test_create_mesh_from_regions2(self):
        # These are the absolute values
        min_x = -10
        min_y = -88
        polygon_absolute = [[min_x, min_y], [1000, 100], [1000, 1000],
                            [100, 1000]]

        x_p = -10
        y_p = -40
        zone = 808
        geo_ref_poly = Geo_reference(zone, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0, 1], 'bom': [2, 3]}

        inner1_polygon_absolute = [[10, 10], [20, 10], [20, 20], [10, 20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30, 30], [40, 30], [40, 40], [30, 40]]
        inner2_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner2_polygon_absolute)

        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly)

        # Test the mesh instance
        self.assertTrue(len(m.regions) == 3, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs) == 12, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 12, 'FAILED!')
        self.assertTrue(segs[0].tag == 'walls', 'FAILED!')
        self.assertTrue(segs[1].tag == 'walls', 'FAILED!')
        self.assertTrue(segs[2].tag == 'bom', 'FAILED!')
        self.assertTrue(segs[3].tag == 'bom', 'FAILED!')
        self.assertTrue(m.geo_reference.get_zone() == zone, 'FAILED!')
        self.assertTrue(m.geo_reference.get_xllcorner() == min_x, 'FAILED!')
        self.assertTrue(m.geo_reference.get_yllcorner() == min_y, 'FAILED!')
    def test_create_mesh_from_regions2(self):
        # These are the absolute values
        min_x = -10
        min_y = -88
        polygon_absolute = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]]

        x_p = -10
        y_p = -40
        zone = 808
        geo_ref_poly = Geo_reference(zone, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}

        inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]]
        inner2_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner2_polygon_absolute)

        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly)

        # Test the mesh instance
        self.assertTrue(len(m.regions)==3, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs)==12, 'FAILED!')
        self.assertTrue(len(m.userVertices)==12, 'FAILED!')
        self.assertTrue(segs[0].tag=='walls', 'FAILED!')
        self.assertTrue(segs[1].tag=='walls', 'FAILED!')
        self.assertTrue(segs[2].tag=='bom', 'FAILED!')
        self.assertTrue(segs[3].tag=='bom', 'FAILED!')
        self.assertTrue(m.geo_reference.get_zone()==zone, 'FAILED!')
        self.assertTrue(m.geo_reference.get_xllcorner()==min_x, 'FAILED!')
        self.assertTrue(m.geo_reference.get_yllcorner()==min_y, 'FAILED!')		
Exemplo n.º 23
0
    def test_create_mesh_from_regions_with_duplicate_verts(self):
        # These are the absolute values
        polygon_absolute = [[0.0, 0.0], [0, 4.0], [4.0, 4.0], [4.0, 0.0],
                            [4.0, 0.0]]
        x_p = -10
        y_p = -40
        zone = 808
        geo_ref_poly = Geo_reference(zone, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)
        boundary_tags = {
            '50': [0],
            '40': [1],
            '30': [2],
            'no where seg': [3],
            '20': [4]
        }
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     poly_geo_reference=geo_ref_poly,
                                     verbose=False)

        fileName = 'badmesh.tsh'
    def test_create_mesh_from_regions_with_duplicate_verts(self):
        # These are the absolute values
        polygon_absolute = [[0.0, 0.0],
                            [0, 4.0],
                            [4.0, 4.0],
                            [4.0, 0.0],
                            [4.0, 0.0]]
        x_p = -10
        y_p = -40
        zone = 808
        geo_ref_poly = Geo_reference(zone, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)
        boundary_tags = {'50': [0],
                         '40': [1],
                         '30': [2],
                         'no where seg': [3],
                         '20': [4]}
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     poly_geo_reference=geo_ref_poly,
                                     verbose=False)

        fileName = 'badmesh.tsh'
    def test_create_mesh_from_regions_interior_regions1(self):
        '''Test that create_mesh_from_regions fails
        when an interior region is outside bounding polygon.
        '''

        # These are the values
        d0 = [310000, 7690000]
        d1 = [280000, 7690000]
        d2 = [270000, 7645000]
        d3 = [240000, 7625000]
        d4 = [270000, 7580000]
        d5 = [300000, 7590000]
        d6 = [340000, 7610000]
        poly_all = [d0, d1, d2, d3, d4, d5, d6]

        i0 = [304000, 7607000]
        i1 = [302000, 7605000]
        i2 = [304000, 7603000]
        i3 = [307000, 7602000]
        i4 = [309000, 7603000]
#        i4 = [310000, 7580000]
        i5 = [307000, 7606000]
        poly_onslow = [i0, i1, i2, i3, i4, i5]

        # Thevenard Island
        j0 = [294000, 7629000]
        j1 = [285000, 7625000]
        j2 = [294000, 7621000]
        j3 = [299000, 7625000]
        poly_thevenard = [j0, j1, j2, j3]

        # med res around onslow
        l0 = [300000, 7610000]
        l1 = [285000, 7600000]
        l2 = [300000, 7597500]
        l3 = [310000, 7770000] # this one is outside
#        l3 = [310000, 7630000] # this one is NOT outside
        l4 = [315000, 7610000]
        poly_coast = [l0, l1, l2, l3, l4]

        # general coast and local area to onslow region
        m0 = [270000, 7581000]
        m1 = [300000, 7591000]
        m2 = [339000, 7610000]
        m3 = [330000, 7630000]
        m4 = [290000, 7640000]
        m5 = [260000, 7600000]
        poly_region = [m0, m1, m2, m3, m4, m5]

        # This one sticks outside bounding polygon - should fail
        interior_regions = [[poly_onslow, 50000], [poly_region, 50000],
                            [poly_coast, 100000], [poly_thevenard, 100000]]
        boundary_tags = {'walls': [0,1], 'bom': [2]}

        try:
            m = create_mesh_from_regions(poly_all,
                                         boundary_tags,
                                         10000000,
                                         interior_regions=interior_regions,
                                         verbose=False)
        except:
            pass
        else:
            msg = 'Interior polygon sticking outside bounding polygon should '
            msg += 'cause an Exception to be raised'
            raise Exception, msg
Exemplo n.º 26
0
    def test_create_mesh_from_regions(self):
        x = -500
        y = -1000
        mesh_geo = geo_reference = Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0, 0], [100, 0], [100, 100], [0, 100]]

        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0, 1], 'bom': [2, 3]}

        inner1_polygon_absolute = [[10, 10], [20, 10], [20, 20], [10, 20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30, 30], [40, 30], [40, 40], [30, 40]]
        inner2_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner2_polygon_absolute)

        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo)

        # Test the mesh instance
        self.assertTrue(len(m.regions) == 3, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs) == 12, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 12, 'FAILED!')
        self.assertTrue(segs[0].tag == 'walls', 'FAILED!')
        self.assertTrue(segs[1].tag == 'walls', 'FAILED!')
        self.assertTrue(segs[2].tag == 'bom', 'FAILED!')
        self.assertTrue(segs[3].tag == 'bom', 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[0]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        msg = ('Expected point (%s,%s) to be inside polygon %s' %
               (str(poly_point.x + x), str(poly_point.y + y),
                str(polygon_absolute)))
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              polygon_absolute,
                              closed=False), msg)

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[1]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              inner1_polygon_absolute,
                              closed=False), 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[2]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              inner2_polygon_absolute,
                              closed=False), 'FAILED!')
Exemplo n.º 27
0
    def test_create_mesh_from_regions_with_caching(self):
        x = -500
        y = -1000
        mesh_geo = geo_reference = Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0, 0], [100, 0], [100, 100], [0, 100]]

        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0, 1], 'bom': [2, 3]}

        inner1_polygon_absolute = [[10, 10], [20, 10], [20, 20], [10, 20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30, 30], [40, 30], [40, 40], [30, 40]]
        inner2_polygon = geo_ref_poly.\
                             change_points_geo_ref(inner2_polygon_absolute)

        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]

        interior_holes = None

        # Clear cache first
        from anuga.caching import cache

        cache(_create_mesh_from_regions, (polygon, boundary_tags), {
            'minimum_triangle_angle': 28.0,
            'maximum_triangle_area': 10000000,
            'interior_regions': interior_regions,
            'interior_holes': interior_holes,
            'poly_geo_reference': geo_ref_poly,
            'mesh_geo_reference': mesh_geo,
            'verbose': False
        },
              verbose=False,
              clear=1)

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     maximum_triangle_area=10000000,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo,
                                     verbose=False,
                                     use_cache=True)

        # Test the mesh instance
        self.assertTrue(len(m.regions) == 3, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs) == 12, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 12, 'FAILED!')
        self.assertTrue(segs[0].tag == 'walls', 'FAILED!')
        self.assertTrue(segs[1].tag == 'walls', 'FAILED!')
        self.assertTrue(segs[2].tag == 'bom', 'FAILED!')
        self.assertTrue(segs[3].tag == 'bom', 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[0]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              polygon_absolute,
                              closed=False), 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[1]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              inner1_polygon_absolute,
                              closed=False), 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[2]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              inner2_polygon_absolute,
                              closed=False), 'FAILED!')

        # Now create m using cached values
        m_cache = create_mesh_from_regions(polygon,
                                           boundary_tags,
                                           10000000,
                                           interior_regions=interior_regions,
                                           poly_geo_reference=geo_ref_poly,
                                           mesh_geo_reference=mesh_geo,
                                           verbose=False,
                                           use_cache=True)
Exemplo n.º 28
0
        
        # Create a scenario outline.
        polygon = [[0,0],[100,0],[100,100],[0,100]]
        
        boundary_tags = {'wall':[0,1,3],'wave':[2]}
        
        inner1_polygon = [[10,10],[20,10],[20,20],[10,20]]
        

        inner2_polygon = [[30,30],[40,30],[40,40],[30,40]]
        
        
        max_area = 1
        interior_regions = [(inner1_polygon, 5),(inner2_polygon, 10)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     max_area,
                                     interior_regions=interior_regions)

        # Create an ungenerate file            
        fileName = tempfile.mktemp(".txt")
        file = open(fileName,"w")
        file.write("         1       ??      ??\n\
       90.0       90.0\n\
       81.0       90.0\n\
       81.0       81.0\n\
       90.0       81.0\n\
       90.0       90.0\n\
END\n\
         2      ?? ??\n\
       10.0       80.0\n\
       10.0       90.0\n\
Exemplo n.º 29
0
    def concept_ungenerateII(self):
        from anuga import Domain, Reflective_boundary, Dirichlet_boundary

        x = 0
        y = 0
        mesh_geo = geo_reference = Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0, 0], [100, 0], [100, 100], [0, 100]]
        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'wall': [0, 1, 3], 'wave': [2]}

        inner1_polygon_absolute = [[10, 10], [20, 10], [20, 20], [10, 20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30, 30], [40, 30], [40, 40], [30, 40]]
        inner2_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner2_polygon_absolute)

        max_area = 1
        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     max_area,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo)

        m.export_mesh_file('a_test_mesh_iknterface.tsh')

        fileName = tempfile.mktemp('.txt')
        file = open(fileName, 'w')
        file.write('         1       ??      ??\n\
       90.0       90.0\n\
       81.0       90.0\n\
       81.0       81.0\n\
       90.0       81.0\n\
       90.0       90.0\n\
END\n\
         2      ?? ??\n\
       10.0       80.0\n\
       10.0       90.0\n\
       20.0       90.0\n\
       10.0       80.0\n\
END\n\
END\n')
        file.close()

        m.import_ungenerate_file(fileName)  #, tag='wall')
        os.remove(fileName)
        m.generate_mesh(maximum_triangle_area=max_area, verbose=False)
        mesh_filename = 'bento_b.tsh'
        m.export_mesh_file(mesh_filename)

        domain = Domain(mesh_filename, use_cache=False)

        Br = Reflective_boundary(domain)
        Bd = Dirichlet_boundary([3, 0, 0])
        domain.set_boundary({'wall': Br, 'wave': Bd})
        yieldstep = 0.1
        finaltime = 10
        for t in domain.evolve(yieldstep, finaltime):
            domain.write_time()
    def concept_ungenerateII(self):
        from anuga import Domain, Reflective_boundary, Dirichlet_boundary

        x=0
        y=0
        mesh_geo = geo_reference=Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0,0], [100,0], [100,100], [0,100]]
        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'wall': [0,1,3], 'wave': [2]}

        inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]]
        inner2_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner2_polygon_absolute)

        max_area = 1
        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     max_area,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo)

        m.export_mesh_file('a_test_mesh_iknterface.tsh')

        fileName = tempfile.mktemp('.txt')
        file = open(fileName, 'w')
        file.write('         1       ??      ??\n\
       90.0       90.0\n\
       81.0       90.0\n\
       81.0       81.0\n\
       90.0       81.0\n\
       90.0       90.0\n\
END\n\
         2      ?? ??\n\
       10.0       80.0\n\
       10.0       90.0\n\
       20.0       90.0\n\
       10.0       80.0\n\
END\n\
END\n')
        file.close()

        m.import_ungenerate_file(fileName)      #, tag='wall')
        os.remove(fileName)
        m.generate_mesh(maximum_triangle_area=max_area, verbose=False)
        mesh_filename = 'bento_b.tsh'
        m.export_mesh_file(mesh_filename)

        domain = Domain(mesh_filename, use_cache = False)

        Br = Reflective_boundary(domain)
        Bd = Dirichlet_boundary([3, 0, 0])
        domain.set_boundary({'wall': Br, 'wave': Bd})
        yieldstep = 0.1
        finaltime = 10
        for t in domain.evolve(yieldstep, finaltime):
            domain.write_time()
    def parallel_time_varying_file_boundary_sts(self):
        """ parallel_test_time_varying_file_boundary_sts_sequential(self):
            Read correct points from ordering file and apply sts to boundary. 
            The boundary is time varying. Compares sequential result with 
            distributed result found using anuga_parallel
        """

        #------------------------------------------------------------
        # Define test variables
        #------------------------------------------------------------
        lat_long_points = [[6.01, 97.0], [6.02, 97.0], [6.05, 96.9],
                           [6.0, 97.0]]
        bounding_polygon = [[6.0, 97.0], [6.01, 97.0], [6.02, 97.0],
                            [6.02, 97.02], [6.00, 97.02]]
        tide = 3.0
        time_step_count = 65
        time_step = 2
        n = len(lat_long_points)
        first_tstep = num.ones(n, num.int)
        last_tstep = (time_step_count) * num.ones(n, num.int)
        finaltime = num.float(time_step * (time_step_count - 1))
        yieldstep = num.float(time_step)
        gauge_depth = 20 * num.ones(n, num.float)
        ha = 2 * num.ones((n, time_step_count), num.float)
        ua = 10 * num.ones((n, time_step_count), num.float)
        va = -10 * num.ones((n, time_step_count), num.float)

        times = num.arange(0, time_step_count * time_step, time_step)
        for i in range(n):
            #ha[i]+=num.sin(times)
            ha[i] += times / finaltime

        #------------------------------------------------------------
        # Write mux data to file then convert to sts format
        #------------------------------------------------------------
        sts_file = "test"
        if myid == 0:
            base_name, files = self.write_mux2(lat_long_points,
                                               time_step_count,
                                               time_step,
                                               first_tstep,
                                               last_tstep,
                                               depth=gauge_depth,
                                               ha=ha,
                                               ua=ua,
                                               va=va)
            # base name will not exist, but 3 other files are created

            # Write order file
            file_handle, order_base_name = tempfile.mkstemp("")
            os.close(file_handle)
            os.remove(order_base_name)
            d = ","
            order_file = order_base_name + 'order.txt'
            fid = open(order_file, 'w')

            # Write Header
            header = 'index, longitude, latitude\n'
            fid.write(header)
            indices = [3, 0, 1]
            for i in indices:
                line=str(i)+d+str(lat_long_points[i][1])+d+\
                    str(lat_long_points[i][0])+"\n"
                fid.write(line)
            fid.close()

            urs2sts(base_name,
                    basename_out=sts_file,
                    ordering_filename=order_file,
                    mean_stage=tide,
                    verbose=verbose)
            self.delete_mux(files)

            assert (os.access(sts_file + '.sts', os.F_OK))

            os.remove(order_file)

        barrier()
        #------------------------------------------------------------
        # Define boundary_polygon on each processor. This polygon defines the
        # urs boundary and lies on a portion of the bounding_polygon
        #------------------------------------------------------------
        boundary_polygon = create_sts_boundary(sts_file)

        # Append the remaining part of the boundary polygon to be defined by
        # the user
        bounding_polygon_utm = []
        for point in bounding_polygon:
            zone, easting, northing = redfearn(point[0], point[1])
            bounding_polygon_utm.append([easting, northing])

        boundary_polygon.append(bounding_polygon_utm[3])
        boundary_polygon.append(bounding_polygon_utm[4])

        assert num.allclose(bounding_polygon_utm, boundary_polygon)

        extent_res = 10000
        meshname = 'urs_test_mesh' + '.tsh'
        interior_regions = None
        boundary_tags = {'ocean': [0, 1], 'otherocean': [2, 3, 4]}

        #------------------------------------------------------------
        # Create mesh on the master processor and store in file. This file
        # is read in by each slave processor when needed
        #------------------------------------------------------------
        if myid == 0:
            create_mesh_from_regions(boundary_polygon,
                                     boundary_tags=boundary_tags,
                                     maximum_triangle_area=extent_res,
                                     filename=meshname,
                                     interior_regions=interior_regions,
                                     verbose=verbose)

            # barrier()
            domain_fbound = Domain(meshname)
            domain_fbound.set_quantities_to_be_stored(None)
            domain_fbound.set_quantity('stage', tide)
            # print domain_fbound.mesh.get_boundary_polygon()
        else:
            domain_fbound = None

        barrier()
        if (verbose and myid == 0):
            print 'DISTRIBUTING PARALLEL DOMAIN'
        domain_fbound = distribute(domain_fbound)

        #--------------------------------------------------------------------
        # Find which sub_domain in which the interpolation points are located
        #
        # Sometimes the interpolation points sit exactly
        # between two centroids, so in the parallel run we
        # reset the interpolation points to the centroids
        # found in the sequential run
        #--------------------------------------------------------------------
        interpolation_points = [[279000, 664000], [280250, 664130],
                                [279280, 665400], [280500, 665000]]

        interpolation_points = num.array(interpolation_points)

        #if myid==0:
        #    import pylab as P
        #    boundary_polygon=num.array(boundary_polygon)
        #    P.plot(boundary_polygon[:,0],boundary_polygon[:,1])
        #    P.plot(interpolation_points[:,0],interpolation_points[:,1],'ko')
        #    P.show()

        fbound_gauge_values = []
        fbound_proc_tri_ids = []
        for i, point in enumerate(interpolation_points):
            fbound_gauge_values.append([])  # Empty list for timeseries

            try:
                k = domain_fbound.get_triangle_containing_point(point)
                if domain_fbound.tri_full_flag[k] == 1:
                    fbound_proc_tri_ids.append(k)
                else:
                    fbound_proc_tri_ids.append(-1)
            except:
                fbound_proc_tri_ids.append(-2)

        if verbose: print 'P%d has points = %s' % (myid, fbound_proc_tri_ids)

        #------------------------------------------------------------
        # Set boundary conditions
        #------------------------------------------------------------
        Bf = File_boundary(sts_file + '.sts',
                           domain_fbound,
                           boundary_polygon=boundary_polygon)
        Br = Reflective_boundary(domain_fbound)

        domain_fbound.set_boundary({'ocean': Bf, 'otherocean': Br})

        #------------------------------------------------------------
        # Evolve the domain on each processor
        #------------------------------------------------------------
        for i, t in enumerate(
                domain_fbound.evolve(yieldstep=yieldstep,
                                     finaltime=finaltime,
                                     skip_initial_step=False)):

            stage = domain_fbound.get_quantity('stage')
            for i in range(4):
                if fbound_proc_tri_ids[i] > -1:
                    fbound_gauge_values[i].append(
                        stage.centroid_values[fbound_proc_tri_ids[i]])

        #------------------------------------------------------------
        # Create domain to be run sequntially on each processor
        #------------------------------------------------------------
        domain_drchlt = Domain(meshname)
        domain_drchlt.set_quantities_to_be_stored(None)
        domain_drchlt.set_starttime(time_step)
        domain_drchlt.set_quantity('stage', tide)
        Br = Reflective_boundary(domain_drchlt)
        #Bd = Dirichlet_boundary([2.0+tide,220+10*tide,-220-10*tide])
        Bd = Time_boundary(
            domain=domain_drchlt,
            function=lambda t: [
                2.0 + t / finaltime + tide, 220. + 10. * tide + 10. * t /
                finaltime, -220. - 10. * tide - 10. * t / finaltime
            ])
        #Bd = Time_boundary(domain=domain_drchlt,function=lambda t: [2.0+num.sin(t)+tide,10.*(2+20.+num.sin(t)+tide),-10.*(2+20.+num.sin(t)+tide)])
        domain_drchlt.set_boundary({'ocean': Bd, 'otherocean': Br})

        drchlt_gauge_values = []
        drchlt_proc_tri_ids = []
        for i, point in enumerate(interpolation_points):
            drchlt_gauge_values.append([])  # Empty list for timeseries

            try:
                k = domain_drchlt.get_triangle_containing_point(point)
                if domain_drchlt.tri_full_flag[k] == 1:
                    drchlt_proc_tri_ids.append(k)
                else:
                    drchlt_proc_tri_ids.append(-1)
            except:
                drchlt_proc_tri_ids.append(-2)

        if verbose: print 'P%d has points = %s' % (myid, drchlt_proc_tri_ids)

        #------------------------------------------------------------
        # Evolve entire domain on each processor
        #------------------------------------------------------------
        for i, t in enumerate(
                domain_drchlt.evolve(yieldstep=yieldstep,
                                     finaltime=finaltime,
                                     skip_initial_step=False)):

            stage = domain_drchlt.get_quantity('stage')
            for i in range(4):
                drchlt_gauge_values[i].append(
                    stage.centroid_values[drchlt_proc_tri_ids[i]])

        #------------------------------------------------------------
        # Compare sequential values with parallel values
        #------------------------------------------------------------
        barrier()
        success = True
        for i in range(4):
            if fbound_proc_tri_ids[i] > -1:
                fbound_gauge_values[i] = num.array(fbound_gauge_values[i])
                drchlt_gauge_values[i] = num.array(drchlt_gauge_values[i])
                #print i,fbound_gauge_values[i][4]
                #print i,drchlt_gauge_values[i][4]
                success = success and num.allclose(fbound_gauge_values[i],
                                                   drchlt_gauge_values[i])
                assert success  #, (fbound_gauge_values[i]-drchlt_gauge_values[i])

        #assert_(success)

        if not sys.platform == 'win32':
            if myid == 0: os.remove(sts_file + '.sts')

        if myid == 0: os.remove(meshname)
    def sequential_time_varying_file_boundary_sts(self):
        """sequential_ltest_time_varying_file_boundary_sts_sequential(self):
        Read correct points from ordering file and apply sts to boundary. The boundary is time varying. FIXME add to test_urs2sts.
        """
        lat_long_points = [[6.01, 97.0], [6.02, 97.0], [6.05, 96.9],
                           [6.0, 97.0]]
        bounding_polygon = [[6.0, 97.0], [6.01, 97.0], [6.02, 97.0],
                            [6.02, 97.02], [6.00, 97.02]]
        tide = 3.0
        time_step_count = 65
        time_step = 2.
        n = len(lat_long_points)
        first_tstep = num.ones(n, num.int)
        last_tstep = (time_step_count) * num.ones(n, num.int)
        finaltime = num.float(time_step * (time_step_count - 1))
        yieldstep = num.float(time_step)
        gauge_depth = 20 * num.ones(n, num.float)
        ha = 2 * num.ones((n, time_step_count), num.float)
        ua = 10 * num.ones((n, time_step_count), num.float)
        va = -10 * num.ones((n, time_step_count), num.float)

        times = num.arange(0., num.float(time_step_count * time_step),
                           time_step)
        for i in range(n):
            #ha[i]+=num.sin(times)
            ha[i] += times / finaltime

        sts_file = "test"
        if myid == 0:
            base_name, files = self.write_mux2(lat_long_points,
                                               time_step_count,
                                               time_step,
                                               first_tstep,
                                               last_tstep,
                                               depth=gauge_depth,
                                               ha=ha,
                                               ua=ua,
                                               va=va)
            # base name will not exist, but 3 other files are created

            # Write order file
            file_handle, order_base_name = tempfile.mkstemp("")
            os.close(file_handle)
            os.remove(order_base_name)
            d = ","
            order_file = order_base_name + 'order.txt'
            fid = open(order_file, 'w')

            # Write Header
            header = 'index, longitude, latitude\n'
            fid.write(header)
            indices = [3, 0, 1]
            for i in indices:
                line=str(i)+d+str(lat_long_points[i][1])+d+\
                    str(lat_long_points[i][0])+"\n"
                fid.write(line)
            fid.close()

            urs2sts(base_name,
                    basename_out=sts_file,
                    ordering_filename=order_file,
                    mean_stage=tide,
                    verbose=verbose)
            self.delete_mux(files)

            assert (os.access(sts_file + '.sts', os.F_OK))

            os.remove(order_file)

        barrier()
        boundary_polygon = create_sts_boundary(sts_file)

        # Append the remaining part of the boundary polygon to be defined by
        # the user
        bounding_polygon_utm = []
        for point in bounding_polygon:
            zone, easting, northing = redfearn(point[0], point[1])
            bounding_polygon_utm.append([easting, northing])

        boundary_polygon.append(bounding_polygon_utm[3])
        boundary_polygon.append(bounding_polygon_utm[4])

        assert num.allclose(bounding_polygon_utm, boundary_polygon)

        extent_res = 1000000
        meshname = 'urs_test_mesh' + '.tsh'
        interior_regions = None
        boundary_tags = {'ocean': [0, 1], 'otherocean': [2, 3, 4]}

        # have to change boundary tags from last example because now bounding
        # polygon starts in different place.
        if myid == 0:
            create_mesh_from_regions(boundary_polygon,
                                     boundary_tags=boundary_tags,
                                     maximum_triangle_area=extent_res,
                                     filename=meshname,
                                     interior_regions=interior_regions,
                                     verbose=verbose)

        barrier()

        domain_fbound = Domain(meshname)
        domain_fbound.set_quantities_to_be_stored(None)
        domain_fbound.set_quantity('stage', tide)
        if verbose: print "Creating file boundary condition"
        Bf = File_boundary(sts_file + '.sts',
                           domain_fbound,
                           boundary_polygon=boundary_polygon)
        Br = Reflective_boundary(domain_fbound)

        domain_fbound.set_boundary({'ocean': Bf, 'otherocean': Br})

        temp_fbound = num.zeros(int(finaltime / yieldstep) + 1, num.float)
        if verbose: print "Evolving domain with file boundary condition"
        for i, t in enumerate(
                domain_fbound.evolve(yieldstep=yieldstep,
                                     finaltime=finaltime,
                                     skip_initial_step=False)):
            temp_fbound[i] = domain_fbound.quantities['stage'].centroid_values[
                2]
            if verbose: domain_fbound.write_time()

        domain_drchlt = Domain(meshname)
        domain_drchlt.set_quantities_to_be_stored(None)
        domain_drchlt.set_starttime(time_step)
        domain_drchlt.set_quantity('stage', tide)
        Br = Reflective_boundary(domain_drchlt)
        #Bd = Dirichlet_boundary([2.0+tide,220+10*tide,-220-10*tide])
        Bd = Time_boundary(
            domain=domain_drchlt,
            f=lambda t: [
                2.0 + t / finaltime + tide, 220. + 10. * tide + 10. * t /
                finaltime, -220. - 10. * tide - 10. * t / finaltime
            ])
        #Bd = Time_boundary(domain=domain_drchlt,f=lambda t: [2.0+num.sin(t)+tide,10.*(2+20.+num.sin(t)+tide),-10.*(2+20.+num.sin(t)+tide)])
        domain_drchlt.set_boundary({'ocean': Bd, 'otherocean': Br})
        temp_drchlt = num.zeros(int(finaltime / yieldstep) + 1, num.float)

        for i, t in enumerate(
                domain_drchlt.evolve(yieldstep=yieldstep,
                                     finaltime=finaltime,
                                     skip_initial_step=False)):
            temp_drchlt[i] = domain_drchlt.quantities['stage'].centroid_values[
                2]
            #domain_drchlt.write_time()

        #print domain_fbound.quantities['stage'].vertex_values
        #print domain_drchlt.quantities['stage'].vertex_values

        assert num.allclose(temp_fbound,
                            temp_drchlt), temp_fbound - temp_drchlt

        assert num.allclose(domain_fbound.quantities['stage'].vertex_values,
                            domain_drchlt.quantities['stage'].vertex_values)

        assert num.allclose(
            domain_fbound.quantities['xmomentum'].vertex_values,
            domain_drchlt.quantities['xmomentum'].vertex_values)

        assert num.allclose(
            domain_fbound.quantities['ymomentum'].vertex_values,
            domain_drchlt.quantities['ymomentum'].vertex_values)

        if not sys.platform == 'win32':
            if myid == 0: os.remove(sts_file + '.sts')

        if myid == 0: os.remove(meshname)
    def test_create_mesh_with_interior_holes(self):
        # These are the absolute values
        polygon = [[100,100], [1000,100], [1000,1000], [100,1000]]
        
        interior_poly1 = [[101,101],[200,200], [101,200]]
        interior_poly2 = [[300,300],[500,500], [400,200]]

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}


        # This should work with one hole
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_holes=[interior_poly1])

        self.assertTrue(len(m.getUserSegments()) == 7, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 7, 'FAILED!')


        # This should work with two holes
        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_holes=[interior_poly1, interior_poly2])
        #print len(m.getUserSegments())
        #print len(m.userVertices)
        
        self.assertTrue(len(m.getUserSegments()) == 10, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 10, 'FAILED!')

        #-------------------------------------
        # Error testing
        #-------------------------------------

        
        # try passing just one polygon, not a list of polygons, should throw exception
        try:
            m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_holes=interior_poly1)
        except:
            pass
        else:
            msg = 'Passing a single polygon should have raised an error '
            raise Exception, msg



        # interior polygon outside bounding polygon, should throw exception
        interior_poly3  = [[50,50],[500,500], [400,200]]
        try:
            m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_holes=[interior_poly3])
        except:
            pass
        else:
            msg = 'Passing a single polygon should have raised an error '
            raise Exception, msg
Exemplo n.º 34
0
    def test_create_mesh_from_regions_interior_regions1(self):
        '''Test that create_mesh_from_regions fails
        when an interior region is outside bounding polygon.
        '''

        # These are the values
        d0 = [310000, 7690000]
        d1 = [280000, 7690000]
        d2 = [270000, 7645000]
        d3 = [240000, 7625000]
        d4 = [270000, 7580000]
        d5 = [300000, 7590000]
        d6 = [340000, 7610000]
        poly_all = [d0, d1, d2, d3, d4, d5, d6]

        i0 = [304000, 7607000]
        i1 = [302000, 7605000]
        i2 = [304000, 7603000]
        i3 = [307000, 7602000]
        i4 = [309000, 7603000]
        #        i4 = [310000, 7580000]
        i5 = [307000, 7606000]
        poly_onslow = [i0, i1, i2, i3, i4, i5]

        # Thevenard Island
        j0 = [294000, 7629000]
        j1 = [285000, 7625000]
        j2 = [294000, 7621000]
        j3 = [299000, 7625000]
        poly_thevenard = [j0, j1, j2, j3]

        # med res around onslow
        l0 = [300000, 7610000]
        l1 = [285000, 7600000]
        l2 = [300000, 7597500]
        l3 = [310000, 7770000]  # this one is outside
        #        l3 = [310000, 7630000] # this one is NOT outside
        l4 = [315000, 7610000]
        poly_coast = [l0, l1, l2, l3, l4]

        # general coast and local area to onslow region
        m0 = [270000, 7581000]
        m1 = [300000, 7591000]
        m2 = [339000, 7610000]
        m3 = [330000, 7630000]
        m4 = [290000, 7640000]
        m5 = [260000, 7600000]
        poly_region = [m0, m1, m2, m3, m4, m5]

        # This one sticks outside bounding polygon - should fail
        interior_regions = [[poly_onslow, 50000], [poly_region, 50000],
                            [poly_coast, 100000], [poly_thevenard, 100000]]
        boundary_tags = {'walls': [0, 1], 'bom': [2]}

        try:
            m = create_mesh_from_regions(poly_all,
                                         boundary_tags,
                                         10000000,
                                         interior_regions=interior_regions,
                                         verbose=False)
        except:
            pass
        else:
            msg = 'Interior polygon sticking outside bounding polygon should '
            msg += 'cause an Exception to be raised'
            raise_(Exception, msg)
    def test_create_mesh_from_regions_with_caching(self):
        x=-500
        y=-1000
        mesh_geo = geo_reference=Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0,0], [100,0], [100,100], [0,100]]

        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}

        inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]]
        inner2_polygon = geo_ref_poly.\
                             change_points_geo_ref(inner2_polygon_absolute)

        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]

        interior_holes = None

        # Clear cache first
        from anuga.caching import cache

        cache(_create_mesh_from_regions,
              (polygon, boundary_tags),
              {'minimum_triangle_angle': 28.0,
               'maximum_triangle_area': 10000000,
               'interior_regions': interior_regions,
               'interior_holes': interior_holes,
               'poly_geo_reference': geo_ref_poly,
               'mesh_geo_reference': mesh_geo,
               'verbose': False},
              verbose=False,
              clear=1)

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     maximum_triangle_area=10000000,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo,
                                     verbose=False,
                                     use_cache=True)


        # Test the mesh instance
        self.assertTrue(len(m.regions)==3, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs)==12, 'FAILED!')
        self.assertTrue(len(m.userVertices)==12, 'FAILED!')
        self.assertTrue(segs[0].tag=='walls', 'FAILED!')
        self.assertTrue(segs[1].tag=='walls', 'FAILED!')
        self.assertTrue(segs[2].tag=='bom', 'FAILED!')
        self.assertTrue(segs[3].tag=='bom', 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[0]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          polygon_absolute,
                                          closed=False),
                        'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[1]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          inner1_polygon_absolute,
                                          closed=False),
                        'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[2]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          inner2_polygon_absolute,
                                          closed=False),
                        'FAILED!')

        # Now create m using cached values
        m_cache = create_mesh_from_regions(polygon,
                                           boundary_tags,
                                           10000000,
                                           interior_regions=interior_regions,
                                           poly_geo_reference=geo_ref_poly,
                                           mesh_geo_reference=mesh_geo,
                                           verbose=False,
                                           use_cache=True)
Exemplo n.º 36
0
    def test_file_boundary_stsIV_sinewave_ordering(self):
        """test_file_boundary_stsIV_sinewave_ordering(self):
        Read correct points from ordering file and apply sts to boundary
        This one uses a sine wave and compares to time boundary
        """

        lat_long_points=[[6.01, 97.0], [6.02, 97.0], [6.05, 96.9], [6.0, 97.0]]
        bounding_polygon=[[6.0, 97.0], [6.01, 97.0], [6.02,97.0], \
                            [6.02,97.02], [6.00,97.02]]
        tide = 0.35
        time_step_count = 50
        time_step = 0.1
        times_ref = num.arange(0, time_step_count*time_step, time_step)
        
        n=len(lat_long_points)
        first_tstep=num.ones(n,num.int)
        last_tstep=(time_step_count)*num.ones(n,num.int)
        
        gauge_depth=20*num.ones(n,num.float)
        
        ha1=num.ones((n,time_step_count),num.float)
        ua1=3.*num.ones((n,time_step_count),num.float)
        va1=2.*num.ones((n,time_step_count),num.float)
        for i in range(n):
            ha1[i]=num.sin(times_ref)
        
        
        base_name, files = self.write_mux2(lat_long_points,
                                           time_step_count, time_step,
                                           first_tstep, last_tstep,
                                           depth=gauge_depth,
                                           ha=ha1,
                                           ua=ua1,
                                           va=va1)

        # Write order file
        file_handle, order_base_name = tempfile.mkstemp("")
        os.close(file_handle)
        os.remove(order_base_name)
        d=","
        order_file=order_base_name+'order.txt'
        fid=open(order_file,'w')
        
        # Write Header
        header='index, longitude, latitude\n'
        fid.write(header)
        indices=[3,0,1]
        for i in indices:
            line=str(i)+d+str(lat_long_points[i][1])+d+\
                str(lat_long_points[i][0])+"\n"
            fid.write(line)
        fid.close()

        sts_file=base_name
        urs2sts(base_name, basename_out=sts_file,
                ordering_filename=order_file,
                mean_stage=tide,
                verbose=False)
        self.delete_mux(files)
        
        
        
        # Now read the sts file and check that values have been stored correctly.
        fid = NetCDFFile(sts_file + '.sts')

        # Check the time vector
        times = fid.variables['time'][:]
        
        #print times

        # Check sts quantities
        stage = fid.variables['stage'][:]
        xmomentum = fid.variables['xmomentum'][:]
        ymomentum = fid.variables['ymomentum'][:]
        elevation = fid.variables['elevation'][:]       

        # Create beginnings of boundary polygon based on sts_boundary
        boundary_polygon = create_sts_boundary(base_name)
        
        os.remove(order_file)

        # Append the remaining part of the boundary polygon to be defined by
        # the user
        bounding_polygon_utm=[]
        for point in bounding_polygon:
            zone,easting,northing=redfearn(point[0],point[1])
            bounding_polygon_utm.append([easting,northing])

        boundary_polygon.append(bounding_polygon_utm[3])
        boundary_polygon.append(bounding_polygon_utm[4])

        #print 'boundary_polygon', boundary_polygon
        
        plot=False
        if plot:
            from pylab import plot,show,axis
            boundary_polygon=ensure_numeric(boundary_polygon)
            bounding_polygon_utm=ensure_numeric(bounding_polygon_utm)
            #plot(lat_long_points[:,0],lat_long_points[:,1],'o')
            plot(boundary_polygon[:,0], boundary_polygon[:,1])
            plot(bounding_polygon_utm[:,0],bounding_polygon_utm[:,1])
            show()

        assert num.allclose(bounding_polygon_utm,boundary_polygon)


        extent_res=1000000
        meshname = 'urs_test_mesh' + '.tsh'
        interior_regions=None
        boundary_tags={'ocean': [0,1], 'otherocean': [2,3,4]}
        
        # have to change boundary tags from last example because now bounding
        # polygon starts in different place.
        create_mesh_from_regions(boundary_polygon,
                                 boundary_tags=boundary_tags,
                                 maximum_triangle_area=extent_res,
                                 filename=meshname,
                                 interior_regions=interior_regions,
                                 verbose=False)
        
        domain_fbound = Domain(meshname)
        domain_fbound.set_quantity('stage', tide)
        Bf = File_boundary(sts_file+'.sts', 
                           domain_fbound, 
                           boundary_polygon=boundary_polygon)
        Br = Reflective_boundary(domain_fbound)

        domain_fbound.set_boundary({'ocean': Bf,'otherocean': Br})
        finaltime=time_step*(time_step_count-1)
        yieldstep=time_step
        temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num.float)
    
        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
                                                   finaltime=finaltime, 
                                                   skip_initial_step=False)):
            temp_fbound[i]=domain_fbound.quantities['stage'].centroid_values[2]
    
        
        domain_time = Domain(meshname)
        domain_time.set_quantity('stage', tide)
        Br = Reflective_boundary(domain_time)
        Bw = Time_boundary(domain=domain_time,
                         function=lambda t: [num.sin(t)+tide,3.*(20.+num.sin(t)+tide),2.*(20.+num.sin(t)+tide)])
        domain_time.set_boundary({'ocean': Bw,'otherocean': Br})
        
        temp_time=num.zeros(int(finaltime/yieldstep)+1,num.float)
        
        domain_time.set_starttime(domain_fbound.get_starttime())
        
        for i, t in enumerate(domain_time.evolve(yieldstep=yieldstep,
                                                   finaltime=finaltime, 
                                                   skip_initial_step=False)):
            temp_time[i]=domain_time.quantities['stage'].centroid_values[2]
        
        assert num.allclose(temp_fbound, temp_time)                
        assert num.allclose(domain_fbound.quantities['stage'].vertex_values,
                            domain_time.quantities['stage'].vertex_values)
                        
        assert num.allclose(domain_fbound.quantities['xmomentum'].vertex_values,
                            domain_time.quantities['xmomentum'].vertex_values)                        
                        
        assert num.allclose(domain_fbound.quantities['ymomentum'].vertex_values,
                            domain_time.quantities['ymomentum'].vertex_values)                                                
        

        try:
            os.remove(sts_file+'.sts')
        except:
            # Windoze can't remove this file for some reason 
            pass
        
        os.remove(meshname)
    def sequential_time_varying_file_boundary_sts(self):
        """sequential_ltest_time_varying_file_boundary_sts_sequential(self):
        Read correct points from ordering file and apply sts to boundary. The boundary is time varying. FIXME add to test_urs2sts.
        """
        lat_long_points=[[6.01,97.0],[6.02,97.0],[6.05,96.9],[6.0,97.0]]
        bounding_polygon=[[6.0,97.0],[6.01,97.0],[6.02,97.0],
                          [6.02,97.02],[6.00,97.02]]
        tide = 3.0
        time_step_count = 65
        time_step = 2.
        n=len(lat_long_points)
        first_tstep=num.ones(n,num.int)
        last_tstep=(time_step_count)*num.ones(n,num.int)
        finaltime=num.float(time_step*(time_step_count-1))
        yieldstep=num.float(time_step)
        gauge_depth=20*num.ones(n,num.float)
        ha=2*num.ones((n,time_step_count),num.float)
        ua=10*num.ones((n,time_step_count),num.float)
        va=-10*num.ones((n,time_step_count),num.float)

        times=num.arange(0., num.float(time_step_count*time_step), time_step)
        for i in range(n):
            #ha[i]+=num.sin(times)
            ha[i]+=times/finaltime



        sts_file="test"
        if myid==0:
            base_name, files = self.write_mux2(lat_long_points,
                                               time_step_count,
                                               time_step,
                                               first_tstep,
                                               last_tstep,
                                               depth=gauge_depth,
                                               ha=ha,
                                               ua=ua,
                                               va=va)
            # base name will not exist, but 3 other files are created

            # Write order file
            file_handle, order_base_name = tempfile.mkstemp("")
            os.close(file_handle)
            os.remove(order_base_name)
            d=","
            order_file=order_base_name+'order.txt'
            fid=open(order_file,'w')
        
            # Write Header
            header='index, longitude, latitude\n'
            fid.write(header)
            indices=[3,0,1]
            for i in indices:
                line=str(i)+d+str(lat_long_points[i][1])+d+\
                    str(lat_long_points[i][0])+"\n"
                fid.write(line)
            fid.close()

            urs2sts(base_name,
                    basename_out=sts_file,
                    ordering_filename=order_file,
                    mean_stage=tide,
                    verbose=verbose)
            self.delete_mux(files)

            assert(os.access(sts_file+'.sts', os.F_OK))

            os.remove(order_file)

        barrier()
        boundary_polygon = create_sts_boundary(sts_file)

        # Append the remaining part of the boundary polygon to be defined by
        # the user
        bounding_polygon_utm=[]
        for point in bounding_polygon:
            zone,easting,northing=redfearn(point[0],point[1])
            bounding_polygon_utm.append([easting,northing])

        boundary_polygon.append(bounding_polygon_utm[3])
        boundary_polygon.append(bounding_polygon_utm[4])

        assert num.allclose(bounding_polygon_utm,boundary_polygon)


        extent_res=1000000
        meshname = 'urs_test_mesh' + '.tsh'
        interior_regions=None
        boundary_tags={'ocean': [0,1], 'otherocean': [2,3,4]}
        
        # have to change boundary tags from last example because now bounding
        # polygon starts in different place.
        if myid==0:
            create_mesh_from_regions(boundary_polygon,
                                     boundary_tags=boundary_tags,
                                     maximum_triangle_area=extent_res,
                                     filename=meshname,
                                     interior_regions=interior_regions,
                                     verbose=verbose)

        barrier()
        
        domain_fbound = Domain(meshname)
        domain_fbound.set_quantities_to_be_stored(None)
        domain_fbound.set_quantity('stage', tide)
        if verbose: print "Creating file boundary condition"
        Bf = File_boundary(sts_file+'.sts',
                           domain_fbound,
                           boundary_polygon=boundary_polygon)
        Br = Reflective_boundary(domain_fbound)

        domain_fbound.set_boundary({'ocean': Bf,'otherocean': Br})

        temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num.float)
        if verbose: print "Evolving domain with file boundary condition"
        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
                                                   finaltime=finaltime, 
                                                   skip_initial_step = False)):
            temp_fbound[i]=domain_fbound.quantities['stage'].centroid_values[2]
            if verbose: domain_fbound.write_time()
            
        
        domain_drchlt = Domain(meshname)
        domain_drchlt.set_quantities_to_be_stored(None)
        domain_drchlt.set_starttime(time_step)
        domain_drchlt.set_quantity('stage', tide)
        Br = Reflective_boundary(domain_drchlt)
        #Bd = Dirichlet_boundary([2.0+tide,220+10*tide,-220-10*tide])
        Bd = Time_boundary(domain=domain_drchlt, f=lambda t: [2.0+t/finaltime+tide,220.+10.*tide+10.*t/finaltime,-220.-10.*tide-10.*t/finaltime])
        #Bd = Time_boundary(domain=domain_drchlt,f=lambda t: [2.0+num.sin(t)+tide,10.*(2+20.+num.sin(t)+tide),-10.*(2+20.+num.sin(t)+tide)])
        domain_drchlt.set_boundary({'ocean': Bd,'otherocean': Br})
        temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num.float)
        
        for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep,
                                                   finaltime=finaltime, 
                                                   skip_initial_step = False)):
            temp_drchlt[i]=domain_drchlt.quantities['stage'].centroid_values[2]
            #domain_drchlt.write_time()
        
        #print domain_fbound.quantities['stage'].vertex_values
        #print domain_drchlt.quantities['stage'].vertex_values
                    
        assert num.allclose(temp_fbound,temp_drchlt),temp_fbound-temp_drchlt

        
        assert num.allclose(domain_fbound.quantities['stage'].vertex_values,
                            domain_drchlt.quantities['stage'].vertex_values)
                        
        assert num.allclose(domain_fbound.quantities['xmomentum'].vertex_values,
                            domain_drchlt.quantities['xmomentum'].vertex_values)                        
                        
        assert num.allclose(domain_fbound.quantities['ymomentum'].vertex_values,
                            domain_drchlt.quantities['ymomentum'].vertex_values)
        
        if not sys.platform == 'win32':
            if myid==0: os.remove(sts_file+'.sts')
        
        if myid==0: os.remove(meshname)
    def parallel_time_varying_file_boundary_sts(self):
        """ parallel_test_time_varying_file_boundary_sts_sequential(self):
            Read correct points from ordering file and apply sts to boundary. 
            The boundary is time varying. Compares sequential result with 
            distributed result found using anuga_parallel
        """

        #------------------------------------------------------------
        # Define test variables
        #------------------------------------------------------------
        lat_long_points=[[6.01,97.0],[6.02,97.0],[6.05,96.9],[6.0,97.0]]
        bounding_polygon=[[6.0,97.0],[6.01,97.0],[6.02,97.0],
                          [6.02,97.02],[6.00,97.02]]
        tide = 3.0
        time_step_count = 65
        time_step = 2
        n=len(lat_long_points)
        first_tstep=num.ones(n,num.int)
        last_tstep=(time_step_count)*num.ones(n,num.int)
        finaltime=num.float(time_step*(time_step_count-1))
        yieldstep=num.float(time_step)
        gauge_depth=20*num.ones(n,num.float)
        ha=2*num.ones((n,time_step_count),num.float)
        ua=10*num.ones((n,time_step_count),num.float)
        va=-10*num.ones((n,time_step_count),num.float)

        times=num.arange(0, time_step_count*time_step, time_step)
        for i in range(n):
            #ha[i]+=num.sin(times)
            ha[i]+=times/finaltime

        #------------------------------------------------------------
        # Write mux data to file then convert to sts format
        #------------------------------------------------------------
        sts_file="test"
        if myid==0:
            base_name, files = self.write_mux2(lat_long_points,
                                               time_step_count,
                                               time_step,
                                               first_tstep,
                                               last_tstep,
                                               depth=gauge_depth,
                                               ha=ha,
                                               ua=ua,
                                               va=va)
            # base name will not exist, but 3 other files are created

            # Write order file
            file_handle, order_base_name = tempfile.mkstemp("")
            os.close(file_handle)
            os.remove(order_base_name)
            d=","
            order_file=order_base_name+'order.txt'
            fid=open(order_file,'w')
        
            # Write Header
            header='index, longitude, latitude\n'
            fid.write(header)
            indices=[3,0,1]
            for i in indices:
                line=str(i)+d+str(lat_long_points[i][1])+d+\
                    str(lat_long_points[i][0])+"\n"
                fid.write(line)
            fid.close()

            urs2sts(base_name,
                    basename_out=sts_file,
                    ordering_filename=order_file,
                    mean_stage=tide,
                    verbose=verbose)
            self.delete_mux(files)

            assert(os.access(sts_file+'.sts', os.F_OK))

            os.remove(order_file)

        barrier()
        #------------------------------------------------------------
        # Define boundary_polygon on each processor. This polygon defines the
        # urs boundary and lies on a portion of the bounding_polygon
        #------------------------------------------------------------
        boundary_polygon = create_sts_boundary(sts_file)

        # Append the remaining part of the boundary polygon to be defined by
        # the user
        bounding_polygon_utm=[]
        for point in bounding_polygon:
            zone,easting,northing=redfearn(point[0],point[1])
            bounding_polygon_utm.append([easting,northing])

        boundary_polygon.append(bounding_polygon_utm[3])
        boundary_polygon.append(bounding_polygon_utm[4])


        assert num.allclose(bounding_polygon_utm,boundary_polygon)

        extent_res=10000
        meshname = 'urs_test_mesh' + '.tsh'
        interior_regions=None
        boundary_tags={'ocean': [0,1], 'otherocean': [2,3,4]}
        
        #------------------------------------------------------------
        # Create mesh on the master processor and store in file. This file
        # is read in by each slave processor when needed
        #------------------------------------------------------------
        if myid==0:
            create_mesh_from_regions(boundary_polygon,
                                     boundary_tags=boundary_tags,
                                     maximum_triangle_area=extent_res,
                                     filename=meshname,
                                     interior_regions=interior_regions,
                                     verbose=verbose)
        

            # barrier()
            domain_fbound = Domain(meshname)
            domain_fbound.set_quantities_to_be_stored(None)
            domain_fbound.set_quantity('stage', tide)
            # print domain_fbound.mesh.get_boundary_polygon()
        else:
            domain_fbound=None

        barrier()
        if ( verbose and myid == 0 ): 
            print 'DISTRIBUTING PARALLEL DOMAIN'
        domain_fbound = distribute(domain_fbound)

        #--------------------------------------------------------------------
        # Find which sub_domain in which the interpolation points are located 
        #
        # Sometimes the interpolation points sit exactly
        # between two centroids, so in the parallel run we
        # reset the interpolation points to the centroids
        # found in the sequential run
        #--------------------------------------------------------------------
        interpolation_points = [[279000,664000], [280250,664130], 
                                    [279280,665400], [280500,665000]]

        interpolation_points=num.array(interpolation_points)

        #if myid==0:
        #    import pylab as P
        #    boundary_polygon=num.array(boundary_polygon)
        #    P.plot(boundary_polygon[:,0],boundary_polygon[:,1])
        #    P.plot(interpolation_points[:,0],interpolation_points[:,1],'ko')
        #    P.show()

        fbound_gauge_values = []
        fbound_proc_tri_ids = []
        for i, point in enumerate(interpolation_points):
            fbound_gauge_values.append([]) # Empty list for timeseries

            try:
                k = domain_fbound.get_triangle_containing_point(point)
                if domain_fbound.tri_full_flag[k] == 1:
                    fbound_proc_tri_ids.append(k)
                else:
                    fbound_proc_tri_ids.append(-1)            
            except:
                fbound_proc_tri_ids.append(-2)


        if verbose: print 'P%d has points = %s' %(myid, fbound_proc_tri_ids)

        #------------------------------------------------------------
        # Set boundary conditions
        #------------------------------------------------------------
        Bf = File_boundary(sts_file+'.sts',
                           domain_fbound,
                           boundary_polygon=boundary_polygon)
        Br = Reflective_boundary(domain_fbound)
    
        domain_fbound.set_boundary({'ocean': Bf,'otherocean': Br})

        #------------------------------------------------------------
        # Evolve the domain on each processor
        #------------------------------------------------------------  
        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
                                                   finaltime=finaltime, 
                                                   skip_initial_step = False)):

            stage = domain_fbound.get_quantity('stage')
            for i in range(4):
                if fbound_proc_tri_ids[i] > -1:
                    fbound_gauge_values[i].append(stage.centroid_values[fbound_proc_tri_ids[i]])
        
        #------------------------------------------------------------
        # Create domain to be run sequntially on each processor
        #------------------------------------------------------------
        domain_drchlt = Domain(meshname)
        domain_drchlt.set_quantities_to_be_stored(None)
        domain_drchlt.set_starttime(time_step)
        domain_drchlt.set_quantity('stage', tide)
        Br = Reflective_boundary(domain_drchlt)
        #Bd = Dirichlet_boundary([2.0+tide,220+10*tide,-220-10*tide])
        Bd = Time_boundary(domain=domain_drchlt, function=lambda t: [2.0+t/finaltime+tide,220.+10.*tide+10.*t/finaltime,-220.-10.*tide-10.*t/finaltime])
        #Bd = Time_boundary(domain=domain_drchlt,function=lambda t: [2.0+num.sin(t)+tide,10.*(2+20.+num.sin(t)+tide),-10.*(2+20.+num.sin(t)+tide)])
        domain_drchlt.set_boundary({'ocean': Bd,'otherocean': Br})
       
        drchlt_gauge_values = []
        drchlt_proc_tri_ids = []
        for i, point in enumerate(interpolation_points):
            drchlt_gauge_values.append([]) # Empty list for timeseries

            try:
                k = domain_drchlt.get_triangle_containing_point(point)
                if domain_drchlt.tri_full_flag[k] == 1:
                    drchlt_proc_tri_ids.append(k)
                else:
                    drchlt_proc_tri_ids.append(-1)            
            except:
                drchlt_proc_tri_ids.append(-2)


        if verbose: print 'P%d has points = %s' %(myid, drchlt_proc_tri_ids)

        #------------------------------------------------------------
        # Evolve entire domain on each processor
        #------------------------------------------------------------
        for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep,
                                                   finaltime=finaltime, 
                                                   skip_initial_step = False)):

            stage = domain_drchlt.get_quantity('stage')
            for i in range(4):
                drchlt_gauge_values[i].append(stage.centroid_values[drchlt_proc_tri_ids[i]])

        #------------------------------------------------------------
        # Compare sequential values with parallel values
        #------------------------------------------------------------
        barrier()
        success = True
        for i in range(4):
            if fbound_proc_tri_ids[i] > -1:
                fbound_gauge_values[i]=num.array(fbound_gauge_values[i])
                drchlt_gauge_values[i]=num.array(drchlt_gauge_values[i])
                #print i,fbound_gauge_values[i][4]
                #print i,drchlt_gauge_values[i][4]
                success = success and num.allclose(fbound_gauge_values[i], drchlt_gauge_values[i])
                assert success#, (fbound_gauge_values[i]-drchlt_gauge_values[i])

        #assert_(success)       

        if not sys.platform == 'win32':
            if myid==0: os.remove(sts_file+'.sts')
        
        if myid==0: os.remove(meshname)
    def test_create_mesh_from_regions(self):
        x=-500
        y=-1000
        mesh_geo = geo_reference=Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0,0], [100,0], [100,100], [0,100]]

        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}

        inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]]
        inner2_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner2_polygon_absolute)

        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     10000000,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo)

        # Test the mesh instance
        self.assertTrue(len(m.regions)==3, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs)==12, 'FAILED!')
        self.assertTrue(len(m.userVertices)==12, 'FAILED!')
        self.assertTrue(segs[0].tag=='walls', 'FAILED!')
        self.assertTrue(segs[1].tag=='walls', 'FAILED!')
        self.assertTrue(segs[2].tag=='bom', 'FAILED!')
        self.assertTrue(segs[3].tag=='bom', 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[0]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        msg = ('Expected point (%s,%s) to be inside polygon %s'
               % (str(poly_point.x+x), str(poly_point.y+y),
                  str(polygon_absolute)))
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          polygon_absolute, closed=False),
                        msg)

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[1]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          inner1_polygon_absolute,
                                          closed=False),
                        'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[2]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          inner2_polygon_absolute,
                                          closed=False),
                        'FAILED!')
Exemplo n.º 40
0
                  'side1':[1],
				  'side2':[2],
				    'top':[3],
			      'side3':[4],
			      'side4':[5]}

"""
Create the domain
"""

evolved_quantities =  ['stage', 'xmomentum', 'ymomentum', 'concentration']
								
from anuga.pmesh.mesh_interface import create_mesh_from_regions

create_mesh_from_regions(bounding_polygon = bounding_polygon,
                         boundary_tags = boundary_tags,
                         maximum_triangle_area = 200,
                         filename = filename_root + '.msh')

domain = Domain(filename_root + '.msh', evolved_quantities = evolved_quantities)

#------------------------------------------------------------------------------
# Setup parameters of computational domain
#------------------------------------------------------------------------------

# Print some stats about mesh and domain
print 'Number of triangles = ', len(domain)
print 'The extent is ', domain.get_extent()
print domain.statistics()


domain.set_quantity('elevation',