Changeset 2939


Ignore:
Timestamp:
May 22, 2006, 2:15:24 PM (18 years ago)
Author:
duncan
Message:

adding fit_to_mesh_file

Location:
inundation/fit_interpolate
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • inundation/fit_interpolate/fit.py

    r2924 r2939  
    2121"""
    2222
    23 from Numeric import zeros, Float
     23from Numeric import zeros, Float, ArrayType
    2424
    2525from geospatial_data.geospatial_data import Geospatial_data, ensure_absolute
     
    215215        data points.
    216216
     217        If Ata is None, the matrices AtA and Atz are created.
     218
     219        This function can be called again and again, with sub-sets of
     220        the point coordinates.  Call fit to get the results.
     221       
    217222        Preconditions
    218223        z and points are numeric
     
    235240
    236241            self.AtA = Sparse(m,m)
    237             #self.Atz = zeros((m,att_num), Float)
    238242        self.point_count += point_coordinates.shape[0]
    239243        #print "_build_matrix_AtA_Atz - self.point_count", self.point_count
     
    256260            element_found, sigma0, sigma1, sigma2, k = \
    257261                           search_tree_of_vertices(self.root, self.mesh, x)
    258             #Update interpolation matrix A if necessary
     262           
    259263            if element_found is True:
    260                 #Assign values to matrix A
    261 
    262264                j0 = self.mesh.triangles[k,0] #Global vertex id for sigma0
    263265                j1 = self.mesh.triangles[k,1] #Global vertex id for sigma1
     
    431433
    432434
     435def fit_to_mesh_file(mesh_file, point_file, mesh_output_file,
     436                     alpha=DEFAULT_ALPHA, verbose= False,
     437                     display_errors = True):
     438    """
     439    Given a mesh file (tsh) and a point attribute file (xya), fit
     440    point attributes to the mesh and write a mesh file with the
     441    results.
     442
     443
     444    If data_origin is not None it is assumed to be
     445    a 3-tuple with geo referenced
     446    UTM coordinates (zone, easting, northing)
     447
     448    NOTE: Throws IOErrors, for a variety of file problems.
     449   
     450    """
     451
     452    # Question
     453    # should data_origin and mesh_origin be passed in?
     454    # No they should be in the data structure
     455    #
     456    #Should the origin of the mesh be changed using this function?
     457    # That is overloading this function.  Have it as a seperate
     458    # method, at least initially.
     459   
     460    from load_mesh.loadASCII import import_mesh_file, \
     461                 import_points_file, export_mesh_file, \
     462                 concatinate_attributelist
     463
     464    # FIXME: Use geospatial instead of import_points_file
     465    try:
     466        mesh_dict = import_mesh_file(mesh_file)
     467    except IOError,e:
     468        if display_errors:
     469            print "Could not load bad file. ", e
     470        raise IOError  #Re-raise exception
     471       
     472    vertex_coordinates = mesh_dict['vertices']
     473    triangles = mesh_dict['triangles']
     474    if type(mesh_dict['vertex_attributes']) == ArrayType:
     475        old_point_attributes = mesh_dict['vertex_attributes'].tolist()
     476    else:
     477        old_point_attributes = mesh_dict['vertex_attributes']
     478
     479    if type(mesh_dict['vertex_attribute_titles']) == ArrayType:
     480        old_title_list = mesh_dict['vertex_attribute_titles'].tolist()
     481    else:
     482        old_title_list = mesh_dict['vertex_attribute_titles']
     483
     484    if verbose: print 'tsh file %s loaded' %mesh_file
     485
     486    # load in the .pts file
     487    try:
     488        point_dict = import_points_file(point_file, verbose=verbose)
     489    except IOError,e:
     490        if display_errors:
     491            print "Could not load bad file. ", e
     492        raise IOError  #Re-raise exception 
     493
     494    point_coordinates = point_dict['pointlist']
     495    title_list,point_attributes = concatinate_attributelist(point_dict['attributelist'])
     496
     497    if point_dict.has_key('geo_reference') and not point_dict['geo_reference'] is None:
     498        data_origin = point_dict['geo_reference'].get_origin()
     499    else:
     500        data_origin = (56, 0, 0) #FIXME(DSG-DSG)
     501
     502    if mesh_dict.has_key('geo_reference') and not mesh_dict['geo_reference'] is None:
     503        mesh_origin = mesh_dict['geo_reference'].get_origin()
     504    else:
     505        mesh_origin = (56, 0, 0) #FIXME(DSG-DSG)
     506
     507    if verbose: print "points file loaded"
     508    if verbose: print "fitting to mesh"
     509    f = fit_to_mesh(vertex_coordinates,
     510                    triangles,
     511                    point_coordinates,
     512                    point_attributes,
     513                    alpha = alpha,
     514                    verbose = verbose,
     515                    data_origin = data_origin,
     516                    mesh_origin = mesh_origin)
     517    if verbose: print "finished fitting to mesh"
     518
     519    # convert array to list of lists
     520    new_point_attributes = f.tolist()
     521    #FIXME have this overwrite attributes with the same title - DSG
     522    #Put the newer attributes last
     523    if old_title_list <> []:
     524        old_title_list.extend(title_list)
     525        #FIXME can this be done a faster way? - DSG
     526        for i in range(len(old_point_attributes)):
     527            old_point_attributes[i].extend(new_point_attributes[i])
     528        mesh_dict['vertex_attributes'] = old_point_attributes
     529        mesh_dict['vertex_attribute_titles'] = old_title_list
     530    else:
     531        mesh_dict['vertex_attributes'] = new_point_attributes
     532        mesh_dict['vertex_attribute_titles'] = title_list
     533
     534    if verbose: print "exporting to file ", mesh_output_file
     535
     536    try:
     537        export_mesh_file(mesh_output_file, mesh_dict)
     538    except IOError,e:
     539        if display_errors:
     540            print "Could not write file. ", e
     541        raise IOError
     542
     543
    433544def _fit(*args, **kwargs):
    434545    """Private function for use with caching. Reason is that classes
  • inundation/fit_interpolate/test_fit.py

    r2897 r2939  
    488488
    489489
     490    def test_fit_to_mesh_file(self):
     491        from load_mesh.loadASCII import import_mesh_file, \
     492             export_mesh_file
     493        import tempfile
     494        import os
     495
     496        # create a .tsh file, no user outline
     497        mesh_dic = {}
     498        mesh_dic['vertices'] = [[0.0, 0.0],
     499                                          [0.0, 5.0],
     500                                          [5.0, 0.0]]
     501        mesh_dic['triangles'] =  [[0, 2, 1]]
     502        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
     503        mesh_dic['triangle_tags'] = ['']
     504        mesh_dic['vertex_attributes'] = [[], [], []]
     505        mesh_dic['vertiex_attribute_titles'] = []
     506        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
     507        mesh_dic['segment_tags'] = ['external',
     508                                                  'external',
     509                                                  'external']
     510        mesh_file = tempfile.mktemp(".tsh")
     511        export_mesh_file(mesh_file,mesh_dic)
     512
     513        # create an .xya file
     514        point_file = tempfile.mktemp(".xya")
     515        fd = open(point_file,'w')
     516        fd.write("elevation, stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
     517        fd.close()
     518
     519        mesh_output_file = tempfile.mktemp(".tsh")
     520        fit_to_mesh_file(mesh_file,
     521                         point_file,
     522                         mesh_output_file,
     523                         alpha = 0.0)
     524        # load in the .tsh file we just wrote
     525        mesh_dic = import_mesh_file(mesh_output_file)
     526        #print "mesh_dic",mesh_dic
     527        ans =[[0.0, 0.0],
     528              [5.0, 10.0],
     529              [5.0,10.0]]
     530        assert allclose(mesh_dic['vertex_attributes'],ans)
     531
     532        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
     533                        ['elevation','stage'],
     534                        'test_fit_to_mesh_file failed')
     535
     536        #clean up
     537        os.remove(mesh_file)
     538        os.remove(point_file)
     539        os.remove(mesh_output_file)
     540
     541
     542    def test_fit_to_mesh_file3(self):
     543        from load_mesh.loadASCII import import_mesh_file, \
     544             export_mesh_file
     545        import tempfile
     546        import os
     547
     548        # create a .tsh file, no user outline
     549        mesh_dic = {}
     550        mesh_dic['vertices'] = [[0.76, 0.76],
     551                                          [0.76, 5.76],
     552                                          [5.76, 0.76]]
     553        mesh_dic['triangles'] =  [[0, 2, 1]]
     554        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
     555        mesh_dic['triangle_tags'] = ['']
     556        mesh_dic['vertex_attributes'] = [[], [], []]
     557        mesh_dic['vertiex_attribute_titles'] = []
     558        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
     559        mesh_dic['segment_tags'] = ['external',
     560                                                  'external',
     561                                                  'external']
     562        mesh_dic['geo_reference'] = Geo_reference(56,-0.76,-0.76)
     563        mesh_file = tempfile.mktemp(".tsh")
     564        export_mesh_file(mesh_file,mesh_dic)
     565
     566        # create an .xya file
     567        point_file = tempfile.mktemp(".xya")
     568        fd = open(point_file,'w')
     569        fd.write("elevation, stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
     570        fd.close()
     571
     572        mesh_output_file = tempfile.mktemp(".tsh")
     573        fit_to_mesh_file(mesh_file,
     574                         point_file,
     575                         mesh_output_file,
     576                         alpha = 0.0)
     577        # load in the .tsh file we just wrote
     578        mesh_dic = import_mesh_file(mesh_output_file)
     579        #print "mesh_dic",mesh_dic
     580        ans =[[0.0, 0.0],
     581              [5.0, 10.0],
     582              [5.0,10.0]]
     583        assert allclose(mesh_dic['vertex_attributes'],ans)
     584
     585        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
     586                        ['elevation','stage'],
     587                        'test_fit_to_mesh_file failed')
     588
     589        #clean up
     590        os.remove(mesh_file)
     591        os.remove(point_file)
     592        os.remove(mesh_output_file)
     593
     594    def test_fit_to_mesh_file4(self):
     595        from load_mesh.loadASCII import import_mesh_file, \
     596             export_mesh_file
     597        import tempfile
     598        import os
     599
     600        # create a .tsh file, no user outline
     601        mesh_dic = {}
     602        mesh_dic['vertices'] = [[0.76, 0.76],
     603                                [0.76, 5.76],
     604                                [5.76, 0.76]]
     605        mesh_dic['triangles'] =  [[0, 2, 1]]
     606        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
     607        mesh_dic['triangle_tags'] = ['']
     608        mesh_dic['vertex_attributes'] = [[], [], []]
     609        mesh_dic['vertiex_attribute_titles'] = []
     610        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
     611        mesh_dic['segment_tags'] = ['external',
     612                                    'external',
     613                                    'external']
     614        mesh_dic['geo_reference'] = Geo_reference(56,-0.76,-0.76)
     615        mesh_file = tempfile.mktemp(".tsh")
     616        export_mesh_file(mesh_file,mesh_dic)
     617
     618        geo_ref = Geo_reference(56,-200,-400)
     619        # create an .xya file
     620        point_file = tempfile.mktemp(".xya")
     621        fd = open(point_file,'w')
     622        fd.write("elevation, stage \n 201.0, 401.0,2.,4 \n 201.0, 403.0,4,8 \n 203.0, 401.0,4.,8 \n")
     623        geo_ref.write_ASCII(fd)
     624        fd.close()
     625
     626        mesh_output_file = tempfile.mktemp(".tsh")
     627        fit_to_mesh_file(mesh_file,
     628                         point_file,
     629                         mesh_output_file,
     630                         alpha = 0.0)
     631        # load in the .tsh file we just wrote
     632        mesh_dic = import_mesh_file(mesh_output_file)
     633        #print "mesh_dic",mesh_dic
     634        ans =[[0.0, 0.0],
     635              [5.0, 10.0],
     636              [5.0, 10.0]]
     637        assert allclose(mesh_dic['vertex_attributes'],ans)
     638
     639        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
     640                        ['elevation','stage'],
     641                        'test_fit_to_mesh_file failed')
     642
     643        #clean up
     644        os.remove(mesh_file)
     645        os.remove(point_file)
     646        os.remove(mesh_output_file)
     647
     648    def test_fit_to_mesh_fileII(self):
     649        from load_mesh.loadASCII import import_mesh_file, \
     650             export_mesh_file
     651        import tempfile
     652        import os
     653
     654        # create a .tsh file, no user outline
     655        mesh_dic = {}
     656        mesh_dic['vertices'] = [[0.0, 0.0],
     657                                [0.0, 5.0],
     658                                [5.0, 0.0]]
     659        mesh_dic['triangles'] =  [[0, 2, 1]]
     660        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
     661        mesh_dic['triangle_tags'] = ['']
     662        mesh_dic['vertex_attributes'] = [[1,2], [1,2], [1,2]]
     663        mesh_dic['vertex_attribute_titles'] = ['density', 'temp']
     664        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
     665        mesh_dic['segment_tags'] = ['external',
     666                                                  'external',
     667                                                  'external']
     668        mesh_file = tempfile.mktemp(".tsh")
     669        export_mesh_file(mesh_file,mesh_dic)
     670
     671        # create an .xya file
     672        point_file = tempfile.mktemp(".xya")
     673        fd = open(point_file,'w')
     674        fd.write("elevation, stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
     675        fd.close()
     676
     677        mesh_output_file = "new_triangle.tsh"
     678        fit_to_mesh_file(mesh_file,
     679                         point_file,
     680                         mesh_output_file,
     681                         alpha = 0.0)
     682        # load in the .tsh file we just wrote
     683        mesh_dic = import_mesh_file(mesh_output_file)
     684
     685        assert allclose(mesh_dic['vertex_attributes'],
     686                        [[1.0, 2.0,0.0, 0.0],
     687                         [1.0, 2.0,5.0, 10.0],
     688                         [1.0, 2.0,5.0,10.0]])
     689
     690        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
     691                        ['density', 'temp','elevation','stage'],
     692                        'test_fit_to_mesh_file failed')
     693
     694        #clean up
     695        os.remove(mesh_file)
     696        os.remove(mesh_output_file)
     697        os.remove(point_file)
     698
     699    def test_fit_to_mesh_file_errors(self):
     700        from load_mesh.loadASCII import import_mesh_file, export_mesh_file
     701        import tempfile
     702        import os
     703
     704        # create a .tsh file, no user outline
     705        mesh_dic = {}
     706        mesh_dic['vertices'] = [[0.0, 0.0],[0.0, 5.0],[5.0, 0.0]]
     707        mesh_dic['triangles'] =  [[0, 2, 1]]
     708        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
     709        mesh_dic['triangle_tags'] = ['']
     710        mesh_dic['vertex_attributes'] = [[1,2], [1,2], [1,2]]
     711        mesh_dic['vertex_attribute_titles'] = ['density', 'temp']
     712        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
     713        mesh_dic['segment_tags'] = ['external', 'external','external']
     714        mesh_file = tempfile.mktemp(".tsh")
     715        export_mesh_file(mesh_file,mesh_dic)
     716
     717        # create an .xya file
     718        point_file = tempfile.mktemp(".xya")
     719        fd = open(point_file,'w')
     720        fd.write("elevation stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
     721        fd.close()
     722
     723        mesh_output_file = "new_triangle.tsh"
     724        try:
     725            fit_to_mesh_file(mesh_file, point_file,
     726                             mesh_output_file, display_errors = False)
     727        except IOError:
     728            pass
     729        else:
     730            #self.failUnless(0 ==1,  'Bad file did not raise error!')
     731            raise 'Bad file did not raise error!'
     732           
     733        #clean up
     734        os.remove(mesh_file)
     735        os.remove(point_file)
     736
     737    def test_fit_to_mesh_file_errorsII(self):
     738        from load_mesh.loadASCII import import_mesh_file, export_mesh_file
     739        import tempfile
     740        import os
     741
     742        # create a .tsh file, no user outline
     743        mesh_file = tempfile.mktemp(".tsh")
     744        fd = open(mesh_file,'w')
     745        fd.write("unit testing a bad .tsh file \n")
     746        fd.close()
     747
     748        # create an .xya file
     749        point_file = tempfile.mktemp(".xya")
     750        fd = open(point_file,'w')
     751        fd.write("elevation, stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
     752        fd.close()
     753
     754        mesh_output_file = "new_triangle.tsh"
     755        try:
     756            fit_to_mesh_file(mesh_file, point_file,
     757                             mesh_output_file, display_errors = False)
     758        except IOError:
     759            pass
     760        else:
     761            raise 'Bad file did not raise error!'
     762           
     763        #clean up
     764        os.remove(mesh_file)
     765        os.remove(point_file)
     766
     767    def test_fit_to_mesh_file_errorsIII(self):
     768        from load_mesh.loadASCII import import_mesh_file, export_mesh_file
     769        import tempfile
     770        import os
     771
     772        # create a .tsh file, no user outline
     773        mesh_dic = {}
     774        mesh_dic['vertices'] = [[0.0, 0.0],[0.0, 5.0],[5.0, 0.0]]
     775        mesh_dic['triangles'] =  [[0, 2, 1]]
     776        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
     777        mesh_dic['triangle_tags'] = ['']
     778        mesh_dic['vertex_attributes'] = [[1,2], [1,2], [1,2]]
     779        mesh_dic['vertex_attribute_titles'] = ['density', 'temp']
     780        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
     781        mesh_dic['segment_tags'] = ['external', 'external','external']
     782        mesh_file = tempfile.mktemp(".tsh")
     783        export_mesh_file(mesh_file,mesh_dic)
     784
     785        # create an .xya file
     786        point_file = tempfile.mktemp(".xya")
     787        fd = open(point_file,'w')
     788        fd.write("elevation, stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
     789        fd.close()
     790
     791        #This a deliberately illegal filename to invoke the error.
     792        mesh_output_file = ".../\z\z:ya.tsh"       
     793
     794        try:
     795            fit_to_mesh_file(mesh_file, point_file,
     796                             mesh_output_file, display_errors = False)
     797        except IOError:
     798            pass
     799        else:
     800            raise 'Bad file did not raise error!'
     801       
     802        #clean up
     803        os.remove(mesh_file)
     804        os.remove(point_file)
    490805
    491806#-------------------------------------------------------------
Note: See TracChangeset for help on using the changeset viewer.