source: anuga_core/source/anuga/fit_interpolate/test_fit.py @ 5571

Last change on this file since 5571 was 5349, checked in by duncan, 16 years ago

Minor fixes/ comments

File size: 33.3 KB
Line 
1#!/usr/bin/env python
2
3"""
4Note, fitting/blocking is also tested in
5test_quantity.test_set_values_from_UTM_pts.
6"""
7
8#TEST
9import sys
10import unittest
11from math import sqrt
12import tempfile
13import os
14from Numeric import zeros, take, compress, Float, Int, dot, concatenate, \
15     ArrayType, allclose, array
16
17from fit import *
18from anuga.abstract_2d_finite_volumes.neighbour_mesh import Mesh
19from anuga.utilities.sparse import Sparse, Sparse_CSR
20from anuga.coordinate_transforms.geo_reference import Geo_reference
21from anuga.utilities.numerical_tools import ensure_numeric
22from anuga.geospatial_data.geospatial_data import Geospatial_data
23from anuga.shallow_water import Domain
24
25def distance(x, y):
26    return sqrt( sum( (array(x)-array(y))**2 ))
27
28def linear_function(point):
29    point = array(point)
30    return point[:,0]+point[:,1]
31
32
33class Test_Fit(unittest.TestCase):
34
35    def setUp(self):
36        pass
37
38    def tearDown(self):
39        pass
40
41
42    def test_smooth_attributes_to_mesh(self):
43        a = [0.0, 0.0]
44        b = [0.0, 5.0]
45        c = [5.0, 0.0]
46        points = [a, b, c]
47        triangles = [ [1,0,2] ]   #bac
48
49        d1 = [1.0, 1.0]
50        d2 = [1.0, 3.0]
51        d3 = [3.0,1.0]
52        z1 = 2
53        z2 = 4
54        z3 = 4
55        data_coords = [d1, d2, d3]
56
57        z = [z1, z2, z3]
58        fit = Fit(points, triangles, alpha=0)
59        #print "interp.get_A()", interp.get_A()
60        fit._build_matrix_AtA_Atz(ensure_numeric(data_coords),
61                                  ensure_numeric(z))
62        #print "Atz - from fit", fit.Atz
63        #print "AtA - from fit", fit.AtA.todense()
64        #print "z",z
65
66        assert allclose(fit.Atz, [2.8, 3.6, 3.6], atol=1e-7)
67
68        f = fit.fit()
69       
70        answer = [0, 5., 5.]
71
72        #print "f\n",f
73        #print "answer\n",answer
74
75        assert allclose(f, answer, atol=1e-7)
76
77    def test_smooth_att_to_meshII(self):
78
79        a = [0.0, 0.0]
80        b = [0.0, 5.0]
81        c = [5.0, 0.0]
82        points = [a, b, c]
83        triangles = [ [1,0,2] ]   #bac
84
85        d1 = [1.0, 1.0]
86        d2 = [1.0, 2.0]
87        d3 = [3.0,1.0]
88        data_coords = [d1, d2, d3]
89        z = linear_function(data_coords)
90        #print "z",z
91
92        interp = Fit(points, triangles, alpha=0.0)
93        f = interp.fit(data_coords, z)
94        answer = linear_function(points)
95        #print "f\n",f
96        #print "answer\n",answer
97
98        assert allclose(f, answer)
99
100    def test_smooth_attributes_to_meshIII(self):
101
102        a = [-1.0, 0.0]
103        b = [3.0, 4.0]
104        c = [4.0,1.0]
105        d = [-3.0, 2.0] #3
106        e = [-1.0,-2.0]
107        f = [1.0, -2.0] #5
108
109        vertices = [a, b, c, d,e,f]
110        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
111
112        point_coords = [[-2.0, 2.0],
113                        [-1.0, 1.0],
114                        [0.0,2.0],
115                        [1.0, 1.0],
116                        [2.0, 1.0],
117                        [0.0,0.0],
118                        [1.0, 0.0],
119                        [0.0, -1.0],
120                        [-0.2,-0.5],
121                        [-0.9, -1.5],
122                        [0.5, -1.9],
123                        [3.0,1.0]]
124
125        z = linear_function(point_coords)
126        interp = Fit(vertices, triangles,
127                                alpha=0.0)
128
129        #print 'z',z
130        f = interp.fit(point_coords,z)
131        answer = linear_function(vertices)
132        #print "f\n",f
133        #print "answer\n",answer
134        assert allclose(f, answer)
135
136   
137    def test_smooth_attributes_to_meshIV(self):
138        # Testing 2 attributes smoothed to the mesh
139       
140
141        a = [0.0, 0.0]
142        b = [0.0, 5.0]
143        c = [5.0, 0.0]
144        points = [a, b, c]
145        triangles = [ [1,0,2] ]   #bac
146
147        d1 = [1.0, 1.0]
148        d2 = [1.0, 3.0]
149        d3 = [3.0, 1.0]
150        z1 = [2, 4]
151        z2 = [4, 8]
152        z3 = [4, 8]
153        data_coords = [d1, d2, d3]
154
155        z = [z1, z2, z3]
156        fit = Fit(points, triangles, alpha=0)
157       
158        f =  fit.fit(data_coords,z)
159        answer = [[0,0], [5., 10.], [5., 10.]]
160        assert allclose(f, answer)
161
162    def test_smooth_attributes_to_mesh_build_fit_subset(self):
163
164        a = [-1.0, 0.0]
165        b = [3.0, 4.0]
166        c = [4.0,1.0]
167        d = [-3.0, 2.0] #3
168        e = [-1.0,-2.0]
169        f = [1.0, -2.0] #5
170
171        vertices = [a, b, c, d,e,f]
172        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
173
174        interp = Fit(vertices, triangles,
175                                alpha=0.0)
176
177        point_coords = [[-2.0, 2.0],
178                        [-1.0, 1.0],
179                        [0.0,2.0],
180                        [1.0, 1.0],
181                       ]
182
183        z = linear_function(point_coords)
184
185        f = interp.build_fit_subset(point_coords,z)
186       
187        point_coords = [
188                        [2.0, 1.0],
189                        [0.0,0.0],
190                        [1.0, 0.0],
191                        [0.0, -1.0],
192                        [-0.2,-0.5],
193                        [-0.9, -1.5],
194                        [0.5, -1.9],
195                        [3.0,1.0]]
196       
197        z = linear_function(point_coords)
198
199        f = interp.build_fit_subset(point_coords,z)
200       
201        #print 'z',z
202        f = interp.fit()
203        answer = linear_function(vertices)
204        #print "f\n",f
205        #print "answer\n",answer
206        assert allclose(f, answer)
207
208        # test fit 2 mesh as well.
209    def test_fit_file_blocking(self):
210
211        a = [-1.0, 0.0]
212        b = [3.0, 4.0]
213        c = [4.0,1.0]
214        d = [-3.0, 2.0] #3
215        e = [-1.0,-2.0]
216        f = [1.0, -2.0] #5
217
218        vertices = [a, b, c, d,e,f]
219        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
220
221        interp = Fit(vertices, triangles,
222                     alpha=0.0)
223
224
225        fileName = tempfile.mktemp(".ddd")
226        file = open(fileName,"w")
227        file.write(" x,y, elevation \n\
228-2.0, 2.0, 0.\n\
229-1.0, 1.0, 0.\n\
2300.0, 2.0 , 2.\n\
2311.0, 1.0 , 2.\n\
232 2.0,  1.0 ,3. \n\
233 0.0,  0.0 , 0.\n\
234 1.0,  0.0 , 1.\n\
235 0.0,  -1.0, -1.\n\
236 -0.2, -0.5, -0.7\n\
237 -0.9, -1.5, -2.4\n\
238 0.5,  -1.9, -1.4\n\
239 3.0,  1.0 , 4.\n")
240        file.close()
241       
242        f = interp.fit(fileName, max_read_lines=2)
243        answer = linear_function(vertices)
244        #print "f\n",f
245        #print "answer\n",answer
246        assert allclose(f, answer)
247        os.remove(fileName)
248
249    def test_fit_to_mesh_UTM_file(self):
250        #Get (enough) datapoints
251        data_points = [[-21.5, 114.5],[-21.4, 114.6],[-21.45,114.65],
252                       [-21.35, 114.65],[-21.45, 114.55],[-21.45,114.6]]
253
254        data_geo_spatial = Geospatial_data(data_points,
255                                           points_are_lats_longs=True)
256        points_UTM = data_geo_spatial.get_data_points(absolute=True)
257        attributes = linear_function(points_UTM)
258        att = 'elevation'
259       
260        #Create .txt file
261        txt_file = tempfile.mktemp(".txt")
262        file = open(txt_file,"w")
263        file.write(" x,y," + att + " \n")
264        for data_point, attribute in map(None, points_UTM, attributes):
265            row = str(data_point[0]) + ',' + str(data_point[1]) \
266                  + ',' + str(attribute)
267            #print "row", row
268            file.write(row + "\n")
269        file.close()
270
271        # setting up the mesh
272        a = [240000, 7620000]
273        b = [240000, 7680000]
274        c = [300000, 7620000]
275        points = [a, b, c]
276        elements = [[0,2,1]]
277        f = fit_to_mesh(txt_file, points, elements, 
278                        alpha=0.0, max_read_lines=2)
279        answer = linear_function(points)
280        #print "f",f
281        #print "answer",answer
282        assert allclose(f, answer)
283
284        # Delete file!
285        os.remove(txt_file)
286       
287    def cache_test_fit_to_mesh_pts(self):
288        a = [-1.0, 0.0]
289        b = [3.0, 4.0]
290        c = [4.0,1.0]
291        d = [-3.0, 2.0] #3
292        e = [-1.0,-2.0]
293        f = [1.0, -2.0] #5
294
295        vertices = [a, b, c, d,e,f]
296        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
297
298
299        fileName = tempfile.mktemp(".txt")
300        file = open(fileName,"w")
301        file.write(" x, y, elevation \n\
302-2.0, 2.0, 0.\n\
303-1.0, 1.0, 0.\n\
3040.0, 2.0 , 2.\n\
3051.0, 1.0 , 2.\n\
306 2.0,  1.0 ,3. \n\
307 0.0,  0.0 , 0.\n\
308 1.0,  0.0 , 1.\n\
309 0.0,  -1.0, -1.\n\
310 -0.2, -0.5, -0.7\n\
311 -0.9, -1.5, -2.4\n\
312 0.5,  -1.9, -1.4\n\
313 3.0,  1.0 , 4.\n")
314        file.close()
315        geo = Geospatial_data(fileName)
316        fileName_pts = tempfile.mktemp(".pts")
317        points = geo.get_data_points(absolute=True)
318        atts = geo.get_attributes()
319        f = fit_to_mesh(points,atts, vertices, triangles,
320                                alpha=0.0, max_read_lines=2,
321                        use_cache=True, verbose=True)
322        answer = linear_function(vertices)
323        #print "f\n",f
324        #print "answer\n",answer
325        assert allclose(f, answer)
326        os.remove(fileName)
327       
328    def test_fit_to_mesh_pts(self):
329        a = [-1.0, 0.0]
330        b = [3.0, 4.0]
331        c = [4.0,1.0]
332        d = [-3.0, 2.0] #3
333        e = [-1.0,-2.0]
334        f = [1.0, -2.0] #5
335
336        vertices = [a, b, c, d,e,f]
337        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
338
339
340        fileName = tempfile.mktemp(".txt")
341        file = open(fileName,"w")
342        file.write(" x, y, elevation \n\
343-2.0, 2.0, 0.\n\
344-1.0, 1.0, 0.\n\
3450.0, 2.0 , 2.\n\
3461.0, 1.0 , 2.\n\
347 2.0,  1.0 ,3. \n\
348 0.0,  0.0 , 0.\n\
349 1.0,  0.0 , 1.\n\
350 0.0,  -1.0, -1.\n\
351 -0.2, -0.5, -0.7\n\
352 -0.9, -1.5, -2.4\n\
353 0.5,  -1.9, -1.4\n\
354 3.0,  1.0 , 4.\n")
355        file.close()
356        geo = Geospatial_data(fileName)
357        fileName_pts = tempfile.mktemp(".pts")
358        geo.export_points_file(fileName_pts)
359        f = fit_to_mesh(fileName_pts, vertices, triangles,
360                                alpha=0.0, max_read_lines=2)
361        answer = linear_function(vertices)
362        #print "f\n",f
363        #print "answer\n",answer
364        assert allclose(f, answer)
365        os.remove(fileName)
366        os.remove(fileName_pts)
367       
368    def test_fit_to_mesh_pts_passing_mesh_in(self):
369        a = [-1.0, 0.0]
370        b = [3.0, 4.0]
371        c = [4.0,1.0]
372        d = [-3.0, 2.0] #3
373        e = [-1.0,-2.0]
374        f = [1.0, -2.0] #5
375
376        vertices = [a, b, c, d,e,f]
377        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
378
379
380        fileName = tempfile.mktemp(".txt")
381        file = open(fileName,"w")
382        file.write(" x, y, elevation \n\
383-2.0, 2.0, 0.\n\
384-1.0, 1.0, 0.\n\
3850.0, 2.0 , 2.\n\
3861.0, 1.0 , 2.\n\
387 2.0,  1.0 ,3. \n\
388 0.0,  0.0 , 0.\n\
389 1.0,  0.0 , 1.\n\
390 0.0,  -1.0, -1.\n\
391 -0.2, -0.5, -0.7\n\
392 -0.9, -1.5, -2.4\n\
393 0.5,  -1.9, -1.4\n\
394 3.0,  1.0 , 4.\n")
395        file.close()
396        geo = Geospatial_data(fileName)
397        fileName_pts = tempfile.mktemp(".pts")
398        geo.export_points_file(fileName_pts)
399        f = fit_to_mesh(fileName_pts, vertices, triangles,
400                                alpha=0.0, max_read_lines=2)
401        answer = linear_function(vertices)
402        #print "f\n",f
403        #print "answer\n",answer
404        assert allclose(f, answer)
405        os.remove(fileName)
406        os.remove(fileName_pts)
407       
408    def test_fit_to_mesh(self):
409
410        a = [-1.0, 0.0]
411        b = [3.0, 4.0]
412        c = [4.0,1.0]
413        d = [-3.0, 2.0] #3
414        e = [-1.0,-2.0]
415        f = [1.0, -2.0] #5
416
417        vertices = [a, b, c, d,e,f]
418        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
419
420
421        fileName = tempfile.mktemp(".ddd")
422        file = open(fileName,"w")
423        file.write(" x,y, elevation \n\
424-2.0, 2.0, 0.\n\
425-1.0, 1.0, 0.\n\
4260.0, 2.0 , 2.\n\
4271.0, 1.0 , 2.\n\
428 2.0,  1.0 ,3. \n\
429 0.0,  0.0 , 0.\n\
430 1.0,  0.0 , 1.\n\
431 0.0,  -1.0, -1.\n\
432 -0.2, -0.5, -0.7\n\
433 -0.9, -1.5, -2.4\n\
434 0.5,  -1.9, -1.4\n\
435 3.0,  1.0 , 4.\n")
436        file.close()
437       
438        f = fit_to_mesh(fileName, vertices, triangles,
439                                alpha=0.0, max_read_lines=2)
440                        #use_cache=True, verbose=True)
441        answer = linear_function(vertices)
442        #print "f\n",f
443        #print "answer\n",answer
444        assert allclose(f, answer)
445   
446        os.remove(fileName)
447       
448    def test_fit_to_mesh_2_atts(self):
449
450        a = [-1.0, 0.0]
451        b = [3.0, 4.0]
452        c = [4.0,1.0]
453        d = [-3.0, 2.0] #3
454        e = [-1.0,-2.0]
455        f = [1.0, -2.0] #5
456
457        vertices = [a, b, c, d,e,f]
458        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
459
460
461        fileName = tempfile.mktemp(".ddd")
462        file = open(fileName,"w")
463        # the 2nd att name is wacky so it's the first key off a hash table
464        file.write(" x,y, elevation, afriqction \n\
465-2.0, 2.0, 0., 0.\n\
466-1.0, 1.0, 0., 0.\n\
4670.0, 2.0 , 2., 20.\n\
4681.0, 1.0 , 2., 20.\n\
469 2.0,  1.0 ,3., 30. \n\
470 0.0,  0.0 , 0., 0.\n\
471 1.0,  0.0 , 1., 10.\n\
472 0.0,  -1.0, -1., -10.\n\
473 -0.2, -0.5, -0.7, -7.\n\
474 -0.9, -1.5, -2.4, -24. \n\
475 0.5,  -1.9, -1.4, -14. \n\
476 3.0,  1.0 , 4., 40. \n")
477        file.close()
478       
479        f = fit_to_mesh(fileName, vertices, triangles,
480                        alpha=0.0, 
481                        attribute_name='elevation', max_read_lines=2)
482        answer = linear_function(vertices)
483        #print "f\n",f
484        #print "answer\n",answer
485        assert allclose(f, answer)
486        os.remove(fileName)
487       
488    def test_fit_and_interpolation(self):
489
490        a = [0.0, 0.0]
491        b = [0.0, 2.0]
492        c = [2.0, 0.0]
493        d = [0.0, 4.0]
494        e = [2.0, 2.0]
495        f = [4.0, 0.0]
496
497        points = [a, b, c, d, e, f]
498        #bac, bce, ecf, dbe, daf, dae
499        triangles = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
500
501        #Get (enough) datapoints
502        data_points = [[ 0.66666667, 0.66666667],
503                       [ 1.33333333, 1.33333333],
504                       [ 2.66666667, 0.66666667],
505                       [ 0.66666667, 2.66666667],
506                       [ 0.0, 1.0],
507                       [ 0.0, 3.0],
508                       [ 1.0, 0.0],
509                       [ 1.0, 1.0],
510                       [ 1.0, 2.0],
511                       [ 1.0, 3.0],
512                       [ 2.0, 1.0],
513                       [ 3.0, 0.0],
514                       [ 3.0, 1.0]]
515
516        z = linear_function(data_points)
517        interp = Fit(points, triangles,
518                                alpha=0.0)
519
520        answer = linear_function(points)
521
522        f = interp.fit(data_points, z)
523
524        #print "f",f
525        #print "answer",answer
526        assert allclose(f, answer)
527
528       
529    def test_smoothing_and_interpolation(self):
530
531        a = [0.0, 0.0]
532        b = [0.0, 2.0]
533        c = [2.0, 0.0]
534        d = [0.0, 4.0]
535        e = [2.0, 2.0]
536        f = [4.0, 0.0]
537
538        points = [a, b, c, d, e, f]
539        #bac, bce, ecf, dbe, daf, dae
540        triangles = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
541
542        #Get (too few!) datapoints
543        data_points = [[ 0.66666667, 0.66666667],
544                       [ 1.33333333, 1.33333333],
545                       [ 2.66666667, 0.66666667],
546                       [ 0.66666667, 2.66666667]]
547
548        z = linear_function(data_points)
549        answer = linear_function(points)
550
551        #Make interpolator with too few data points and no smoothing
552        interp = Fit(points, triangles, alpha=0.0)
553        #Must raise an exception
554        try:
555            f = interp.fit(data_points,z)
556        except TooFewPointsError:
557            pass
558
559        #Now try with smoothing parameter
560        interp = Fit(points, triangles, alpha=1.0e-13)
561
562        f = interp.fit(data_points,z)
563        #f will be different from answer due to smoothing
564        assert allclose(f, answer,atol=5)
565
566
567    #Tests of smoothing matrix
568    def test_smoothing_matrix_one_triangle(self):
569        from Numeric import dot
570        a = [0.0, 0.0]
571        b = [0.0, 2.0]
572        c = [2.0,0.0]
573        points = [a, b, c]
574
575        vertices = [ [1,0,2] ]   #bac
576
577        interp = Fit(points, vertices)
578
579        assert allclose(interp.get_D(), [[1, -0.5, -0.5],
580                                   [-0.5, 0.5, 0],
581                                   [-0.5, 0, 0.5]])
582
583        #Define f(x,y) = x
584        f = array([0,0,2]) #Value at global vertex 2
585
586        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
587        #           int 1 dx dy = area = 2
588        assert dot(dot(f, interp.get_D()), f) == 2
589
590        #Define f(x,y) = y
591        f = array([0,2,0])  #Value at global vertex 1
592
593        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
594        #           int 1 dx dy = area = 2
595        assert dot(dot(f, interp.get_D()), f) == 2
596
597        #Define f(x,y) = x+y
598        f = array([0,2,2])  #Values at global vertex 1 and 2
599
600        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
601        #           int 2 dx dy = 2*area = 4
602        assert dot(dot(f, interp.get_D()), f) == 4
603
604
605    def test_smoothing_matrix_more_triangles(self):
606        from Numeric import dot
607
608        a = [0.0, 0.0]
609        b = [0.0, 2.0]
610        c = [2.0,0.0]
611        d = [0.0, 4.0]
612        e = [2.0, 2.0]
613        f = [4.0,0.0]
614
615        points = [a, b, c, d, e, f]
616        #bac, bce, ecf, dbe, daf, dae
617        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
618
619        interp = Fit(points, vertices)
620
621
622        #assert allclose(interp.get_D(), [[1, -0.5, -0.5],
623        #                           [-0.5, 0.5, 0],
624        #                           [-0.5, 0, 0.5]])
625
626        #Define f(x,y) = x
627        f = array([0,0,2,0,2,4]) #f evaluated at points a-f
628
629        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
630        #           int 1 dx dy = total area = 8
631        assert dot(dot(f, interp.get_D()), f) == 8
632
633        #Define f(x,y) = y
634        f = array([0,2,0,4,2,0]) #f evaluated at points a-f
635
636        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
637        #           int 1 dx dy = area = 8
638        assert dot(dot(f, interp.get_D()), f) == 8
639
640        #Define f(x,y) = x+y
641        f = array([0,2,2,4,4,4])  #f evaluated at points a-f
642
643        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
644        #           int 2 dx dy = 2*area = 16
645        assert dot(dot(f, interp.get_D()), f) == 16
646
647
648
649    def test_fit_and_interpolation_with_different_origins(self):
650        """Fit a surface to one set of points. Then interpolate that surface
651        using another set of points.
652        This test tests situtaion where points and mesh belong to a different
653        coordinate system as defined by origin.
654        """
655
656        #Setup mesh used to represent fitted function
657        a = [0.0, 0.0]
658        b = [0.0, 2.0]
659        c = [2.0, 0.0]
660        d = [0.0, 4.0]
661        e = [2.0, 2.0]
662        f = [4.0, 0.0]
663
664        points = [a, b, c, d, e, f]
665        #bac, bce, ecf, dbe, daf, dae
666        triangles = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
667
668        #Datapoints to fit from
669        data_points1 = [[ 0.66666667, 0.66666667],
670                        [ 1.33333333, 1.33333333],
671                        [ 2.66666667, 0.66666667],
672                        [ 0.66666667, 2.66666667],
673                        [ 0.0, 1.0],
674                        [ 0.0, 3.0],
675                        [ 1.0, 0.0],
676                        [ 1.0, 1.0],
677                        [ 1.0, 2.0],
678                        [ 1.0, 3.0],
679                        [ 2.0, 1.0],
680                        [ 3.0, 0.0],
681                        [ 3.0, 1.0]]
682
683
684        #First check that things are OK when using same origin
685        mesh_origin = (56, 290000, 618000) #zone, easting, northing
686        data_origin = (56, 290000, 618000) #zone, easting, northing
687
688
689        #Fit surface to mesh
690        interp = Fit(points, triangles, 
691                               alpha=0.0,
692                               mesh_origin = mesh_origin)
693
694        data_geo_spatial = Geospatial_data(data_points1,
695                         geo_reference = Geo_reference(56, 290000, 618000))
696        z = linear_function(data_points1) #Example z-values
697        f = interp.fit(data_geo_spatial, z)   #Fitted values at vertices
698
699        #Shift datapoints according to new origins
700        for k in range(len(data_points1)):
701            data_points1[k][0] += mesh_origin[1] - data_origin[1]
702            data_points1[k][1] += mesh_origin[2] - data_origin[2]
703
704
705
706        #Fit surface to mesh
707        interp = Fit(points, triangles, alpha=0.0)
708        #Fitted values at vertices (using same z as before)
709        f1 = interp.fit(data_points1,z) 
710
711        assert allclose(f,f1), 'Fit should have been unaltered'
712
713
714    def test_smooth_attributes_to_mesh_function(self):
715        #Testing 2 attributes smoothed to the mesh
716       
717
718        a = [0.0, 0.0]
719        b = [0.0, 5.0]
720        c = [5.0, 0.0]
721        points = [a, b, c]
722        triangles = [ [1,0,2] ]   #bac
723
724        d1 = [1.0, 1.0]
725        d2 = [1.0, 3.0]
726        d3 = [3.0, 1.0]
727        z1 = [2, 4]
728        z2 = [4, 8]
729        z3 = [4, 8]
730        data_coords = [d1, d2, d3]
731        z = [z1, z2, z3]
732
733        f = fit_to_mesh(data_coords, vertex_coordinates=points,
734                        triangles=triangles,
735                        point_attributes=z, alpha=0.0)
736        answer = [[0, 0], [5., 10.], [5., 10.]]
737
738        assert allclose(f, answer)
739
740    def test_fit_to_mesh_w_georef(self):
741        """Simple check that georef works at the fit_to_mesh level
742        """
743       
744        from anuga.coordinate_transforms.geo_reference import Geo_reference
745
746        #Mesh
747        vertex_coordinates = [[0.76, 0.76],
748                              [0.76, 5.76],
749                              [5.76, 0.76]]
750        triangles = [[0,2,1]]
751
752        mesh_geo = Geo_reference(56,-0.76,-0.76)
753        #print "mesh_geo.get_absolute(vertex_coordinates)", \
754         #     mesh_geo.get_absolute(vertex_coordinates)
755
756        #Data                       
757        data_points = [[ 201.0, 401.0],
758                       [ 201.0, 403.0],
759                       [ 203.0, 401.0]]
760
761        z = [2, 4, 4]
762       
763        data_geo = Geo_reference(56,-200,-400)
764
765        #print "data_geo.get_absolute(data_points)", \
766        #      data_geo.get_absolute(data_points)
767       
768        #Fit
769        zz = fit_to_mesh(data_points, vertex_coordinates=vertex_coordinates,
770                         triangles=triangles,
771                         point_attributes=z,
772                         data_origin = data_geo.get_origin(),
773                         mesh_origin = mesh_geo.get_origin(),
774                         alpha = 0)
775        assert allclose( zz, [0,5,5] )
776
777
778    def test_fit_to_mesh_file2domain(self):
779        from load_mesh.loadASCII import import_mesh_file, \
780             export_mesh_file
781        import tempfile
782        import os
783
784        # create a .tsh file, no user outline
785        mesh_dic = {}
786        mesh_dic['vertices'] = [[0.0, 0.0],
787                                          [0.0, 5.0],
788                                          [5.0, 0.0]]
789        mesh_dic['triangles'] =  [[0, 2, 1]]
790        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
791        mesh_dic['triangle_tags'] = ['']
792        mesh_dic['vertex_attributes'] = [[], [], []]
793        mesh_dic['vertiex_attribute_titles'] = []
794        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
795        mesh_dic['segment_tags'] = ['external',
796                                                  'external',
797                                                  'external']
798        mesh_file = tempfile.mktemp(".tsh")
799        export_mesh_file(mesh_file,mesh_dic)
800
801        # create a points .csv file
802        point_file = tempfile.mktemp(".csv")
803        fd = open(point_file,'w')
804        fd.write("x,y, elevation, stage \n\
805        1.0, 1.0,2.,4 \n\
806        1.0, 3.0,4,8 \n\
807        3.0,1.0,4.,8 \n")
808        fd.close()
809
810        mesh_output_file = tempfile.mktemp(".tsh") 
811        fit_to_mesh_file(mesh_file,
812                         point_file,
813                         mesh_output_file,
814                         alpha = 0.0)
815        # load in the .tsh file we just wrote
816        mesh_dic = import_mesh_file(mesh_output_file)
817        #print "mesh_dic",mesh_dic
818        ans =[[0.0, 0.0],
819              [5.0, 10.0],
820              [5.0,10.0]]
821        assert allclose(mesh_dic['vertex_attributes'],ans)
822
823        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
824                        ['elevation','stage'],
825                        'test_fit_to_mesh_file failed')
826        domain = Domain(mesh_output_file, use_cache=True, verbose=False)
827       
828        answer = [0., 5., 5.]
829        assert allclose(domain.quantities['elevation'].vertex_values,
830                        answer)
831        #clean up
832        os.remove(mesh_file)
833        os.remove(point_file)
834        os.remove(mesh_output_file)
835
836    def test_fit_to_mesh_file3(self):
837        from load_mesh.loadASCII import import_mesh_file, \
838             export_mesh_file
839        import tempfile
840        import os
841
842        # create a .tsh file, no user outline
843        mesh_dic = {}
844        mesh_dic['vertices'] = [[0.76, 0.76],
845                                          [0.76, 5.76],
846                                          [5.76, 0.76]]
847        mesh_dic['triangles'] =  [[0, 2, 1]]
848        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
849        mesh_dic['triangle_tags'] = ['']
850        mesh_dic['vertex_attributes'] = [[], [], []]
851        mesh_dic['vertiex_attribute_titles'] = []
852        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
853        mesh_dic['segment_tags'] = ['external',
854                                                  'external',
855                                                  'external']
856        mesh_dic['geo_reference'] = Geo_reference(56,-0.76,-0.76)
857        mesh_file = tempfile.mktemp(".tsh")
858        export_mesh_file(mesh_file,mesh_dic)
859
860        # create a points .csv file
861        point_file = tempfile.mktemp(".csv")
862        fd = open(point_file,'w')
863        fd.write("x,y, elevation, stage \n\
864        1.0, 1.0,2.,4 \n\
865        1.0, 3.0,4,8 \n\
866        3.0,1.0,4.,8 \n")
867        fd.close()
868       
869        mesh_output_file = tempfile.mktemp(".tsh")
870        fit_to_mesh_file(mesh_file,
871                         point_file,
872                         mesh_output_file,
873                         alpha = 0.0)
874        # load in the .tsh file we just wrote
875        mesh_dic = import_mesh_file(mesh_output_file)
876        #print "mesh_dic",mesh_dic
877        ans =[[0.0, 0.0],
878              [5.0, 10.0],
879              [5.0,10.0]]
880        assert allclose(mesh_dic['vertex_attributes'],ans)
881
882        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
883                        ['elevation','stage'],
884                        'test_fit_to_mesh_file failed')
885
886        #clean up
887        os.remove(mesh_file)
888        os.remove(point_file)
889        os.remove(mesh_output_file)
890
891    def test_fit_to_mesh_fileII(self):
892        from load_mesh.loadASCII import import_mesh_file, \
893             export_mesh_file
894        import tempfile
895        import os
896
897        # create a .tsh file, no user outline
898        mesh_dic = {}
899        mesh_dic['vertices'] = [[0.0, 0.0],
900                                [0.0, 5.0],
901                                [5.0, 0.0]]
902        mesh_dic['triangles'] =  [[0, 2, 1]]
903        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
904        mesh_dic['triangle_tags'] = ['']
905        mesh_dic['vertex_attributes'] = [[1,2], [1,2], [1,2]]
906        mesh_dic['vertex_attribute_titles'] = ['density', 'temp']
907        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
908        mesh_dic['segment_tags'] = ['external',
909                                                  'external',
910                                                  'external']
911        mesh_file = tempfile.mktemp(".tsh")
912        export_mesh_file(mesh_file,mesh_dic)
913
914        # create a points .csv file
915        point_file = tempfile.mktemp(".csv")
916        fd = open(point_file,'w')
917        fd.write("x,y,elevation, stage \n\
918        1.0, 1.0,2.,4 \n\
919        1.0, 3.0,4,8 \n\
920        3.0,1.0,4.,8 \n")
921        fd.close()
922
923        mesh_output_file = "new_triangle.tsh"
924        fit_to_mesh_file(mesh_file,
925                         point_file,
926                         mesh_output_file,
927                         alpha = 0.0)
928        # load in the .tsh file we just wrote
929        mesh_dic = import_mesh_file(mesh_output_file)
930
931        assert allclose(mesh_dic['vertex_attributes'],
932                        [[1.0, 2.0,0.0, 0.0],
933                         [1.0, 2.0,5.0, 10.0],
934                         [1.0, 2.0,5.0,10.0]])
935
936        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
937                        ['density', 'temp','elevation','stage'],
938                        'test_fit_to_mesh_file failed')
939
940        #clean up
941        os.remove(mesh_file)
942        os.remove(mesh_output_file)
943        os.remove(point_file)
944
945    def test_fit_to_mesh_file_errors(self):
946        from load_mesh.loadASCII import import_mesh_file, export_mesh_file
947        import tempfile
948        import os
949
950        # create a .tsh file, no user outline
951        mesh_dic = {}
952        mesh_dic['vertices'] = [[0.0, 0.0],[0.0, 5.0],[5.0, 0.0]]
953        mesh_dic['triangles'] =  [[0, 2, 1]]
954        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
955        mesh_dic['triangle_tags'] = ['']
956        mesh_dic['vertex_attributes'] = [[1,2], [1,2], [1,2]]
957        mesh_dic['vertex_attribute_titles'] = ['density', 'temp']
958        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
959        mesh_dic['segment_tags'] = ['external', 'external','external']
960        mesh_file = tempfile.mktemp(".tsh")
961        export_mesh_file(mesh_file,mesh_dic)
962
963        # create a bad points .csv file
964        point_file = tempfile.mktemp(".csv")
965        fd = open(point_file,'w')
966        fd.write("x,y,elevation stage \n\
967        1.0, 1.0,2.,4 \n\
968        1.0, 3.0,4,8 \n\
969        3.0,1.0,4.,8 \n")
970        fd.close()
971
972        mesh_output_file = "new_triangle.tsh"
973        try:
974            fit_to_mesh_file(mesh_file, point_file,
975                             mesh_output_file, display_errors = False)
976        except SyntaxError:
977            pass
978        else:
979            #self.failUnless(0 ==1,  'Bad file did not raise error!')
980            raise 'Bad file did not raise error!'
981           
982        #clean up
983        os.remove(mesh_file)
984        os.remove(point_file)
985
986    def test_fit_to_mesh_file_errorsII(self):
987        from load_mesh.loadASCII import import_mesh_file, export_mesh_file
988        import tempfile
989        import os
990
991        # create a .tsh file, no user outline
992        mesh_file = tempfile.mktemp(".tsh")
993        fd = open(mesh_file,'w')
994        fd.write("unit testing a bad .tsh file \n")
995        fd.close()
996
997        # create a points .csv file
998        point_file = tempfile.mktemp(".csv")
999        fd = open(point_file,'w')
1000        fd.write("x,y,elevation, stage \n\
1001        1.0, 1.0,2.,4 \n\
1002        1.0, 3.0,4,8 \n\
1003        3.0,1.0,4.,8 \n")
1004        fd.close()
1005
1006        mesh_output_file = "new_triangle.tsh"
1007        try:
1008            fit_to_mesh_file(mesh_file, point_file,
1009                             mesh_output_file, display_errors = False)
1010        except IOError:
1011            pass
1012        else:
1013            raise 'Bad file did not raise error!'
1014           
1015        #clean up
1016        os.remove(mesh_file)
1017        os.remove(point_file)
1018
1019    def test_fit_to_mesh_file_errorsIII(self):
1020        from load_mesh.loadASCII import import_mesh_file, export_mesh_file
1021        import tempfile
1022        import os
1023
1024        # create a .tsh file, no user outline
1025        mesh_dic = {}
1026        mesh_dic['vertices'] = [[0.0, 0.0],[0.0, 5.0],[5.0, 0.0]]
1027        mesh_dic['triangles'] =  [[0, 2, 1]]
1028        mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]]
1029        mesh_dic['triangle_tags'] = ['']
1030        mesh_dic['vertex_attributes'] = [[1,2], [1,2], [1,2]]
1031        mesh_dic['vertex_attribute_titles'] = ['density', 'temp']
1032        mesh_dic['triangle_neighbors'] = [[-1, -1, -1]]
1033        mesh_dic['segment_tags'] = ['external', 'external','external']
1034        mesh_file = tempfile.mktemp(".tsh")
1035        export_mesh_file(mesh_file,mesh_dic)
1036
1037
1038        # create a points .csv file
1039        point_file = tempfile.mktemp(".csv")
1040        fd = open(point_file,'w')
1041        fd.write("x,y,elevation, stage \n\
1042        1.0, 1.0,2.,4 \n\
1043        1.0, 3.0,4,8 \n\
1044        3.0,1.0,4.,8 \n")
1045        fd.close()
1046
1047        #This a deliberately illegal filename to invoke the error.
1048        mesh_output_file = ".../\z\z:ya.tsh"       
1049
1050        try:
1051            fit_to_mesh_file(mesh_file, point_file,
1052                             mesh_output_file, display_errors = False)
1053        except IOError:
1054            pass
1055        else:
1056            raise 'Bad file did not raise error!'
1057       
1058        #clean up
1059        os.remove(mesh_file)
1060        os.remove(point_file)
1061 
1062    def Not_yet_test_smooth_att_to_mesh_with_excess_verts(self):
1063
1064        a = [0.0, 0.0]
1065        b = [0.0, 5.0]
1066        c = [5.0, 0.0]
1067        d = [1.0, 1.0]
1068        e = [18.0, 1000.0]
1069       
1070        points = [a, b, c, d, e]
1071        triangles = [ [1,0,2] ]   #bac
1072
1073        d1 = [1.0, 1.0]
1074        d2 = [1.0, 2.0]
1075        d3 = [3.0,1.0]
1076        d4 = [2.0,3.0]
1077        d5 = [2.0,2.0]
1078        d6 = [1.0,3.0]
1079        data_coords = [d1, d2, d3, d4, d5, d6]
1080        z = linear_function(data_coords)
1081        #print "z",z
1082
1083        interp = Fit(points, triangles, alpha=0.0)
1084       
1085        try:
1086            f = interp.fit(data_coords, z)
1087        except VertsWithNoTrianglesError:
1088            pass
1089        else:
1090            raise 'Verts with no triangles did not raise error!'
1091       
1092        #f = interp.fit(data_coords, z)
1093        #answer = linear_function(points)
1094
1095        #  Removing the bad verts that we don't care about
1096        #f = f[0:3]
1097        #answer = answer[0:3]
1098        #assert allclose(f, answer)
1099
1100#-------------------------------------------------------------
1101if __name__ == "__main__":
1102    suite = unittest.makeSuite(Test_Fit,'test')
1103    #suite = unittest.makeSuite(Test_Fit,'test_smooth_attributes_to_mesh_function')
1104    #suite = unittest.makeSuite(Test_Fit,'')
1105    runner = unittest.TextTestRunner(verbosity=1)
1106    runner.run(suite)
1107
1108
1109
1110
1111
Note: See TracBrowser for help on using the repository browser.