Changeset 996


Ignore:
Timestamp:
Mar 3, 2005, 4:53:13 PM (20 years ago)
Author:
duncan
Message:

now able to save tsh files as NetCDF files, use the extension .msh

Location:
inundation/ga/storm_surge/pmesh
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • inundation/ga/storm_surge/pmesh/load_mesh/loadASCII.py

    r985 r996  
    6262class TitleAmountError(exceptions.Exception): pass
    6363
     64NOMAXAREA=-999
     65
    6466def mesh_file_to_mesh_dictionary(fileName):
    6567    """Load a pmesh file.  Returning the mesh dictionary.
     
    9496        fd.close()
    9597    elif ofile[-4:]== ".msh":
    96         dict = read_tsh_file(ofile)
     98        dict = read_msh_file(ofile)
    9799    else:     
    98100        msg = 'Extension %s is unknown' %ofile[-4:]
     
    625627    outfile.createDimension('num_of_triangle_faces', 3)
    626628    outfile.createDimension('num_of_region_max_area', 1)
    627    
    628     # dimension definitions - variable
    629     #trianglulation
    630     outfile.createDimension('num_of_vertices', mesh['vertices'].shape[0])
    631     outfile.createDimension('num_of_vertex_attributes',
    632                             mesh['vertex_attributes'].shape[1])
    633     outfile.createDimension('num_of_vertex_attribute_title_chars',
    634                             mesh['vertex_attribute_titles'].shape[1])
    635    
    636     outfile.createDimension('num_of_segments',
    637                             mesh['segments'].shape[0])
    638     outfile.createDimension('num_of_segment_tag_chars',
    639                             mesh['segment_tags'].shape[1])
    640     outfile.createDimension('num_of_triangles',
    641                             mesh['triangles'].shape[0])
    642     outfile.createDimension('num_of_triangle_tag_chars',
    643                             mesh['triangle_tags'].shape[2])
    644     outfile.createDimension('num_of_triangle_tag_per_triangle',
    645                             mesh['triangle_tags'].shape[1])
    646 
    647     #outline
    648     outfile.createDimension('num_of_points', mesh['points'].shape[0])
    649     outfile.createDimension('num_of_point_attributes',
    650                             mesh['point_attributes'].shape[1])
    651     outfile.createDimension('num_of_outline_segments',
    652                             mesh['outline_segments'].shape[0])
    653     outfile.createDimension('num_of_outline_segment_tag_chars',
    654                             mesh['outline_segment_tags'].shape[1])
    655     outfile.createDimension('num_of_holes', mesh['holes'].shape[0])
    656     outfile.createDimension('num_of_regions', mesh['regions'].shape[0])
    657     outfile.createDimension('num_of_region_tag_chars',
    658                             mesh['region_tags'].shape[1])
    659    
    660    
    661     # variable definitions
     629
     630    # Create dimensions, variables and set the variables
     631   
    662632    # trianglulation
    663     outfile.createVariable('vertices', Float, ('num_of_vertices',
    664                                              'num_of_dimensions'))
    665     outfile.createVariable('vertex_attributes', Float, ('num_of_vertices',
    666                                              'num_of_vertex_attributes'))
    667     outfile.createVariable('vertex_attribute_titles',
    668                            Character,
    669                            ( 'num_of_vertex_attributes','num_of_vertex_attribute_title_chars' ))
    670     outfile.createVariable('segments',
    671                            IntType,
    672                            ('num_of_segments', 'num_of_segment_ends'))
    673     outfile.createVariable('segment_tags',
    674                            Character,
    675                            ('num_of_segments',
    676                             'num_of_segment_tag_chars'))
    677     outfile.createVariable('triangles',
    678                            IntType,
    679                            ('num_of_triangles', 'num_of_triangle_vertices'))
    680     outfile.createVariable('triangle_tags',
    681                            Character,
    682                            ('num_of_triangles',
    683                             'num_of_triangle_tag_per_triangle',
    684                             'num_of_triangle_tag_chars'))
    685     outfile.createVariable('triangle_neighbors',
    686                            IntType,
    687                            ('num_of_triangles', 'num_of_triangle_faces'))
    688    
    689    
     633    # vertices
     634    if (mesh['vertices'].shape[0] > 0):
     635        outfile.createDimension('num_of_vertices', mesh['vertices'].shape[0])
     636        outfile.createVariable('vertices', Float, ('num_of_vertices',
     637                                                   'num_of_dimensions'))
     638        outfile.variables['vertices'][:] = mesh['vertices']
     639        if (mesh['vertex_attributes'].shape[0] > 0 and mesh['vertex_attributes'].shape[1] > 0):
     640            outfile.createDimension('num_of_vertex_attributes',
     641                                    mesh['vertex_attributes'].shape[1])
     642            outfile.createDimension('num_of_vertex_attribute_title_chars',
     643                                    mesh['vertex_attribute_titles'].shape[1])
     644            outfile.createVariable('vertex_attributes',
     645                                   Float,
     646                                   ('num_of_vertices',
     647                                    'num_of_vertex_attributes'))   
     648            outfile.createVariable('vertex_attribute_titles',
     649                                   Character,
     650                                   ( 'num_of_vertex_attributes',
     651                                     'num_of_vertex_attribute_title_chars' ))
     652            outfile.variables['vertex_attributes'][:] = \
     653                                                      mesh['vertex_attributes']
     654            outfile.variables['vertex_attribute_titles'][:] = \
     655                                     mesh['vertex_attribute_titles']
     656    # segments
     657    if (mesh['segments'].shape[0] > 0):       
     658        outfile.createDimension('num_of_segments',
     659                                mesh['segments'].shape[0])
     660        outfile.createVariable('segments',
     661                               IntType,
     662                               ('num_of_segments', 'num_of_segment_ends'))
     663        outfile.variables['segments'][:] = mesh['segments']
     664        if (mesh['segment_tags'].shape[1] > 0):
     665            outfile.createDimension('num_of_segment_tag_chars',
     666                                    mesh['segment_tags'].shape[1])
     667            outfile.createVariable('segment_tags',
     668                                   Character,
     669                                   ('num_of_segments',
     670                                    'num_of_segment_tag_chars'))
     671            outfile.variables['segment_tags'][:] = mesh['segment_tags']
     672    # triangles   
     673    if (mesh['triangles'].shape[0] > 0):
     674        outfile.createDimension('num_of_triangles',
     675                                mesh['triangles'].shape[0])
     676        outfile.createVariable('triangles',
     677                               IntType,
     678                               ('num_of_triangles',
     679                                'num_of_triangle_vertices'))
     680        outfile.createVariable('triangle_neighbors',
     681                               IntType,
     682                               ('num_of_triangles',
     683                                'num_of_triangle_faces'))
     684        outfile.variables['triangles'][:] = mesh['triangles']
     685        outfile.variables['triangle_neighbors'][:] = mesh['triangle_neighbors']
     686        if (mesh['triangle_tags'].shape[2] > 0):
     687            outfile.createDimension('num_of_triangle_tag_chars',
     688                                    mesh['triangle_tags'].shape[2])
     689            outfile.createDimension('num_of_triangle_tag_per_triangle',
     690                                    mesh['triangle_tags'].shape[1])
     691            outfile.createVariable('triangle_tags',
     692                                   Character,
     693                                   ('num_of_triangles',
     694                                    'num_of_triangle_tag_per_triangle',
     695                                    'num_of_triangle_tag_chars'))
     696            outfile.variables['triangle_tags'][:] = mesh['triangle_tags']
     697   
     698
    690699    # outline
    691     outfile.createVariable('points', Float, ('num_of_points',
    692                                              'num_of_dimensions'))
    693     outfile.createVariable('point_attributes', Float, ('num_of_points',
    694                                              'num_of_point_attributes'))
    695    
    696     outfile.createVariable('outline_segments',
    697                            IntType,
    698                            ('num_of_outline_segments', 'num_of_segment_ends'))
    699     outfile.createVariable('outline_segment_tags',
    700                            Character,
    701                            ('num_of_outline_segments',
    702                             'num_of_outline_segment_tag_chars'))
    703     outfile.createVariable('holes', Float, ('num_of_holes',
    704                                              'num_of_dimensions'))
    705     outfile.createVariable('regions', Float, ('num_of_regions',
    706                                              'num_of_dimensions'))
    707     outfile.createVariable('region_tags',
    708                            Character,
    709                            ('num_of_regions',
    710                             'num_of_region_tag_chars'))
    711     outfile.createVariable('region_max_areas',
    712                            Float,
    713                            ('num_of_regions',)) #'num_of_region_max_area'))
    714 
    715     # Setting the variables
    716     #triangulation
    717     outfile.variables['vertices'][:] = mesh['vertices']
    718     outfile.variables['vertex_attributes'][:] = mesh['vertex_attributes']
    719     outfile.variables['vertex_attribute_titles'][:] = mesh['vertex_attribute_titles']
    720     outfile.variables['segments'][:] = mesh['segments']
    721     outfile.variables['segment_tags'][:] = mesh['segment_tags']
    722     outfile.variables['triangles'][:] = mesh['triangles']
    723     outfile.variables['triangle_tags'][:] = mesh['triangle_tags']
    724     outfile.variables['triangle_neighbors'][:] = mesh['triangle_neighbors']
    725    
    726     # Outline
    727     outfile.variables['points'][:] = mesh['points']
    728     outfile.variables['point_attributes'][:] = mesh['point_attributes']
    729     outfile.variables['outline_segments'][:] = mesh['outline_segments']
    730     outfile.variables['outline_segment_tags'][:] = mesh['outline_segment_tags']
    731     outfile.variables['holes'][:] = mesh['holes']
    732     outfile.variables['regions'][:] = mesh['regions']
    733     outfile.variables['region_tags'][:] = mesh['region_tags']
    734     outfile.variables['region_max_areas'][:] = mesh['region_max_areas']
    735    
     700    # points
     701    if (mesh['points'].shape[0] > 0):
     702        outfile.createDimension('num_of_points', mesh['points'].shape[0])
     703        outfile.createVariable('points', Float, ('num_of_points',
     704                                                 'num_of_dimensions'))
     705        outfile.variables['points'][:] = mesh['points']
     706        if (mesh['point_attributes'].shape[0] > 0  and mesh['point_attributes'].shape[1] > 0):
     707            outfile.createDimension('num_of_point_attributes',
     708                                    mesh['point_attributes'].shape[1])
     709            outfile.createVariable('point_attributes',
     710                                   Float,
     711                                   ('num_of_points',
     712                                    'num_of_point_attributes'))
     713            outfile.variables['point_attributes'][:] = mesh['point_attributes']
     714    # outline_segments
     715    if (mesh['outline_segments'].shape[0] > 0):
     716        outfile.createDimension('num_of_outline_segments',
     717                                mesh['outline_segments'].shape[0])
     718        outfile.createVariable('outline_segments',
     719                               IntType,
     720                               ('num_of_outline_segments',
     721                                'num_of_segment_ends'))
     722        outfile.variables['outline_segments'][:] = mesh['outline_segments']
     723        if (mesh['outline_segment_tags'].shape[1] > 0):
     724            outfile.createDimension('num_of_outline_segment_tag_chars',
     725                                    mesh['outline_segment_tags'].shape[1])
     726            outfile.createVariable('outline_segment_tags',
     727                                   Character,
     728                                   ('num_of_outline_segments',
     729                                    'num_of_outline_segment_tag_chars'))
     730            outfile.variables['outline_segment_tags'][:] = mesh['outline_segment_tags']
     731    # holes
     732    if (mesh['holes'].shape[0] > 0):
     733        outfile.createDimension('num_of_holes', mesh['holes'].shape[0])
     734        outfile.createVariable('holes', Float, ('num_of_holes',
     735                                                'num_of_dimensions'))
     736        outfile.variables['holes'][:] = mesh['holes']
     737    # regions
     738    if (mesh['regions'].shape[0] > 0):
     739        outfile.createDimension('num_of_regions', mesh['regions'].shape[0])
     740        outfile.createVariable('regions', Float, ('num_of_regions',
     741                                                  'num_of_dimensions'))
     742        outfile.createVariable('region_max_areas',
     743                               Float,
     744                               ('num_of_regions',))
     745        outfile.variables['regions'][:] = mesh['regions']
     746        outfile.variables['region_max_areas'][:] = mesh['region_max_areas']
     747        if (mesh['region_tags'].shape[1] > 0):
     748            outfile.createDimension('num_of_region_tag_chars',
     749                                    mesh['region_tags'].shape[1])
     750            outfile.createVariable('region_tags',
     751                                   Character,
     752                                   ('num_of_regions',
     753                                    'num_of_region_tag_chars'))
     754            outfile.variables['region_tags'][:] = mesh['region_tags']
     755       
    736756    outfile.close()
    737757
     
    745765       
    746766    from Scientific.IO.NetCDF import NetCDFFile         
    747             
     767           
    748768    #Check contents
    749769    #Get NetCDF
     
    753773    # Get the variables
    754774    # the triangulation
    755     mesh['vertices'] = fid.variables['vertices'][:]
    756     mesh['vertex_attributes'] = fid.variables['vertex_attributes'][:]
    757     titles = fid.variables['vertex_attribute_titles'][:]
     775    try:
     776        mesh['vertices'] = fid.variables['vertices'][:]
     777    except KeyError:
     778        mesh['vertices'] = array([])
     779    try:
     780        mesh['vertex_attributes'] = fid.variables['vertex_attributes'][:]
     781    except KeyError:
     782        mesh['vertex_attributes'] = []
     783        for ob in mesh['vertices']:
     784            mesh['vertex_attributes'].append([])
    758785    mesh['vertex_attribute_titles'] = []
    759     for i, title in enumerate(titles):
    760         mesh['vertex_attribute_titles'].append(titles[i].tostring().strip())
    761     mesh['segments'] = fid.variables['segments'][:]
    762     tags = fid.variables['segment_tags'][:]
     786    try:
     787        titles = fid.variables['vertex_attribute_titles'][:]
     788        for i, title in enumerate(titles):
     789            mesh['vertex_attribute_titles'].append(titles[i].tostring().strip())
     790    except KeyError:
     791        pass 
     792    try:
     793        mesh['segments'] = fid.variables['segments'][:]
     794    except KeyError:
     795        mesh['segments'] = array([])
    763796    mesh['segment_tags'] =[]
    764     for i, tag in enumerate(tags):
    765         mesh['segment_tags'].append(tags[i].tostring().strip())
    766     mesh['triangles'] = fid.variables['triangles'][:]
    767     tags = fid.variables['triangle_tags'][:]
     797    try:
     798        tags = fid.variables['segment_tags'][:]
     799        for i, tag in enumerate(tags):
     800            mesh['segment_tags'].append(tags[i].tostring().strip())
     801    except KeyError:
     802        for ob in mesh['segments']:
     803            mesh['segment_tags'].append('')
     804    try:
     805        mesh['triangles'] = fid.variables['triangles'][:]
     806        mesh['triangle_neighbors'] = fid.variables['triangle_neighbors'][:]
     807    except KeyError:
     808        mesh['triangles'] = array([])
     809        mesh['triangle_neighbors'] = array([])
    768810    mesh['triangle_tags'] =[]
    769     for i, tag in enumerate(tags):
    770         mesh['triangle_tags'].append(tags[i].tostring().strip())
    771     mesh['triangle_neighbors'] = fid.variables['triangle_neighbors'][:]
     811    try:
     812        tags = fid.variables['triangle_tags'][:]
     813        for i, tag in enumerate(tags):
     814            mesh['triangle_tags'].append([tags[i].tostring().strip()])
     815    except KeyError:
     816        for ob in mesh['triangles']:
     817            mesh['triangle_tags'].append([''])
    772818   
    773819    #the outline
    774     mesh['points'] = fid.variables['points'][:]
    775     mesh['point_attributes'] = fid.variables['point_attributes'][:]
    776     mesh['outline_segments'] = fid.variables['outline_segments'][:]
    777     tags = fid.variables['outline_segment_tags'][:]
     820    try:
     821        mesh['points'] = fid.variables['points'][:]
     822    except KeyError:
     823        mesh['points'] = []
     824    try:
     825        mesh['point_attributes'] = fid.variables['point_attributes'][:]
     826    except KeyError:
     827        mesh['point_attributes'] = []
     828        for point in mesh['points']:
     829            mesh['point_attributes'].append([])
     830    try:
     831        mesh['outline_segments'] = fid.variables['outline_segments'][:]
     832    except KeyError:
     833        mesh['outline_segments'] = array([])
    778834    mesh['outline_segment_tags'] =[]
    779     for i, tag in enumerate(tags):
    780         mesh['outline_segment_tags'].append(tags[i].tostring().strip())
    781    
    782     mesh['holes'] = fid.variables['holes'][:]
    783     mesh['regions'] = fid.variables['regions'][:]
    784     tags = fid.variables['region_tags'][:]
     835    try:
     836        tags = fid.variables['outline_segment_tags'][:]
     837        for i, tag in enumerate(tags):
     838            mesh['outline_segment_tags'].append(tags[i].tostring().strip())
     839    except KeyError:
     840        for ob in mesh['outline_segments']:
     841            mesh['outline_segment_tags'].append('')
     842    try:
     843        mesh['holes'] = fid.variables['holes'][:]
     844    except KeyError:
     845        mesh['holes'] = array([])
     846    try:
     847        mesh['regions'] = fid.variables['regions'][:]
     848    except KeyError:
     849        mesh['regions'] = array([])
    785850    mesh['region_tags'] =[]
    786     for i, tag in enumerate(tags):
    787         mesh['region_tags'].append(tags[i].tostring().strip())
    788     mesh['region_max_areas'] = fid.variables['region_max_areas'][:]
     851    try:
     852        tags = fid.variables['region_tags'][:]
     853        for i, tag in enumerate(tags):
     854            mesh['region_tags'].append(tags[i].tostring().strip())
     855    except KeyError:
     856        for ob in mesh['regions']:
     857            mesh['region_tags'].append('')
     858    try:
     859        mesh['region_max_areas'] = fid.variables['region_max_areas'][:]
     860    except KeyError:
     861        mesh['region_max_areas'] = array([])
    789862    #mesh[''] = fid.variables[''][:]
    790    
     863       
    791864    fid.close()
    792    
     865     
    793866    return mesh
    794867           
  • inundation/ga/storm_surge/pmesh/load_mesh/test_loadASCII.py

    r985 r996  
    3535        self.dict['region_max_areas'] = [36.0,-7.1]
    3636        self.dict['points'] = [(0.0, 0.0), (0.0, 4.0), (4.0, 0.0), (1.0, 1.0)]
    37 
    3837        self.dict['vertices'] = [(0.0, 0.0), (0.0, 4.0),
    39                                           (4.0, 0.0), (1.0, 1.0), (2.0, 2.0)]
     38                                 (4.0, 0.0), (1.0, 1.0), (2.0, 2.0)]
    4039        self.dict['triangles'] = [(3, 2, 4), (1, 0, 3),
    4140                                             (3, 4,1), (2, 3, 0)]
     
    4342                                            (0, 3), (4, 2)]
    4443        self.dict['triangle_tags'] = [['1.3'], ['1.3'],
    45                                                       ['1.3'], ['1.3']]
    46         self.dict['vertex_attributes'] = [[1.2,2.], [1.2,2.], [1.2,2.], [1.2,2.], [1.2,3.]]
     44                                      ['1.3'], ['1.3']]
     45        self.dict['vertex_attributes'] = [[1.2,2.], [1.2,2.],
     46                                          [1.2,2.], [1.2,2.], [1.2,3.]]
    4747        self.dict['triangle_neighbors'] = [[-1, 2, 3], [3, 2, -1],
    48                                                      [-1, 1, 0], [1, -1, 0]]
     48                                           [-1, 1, 0], [1, -1, 0]]
    4949        self.dict['segment_tags'] = ['50', '40', '30', '20', '40']
    5050        self.dict['vertex_attribute_titles'] = ['bed elevation', 'height']
     51       
     52        self.sparse_dict ={}
     53        self.sparse_dict['outline_segments'] = []
     54        self.sparse_dict['outline_segment_tags'] = []
     55        self.sparse_dict['holes'] = []
     56        self.sparse_dict['points'] = [(0.0, 0.0),(9,8)]
     57        self.sparse_dict['point_attributes'] = [[],[]] # points don't have to have
     58                                                    # attributes
     59        self.sparse_dict['regions'] = []
     60        self.sparse_dict['region_tags'] = []
     61        self.sparse_dict['region_max_areas'] = []
     62
     63        self.sparse_dict['vertices'] = []
     64        self.sparse_dict['triangles'] = []
     65        self.sparse_dict['segments'] = []
     66        self.sparse_dict['triangle_tags'] = []
     67        self.sparse_dict['vertex_attributes'] = []
     68        self.sparse_dict['triangle_neighbors'] = []
     69        self.sparse_dict['segment_tags'] = []
     70        self.sparse_dict['vertex_attribute_titles'] = []
     71       
     72        self.blank_dict ={}
     73        self.blank_dict['outline_segments'] = []
     74        self.blank_dict['outline_segment_tags'] = []
     75        self.blank_dict['holes'] = []
     76        self.blank_dict['points'] = []
     77        self.blank_dict['point_attributes'] = []
     78        self.blank_dict['regions'] = []
     79        self.blank_dict['region_tags'] = []
     80        self.blank_dict['region_max_areas'] = []
     81        self.blank_dict['vertices'] = []
     82        self.blank_dict['triangles'] = []
     83        self.blank_dict['segments'] = []
     84        self.blank_dict['triangle_tags'] = []
     85        self.blank_dict['vertex_attributes'] = []
     86        self.blank_dict['triangle_neighbors'] = []
     87        self.blank_dict['segment_tags'] = []
     88        self.blank_dict['vertex_attribute_titles'] = []
     89       
     90        self.tri_dict ={}
     91        self.tri_dict['outline_segments'] = [[0,1]]
     92        self.tri_dict['outline_segment_tags'] = ['']
     93        self.tri_dict['holes'] = []
     94        self.tri_dict['points'] = [(9,8),(7,8)]
     95        self.tri_dict['point_attributes'] = [[],[]]
     96        self.tri_dict['regions'] = []
     97        self.tri_dict['region_tags'] = []
     98        self.tri_dict['region_max_areas'] = []
     99        self.tri_dict['vertices'] = [[9,8],[7,8], [4,5]]
     100        self.tri_dict['triangles'] = [[0,1,2]]
     101        self.tri_dict['segments'] = [[0,1]]
     102        self.tri_dict['triangle_tags'] = [['']]
     103        self.tri_dict['vertex_attributes'] = [[],[],[]]
     104        self.tri_dict['triangle_neighbors'] = [[0,0,0]]
     105        self.tri_dict['segment_tags'] = ['']
     106        self.tri_dict['vertex_attribute_titles'] = []
     107       
     108        self.seg_dict ={}
     109        self.seg_dict['outline_segments'] = [[0,1]]
     110        self.seg_dict['outline_segment_tags'] = ['']
     111        self.seg_dict['holes'] = []
     112        self.seg_dict['points'] = [(9,8),(7,8)]
     113        self.seg_dict['point_attributes'] = [[],[]] 
     114        self.seg_dict['regions'] = [(5,4)]
     115        self.seg_dict['region_tags'] = ['']
     116        self.seg_dict['region_max_areas'] = [-999]
     117        self.seg_dict['vertices'] = [(9,8),(7,8)]
     118        self.seg_dict['triangles'] = []
     119        self.seg_dict['segments'] = [[0,1]]
     120        self.seg_dict['triangle_tags'] = []
     121        self.seg_dict['vertex_attributes'] = [[],[]]
     122        self.seg_dict['triangle_neighbors'] = []
     123        self.seg_dict['segment_tags'] = ['']
     124        self.seg_dict['vertex_attribute_titles'] = []
     125       
     126        self.reg_dict ={}
     127        self.reg_dict['outline_segments'] = [[0,1]]
     128        self.reg_dict['outline_segment_tags'] = ['']
     129        self.reg_dict['holes'] = []
     130        self.reg_dict['points'] = [(9,8),(7,8)]
     131        self.reg_dict['point_attributes'] = [[],[]]
     132        self.reg_dict['regions'] = [(5,4)]
     133        self.reg_dict['region_tags'] = ['']
     134        self.reg_dict['region_max_areas'] = []
     135        self.reg_dict['vertices'] = [(9,8),(7,8)]
     136        self.reg_dict['triangles'] = []
     137        self.reg_dict['segments'] = [[0,1]]
     138        self.reg_dict['triangle_tags'] = []
     139        self.reg_dict['vertex_attributes'] = [[],[]]
     140        self.reg_dict['triangle_neighbors'] = []
     141        self.reg_dict['segment_tags'] = ['']
     142        self.reg_dict['vertex_attribute_titles'] = []
     143       
    51144    def tearDown(self):
    52145        pass
     
    141234 
    142235    def test_read_write_msh_file(self):
    143        
    144236        dict = self.dict.copy()
    145237        fileName = tempfile.mktemp(".txt")
     
    147239        loaded_dict = read_msh_file(fileName)
    148240        os.remove(fileName)
    149 
    150        
    151241        dict = self.dict
    152242        #print "*********************"
     
    155245        #print loaded_dict
    156246        #print "*********************"
    157 
    158        
    159         self.failUnless(array(loaded_dict['points'])  ==
    160                         array(dict['points']),
    161                          'test_import_mesh failed. Test 1')
    162         self.failUnless(array(loaded_dict['point_attributes'])  ==
    163                         array(dict['point_attributes']),
    164                          'test_import_mesh failed. Test 2')
     247        self.check_mesh_dicts(loaded_dict,dict,'test_read_write_msh_file')
     248
     249    def test_read_write_msh_fileII(self):
     250        dict = self.sparse_dict.copy()
     251        fileName = tempfile.mktemp(".txt")
     252        write_msh_file(fileName,dict)
     253        loaded_dict = read_msh_file(fileName)
     254        os.remove(fileName)
     255        dict = self.sparse_dict
     256        #print "*********************"
     257        #print dict
     258        #print "**loaded_dict*******************"
     259        #print loaded_dict
     260        #print "*********************"       
     261        self.check_mesh_dicts(loaded_dict,dict, 'test_read_write_msh_fileII')
     262             
     263    def test_read_write_msh_fileIII(self):
     264        dict = self.blank_dict.copy()
     265        fileName = tempfile.mktemp(".txt")
     266        write_msh_file(fileName,dict)
     267        loaded_dict = read_msh_file(fileName)
     268        os.remove(fileName)
     269        dict = self.blank_dict
     270        #print "*********************"
     271        #print dict
     272        #print "**loaded_dict*******************"
     273        #print loaded_dict
     274        #print "*********************"       
     275        self.check_mesh_dicts(loaded_dict,dict, 'test_read_write_msh_fileIII')
     276       
     277    def test_read_write_msh_file4(self):
     278        dict = self.seg_dict.copy()
     279        fileName = tempfile.mktemp(".txt")
     280        write_msh_file(fileName,dict)
     281        loaded_dict = read_msh_file(fileName)
     282        os.remove(fileName)
     283        dict = self.seg_dict
     284        #print "*********************"
     285        #print dict
     286        #print "**loaded_dict*******************"
     287        #print loaded_dict
     288        #print "*********************"
     289        self.check_mesh_dicts(loaded_dict,dict, 'test_read_write_msh_fileIII')
     290                         
     291       
     292    def test_read_write_msh_file5(self):
     293        dict = self.tri_dict.copy()
     294        fileName = tempfile.mktemp(".txt")
     295        write_msh_file(fileName,dict)
     296        loaded_dict = read_msh_file(fileName)
     297        os.remove(fileName)
     298        dict = self.tri_dict
     299        #print "*********************"
     300        #print dict
     301        #print "**loaded_dict*******************"
     302        #print loaded_dict
     303        #print "*********************"
     304        self.check_mesh_dicts(loaded_dict,dict, 'test_read_write_msh_fileIII')
     305                         
     306    def check_mesh_dicts(self, loaded_dict, dict, fail_string ):
     307        assert allclose(array(loaded_dict['points']),
     308                        array(dict['points']))
     309                       
     310        assert allclose(array(loaded_dict['point_attributes']),
     311                        array(dict['point_attributes']))
     312        assert allclose(array(loaded_dict['outline_segments']),
     313                        array(dict['outline_segments']))
     314       
     315        self.failUnless(loaded_dict['outline_segment_tags']  ==
     316                        dict['outline_segment_tags'],
     317                        fail_string + ' failed!! Test 4')
     318       
     319           
     320        assert allclose(array(loaded_dict['regions']),
     321                        array(dict['regions']))
     322        self.failUnless(loaded_dict['region_tags']  ==
     323                        dict['region_tags'],
     324                        fail_string + ' failed!! Test 5')
     325       
     326        assert allclose(array(loaded_dict['region_max_areas']),
     327                        array(dict['region_max_areas']))
     328 
     329        assert allclose(array(loaded_dict['holes']),
     330                        array(dict['holes']))
     331 
     332        assert allclose(array(dict['vertices']),
     333                        array(loaded_dict['vertices']))
     334 
     335        assert allclose(array(dict['triangles']),
     336                        array(loaded_dict['triangles']))
     337 
     338        assert allclose(array(dict['segments']),
     339                        array(loaded_dict['segments']))
     340        for ob, ldob in map(None,dict['triangle_tags'],
     341                              loaded_dict['triangle_tags']):
     342            self.failUnless(ob[0]  == ldob[0],
     343                        fail_string + ' failed!! Test triangle_tags')
     344        self.failUnless(loaded_dict['vertex_attributes']  ==
     345                        dict['vertex_attributes'],
     346                        fail_string + ' failed!! Test vertex_attributes')
     347 
     348        assert allclose(array(dict['triangle_neighbors']),
     349                        array(loaded_dict['triangle_neighbors']))
     350
     351        for seg, ldseg in map(None,dict['segment_tags'],
     352                              loaded_dict['segment_tags']):
     353            self.failUnless(seg  == ldseg,
     354                        fail_string + ' failed!! Test 8')
     355        try:
     356            assert allclose(array(dict['vertex_attribute_titles']),
     357                            array(loaded_dict['vertex_attribute_titles']))
     358        except TypeError:
     359            self.failUnless(array(loaded_dict['vertex_attribute_titles'])  ==
     360                        array(dict['vertex_attribute_titles']),
     361                        fail_string + ' failed!! Test 8')
     362 
     363    def baaaad(self):
     364       
     365        assert allclose(array(loaded_dict['point_attributes']),
     366                        array(dict['point_attributes']))
    165367        self.failUnless(array(loaded_dict['outline_segments'])  ==
    166368                        array(dict['outline_segments']),
    167                          'test_import_mesh failed. Test 3')
     369                          fail_string + ' failed. Test 3')
    168370        self.failUnless(array(loaded_dict['outline_segment_tags'])  ==
    169371                        array(dict['outline_segment_tags']),
    170                          'test_import_mesh failed. Test 4')
     372                          fail_string + ' failed! Test 4')
    171373        self.failUnless(array(loaded_dict['regions'])  ==
    172374                        array(dict['regions']),
    173                          'test_import_mesh failed. Test 5')
     375                          fail_string + ' failed. Test 5')
    174376        self.failUnless(array(loaded_dict['region_tags'])  ==
    175377                        array(dict['region_tags']),
    176                          'test_import_mesh failed. Test 5')
     378                          fail_string + ' failed. Test 5')
    177379        self.failUnless(array(loaded_dict['region_max_areas'])  ==
    178380                        array(dict['region_max_areas']),
    179                          'test_import_mesh failed. Test 5')
    180 
     381                          fail_string + ' failed. Test 5')
    181382        self.failUnless(array(loaded_dict['holes'])  ==
    182383                        array(dict['holes']),
    183                          'test_import_mesh failed. Test 6')
    184    
     384                          fail_string + ' failed. Test 6')
    185385        self.failUnless(array(dict['vertices'])  ==
    186386                        array(loaded_dict['vertices']),
    187                          'test_export_triangulation_file failed. Test 1')
     387                          fail_string + ' failed. Test 7')
    188388        self.failUnless(array(dict['triangles'])  ==
    189389                        array(loaded_dict['triangles']),
    190                          'test_export_triangulation_file failed. Test 2')
     390                          fail_string + ' failed. Test 8')
    191391        self.failUnless(array(dict['segments'])  ==
    192392                        array(loaded_dict['segments']),
    193                          'test_export_triangulation_file failed. Test 3')
     393                          fail_string + ' failed. Test 9')
    194394        self.failUnless(array(dict['triangle_tags'])  ==
    195395                        array(loaded_dict['triangle_tags']),
    196                          'test_export_triangulation_file failed. Test 4')
    197        
     396                          fail_string + ' failed. Test 10')
    198397        self.failUnless(dict['vertex_attributes']  ==
    199398                        loaded_dict['vertex_attributes'],
    200                          'test_export_triangulation_file failed. Test 5')
     399                          fail_string + ' failed. Test 11')
    201400        self.failUnless(array(dict['triangle_neighbors'])  ==
    202401                        array(loaded_dict['triangle_neighbors']),
    203                          'test_export_triangulation_file failed. Test 6')
     402                          fail_string + ' failed. Test 12')
    204403        self.failUnless(array(dict['segment_tags'])  ==
    205404                        array(loaded_dict['segment_tags']),
    206                          'test_export_triangulation_file failed. Test 7')
     405                          fail_string + ' failed. Test 13')
    207406        self.failUnless(array(dict['vertex_attribute_titles'])  ==
    208407                        array(loaded_dict['vertex_attribute_titles']),
    209                          'test_export_triangulation_file failed. Test 8')
     408                          fail_string + ' failed. Test 14')
    210409       
    211410    def test_loadpts(self):
     
    422621
    423622    suite = unittest.makeSuite(loadASCIITestCase,'test')
    424     runner = unittest.TextTestRunner() #verbosity=2)
     623    runner = unittest.TextTestRunner(verbosity=2)
    425624    runner.run(suite)
    426625   
  • inundation/ga/storm_surge/pmesh/mesh.py

    r988 r996  
    2929
    3030SET_COLOUR='red'
    31 NOMAXAREA=-999
    32 
    33 
    34 #for alpha shapes boundary type
    35 RAW = 0
    36 REMOVE_HOLES = 1
    37 REMOVE_SHARP_INDENTS = 2
    38 REMOVE_PINCH_OFF = 3
    39 
    4031
    4132   
     
    15341525            #Most probably, the Tkinter module is not available.
    15351526            #"""
    1536            
    1537     # Is this used by anything? 
    1538     def exportASCIItriangulationfile(self,ofile):
     1527             
     1528    def export_triangulation_file(self,ofile):
    15391529        """
    15401530        export a file, ofile, with the format
     
    15481538        Following lines:  <segment #> <vertex #>  <vertex #> [boundary tag]
    15491539        """
    1550         fd = open(ofile,'w')
    1551         gen_dict = self.Mesh2IOTriangulationDict()
    1552         load_mesh.loadASCII.write_ASCII_triangulation(fd,gen_dict)
    1553         self.writeASCIImesh(fd,
    1554                             self.userVertices,
    1555                             self.getUserSegments(),
    1556                             self.holes,
    1557                             self.regions)   
    1558         fd.close()
    1559 
     1540        gen_dict = self.Mesh2IODict()
     1541        if (ofile[-4:] == ".tsh"):
     1542            fd = open(ofile,'w')
     1543            load_mesh.loadASCII.write_ASCII_triangulation(fd,gen_dict)
     1544            self.writeASCIImesh(fd,
     1545                                self.userVertices,
     1546                                self.getUserSegments(),
     1547                                self.holes,
     1548                                self.regions)   
     1549            fd.close()
     1550        elif (ofile[-4:] == ".msh"):
     1551            print "mesh gen_dict",gen_dict
     1552            load_mesh.loadASCII.write_msh_file(ofile, gen_dict)
     1553           
    15601554    def exportASCIIsegmentoutlinefile(self,ofile):
    15611555        """
     
    18651859                regionmaxarealist.append(region.getMaxArea())
    18661860            else:
    1867                 regionmaxarealist.append( NOMAXAREA)
     1861                regionmaxarealist.append( load_mesh.loadASCII.NOMAXAREA)
    18681862        meshDict['regions'] = regionlist
    18691863        meshDict['region_tags'] = regiontaglist
     
    20021996                                   genDict['region_tags'],
    20031997                                   genDict['region_max_areas']):
    2004             Object = Region( reg[0],
    2005                              reg[1],
    2006                              tag = att,
    2007                              maxArea = maxArea)
     1998            if maxArea > 0:  # maybe I should ref NOMAXAREA? Prob' not though
     1999                Object = Region( reg[0],
     2000                                 reg[1],
     2001                                 tag = att,
     2002                                 maxArea = maxArea)
     2003            else:
     2004                Object = Region( reg[0],
     2005                                 reg[1],
     2006                                 tag = att)
     2007               
    20082008            #Object.index = index
    20092009            #index +=1
     
    22632263        if (counter >0):
    22642264            print "%i duplicate vertices removed from dataset" % (counter) 
    2265     elif ofile[-4:]== ".tsh":
     2265    elif (ofile[-4:]== ".tsh" or ofile[-4:]== ".msh"):
    22662266        dict = load_mesh.loadASCII.import_triangulation(ofile)
     2267        print "********"
     2268        print "dict",dict
     2269        print "********"
    22672270        newmesh= Mesh()
    22682271        newmesh.IOOutline2Mesh(dict)
  • inundation/ga/storm_surge/pmesh/meshHarness.py

    r969 r996  
    478478        seg = m.getMeshSegments()
    479479       
    480         fileName = tempfile.mktemp(".txt")
    481         m.exportASCIItriangulationfile(fileName)
     480        fileName = tempfile.mktemp(".tsh")
     481        m.export_triangulation_file(fileName)
    482482        file = open(fileName)
    483483        lFile = file.read().split('\n')
     
    552552        seg = m.getMeshSegments()
    553553       
    554         fileName = tempfile.mktemp(".txt")
    555         m.exportASCIItriangulationfile(fileName)
     554        fileName = tempfile.mktemp(".tsh")
     555        m.export_triangulation_file(fileName)
    556556        file = open(fileName)
    557557        lFile = file.read().split('\n')
     
    684684        #print "dgs!!!"
    685685        #print "****************** fileName", fileName
    686         m.exportASCIItriangulationfile(fileName)
     686        m.export_triangulation_file(fileName)
    687687        #print "******************"
    688688        #print "m", m
  • inundation/ga/storm_surge/pmesh/pmesh.py

    r988 r996  
    11711171                ofile = ofile + addOn
    11721172            try:
    1173                 self.mesh.exportASCIItriangulationfile(ofile)
     1173                self.mesh.export_triangulation_file(ofile)
    11741174            except IOError:
    11751175                showerror('Export ASCII file',
     
    11791179                                   'No triangulation to export.')
    11801180               
     1181   
     1182    def export_tsh(self):
     1183        fileType = "tsh"
     1184        fileTypeDesc = "text Mesh"
     1185       
     1186        ofile = tkFileDialog.asksaveasfilename(initialdir=self.currentPath,
     1187                                         filetypes=[(fileTypeDesc, fileType),
     1188                                                ("All Files", "*")])
     1189        if ofile:
     1190            addOn = "." + fileType
     1191            jumpback = - len(addOn)
     1192            if ofile[jumpback:] != addOn: 
     1193                ofile = ofile + addOn
     1194            try:
     1195                self.mesh.exportASCIImeshfile(ofile)
     1196            except IOError:
     1197                showerror('Export ASCII file',
     1198                                   'Can not write to file.')
     1199            except RuntimeError:
     1200                showerror('Export ASCII file',
     1201                                   'No mesh to export.')
    11811202   
    11821203    def exportMesh(self):
     
    12071228        print "self.currentPath",self.currentPath
    12081229        ofile = tkFileDialog.askopenfilename(initialdir=self.currentPath,
    1209                                              filetypes=[ ("text Mesh", "tsh"),
     1230                                             filetypes=[ ("text Mesh", "*.tsh *.msh"),
    12101231                                                         ("points", "*.xya *.pts"),
    12111232                                           ("All Files", "*")])
     
    12881309        """
    12891310        #print "dsg!!! self.currentFilePathName ",self.currentFilePathName
    1290         if (self.currentFilePathName[-4:] != ".tsh"):
     1311        if (self.currentFilePathName[-4:] != ".tsh" or
     1312            self.currentFilePathName[-4:] != ".msh"):
    12911313            # force user to choose a name
    12921314            self.saveAsDrawing()
     
    12991321        """
    13001322        ofile = tkFileDialog.asksaveasfilename(initialdir=self.currentPath,
    1301                                                filetypes=[("text mesh", "tsh"),
     1323                                               filetypes=[("mesh", "*.tsh *.msh"),
    13021324                                             ("All Files", "*")])
    1303         print "aa"
     1325           
    13041326        if ofile:
    1305             if ofile[-4:] == ".tsh"
     1327            if (ofile[-4:] == ".tsh" or ofile[-4:] == ".msh")
    13061328                self.currentFilePathName = ofile
    13071329            else:
     
    13281350                                   type=YESNOCANCEL)
    13291351            if m == "no":
    1330                 self.mesh.exportASCIItriangulationfile(currentFilePathName)
     1352                self.mesh.export_triangulation_file(currentFilePathName)
    13311353                self.UserMeshChanged = False
    13321354            elif m == "cancel":
     
    13341356            elif m == "yes":
    13351357                self.windowMeshGen(None)
    1336                 self.mesh.exportASCIItriangulationfile(currentFilePathName)
     1358                self.mesh.export_triangulation_file(currentFilePathName)
    13371359        else:
    1338             self.mesh.exportASCIItriangulationfile(currentFilePathName)
     1360            self.mesh.export_triangulation_file(currentFilePathName)
    13391361            self.UserMeshChanged = False
    13401362           
Note: See TracChangeset for help on using the changeset viewer.