Changeset 7035 for branches/numpy/anuga
- Timestamp:
- May 14, 2009, 2:24:54 PM (16 years ago)
- Location:
- branches/numpy/anuga
- Files:
-
- 1 deleted
- 26 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/numpy/anuga/abstract_2d_finite_volumes/domain.py
r6904 r7035 18 18 from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\ 19 19 import File_boundary 20 from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\ 21 import AWI_boundary 20 22 from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\ 21 23 import Dirichlet_boundary … … 311 313 def get_normal(self, *args, **kwargs): 312 314 return self.mesh.get_normal(*args, **kwargs) 315 313 316 def get_triangle_containing_point(self, *args, **kwargs): 314 317 return self.mesh.get_triangle_containing_point(*args, **kwargs) -
branches/numpy/anuga/abstract_2d_finite_volumes/generic_boundary_conditions.py
r6904 r7035 399 399 msg += 'vol_id=%s, edge_id=%s' %(str(vol_id), str(edge_id)) 400 400 raise Exception, msg 401 402 class AWI_boundary(Boundary): 403 """The AWI_boundary reads values for the conserved 404 quantities (only STAGE) from an sww NetCDF file, and returns interpolated values 405 at the midpoints of each associated boundary segment. 406 Time dependency is interpolated linearly. 407 408 Assumes that file contains a time series and possibly 409 also spatial info. See docstring for File_function in util.py 410 for details about admissible file formats 411 412 AWI boundary must read and interpolate from *smoothed* version 413 as stored in sww and cannot work with the discontinuos triangles. 414 415 Example: 416 Ba = AWI_boundary('source_file.sww', domain) 417 418 419 Note that the resulting solution history is not exactly the same as if 420 the models were coupled as there is no feedback into the source model. 421 422 This was added by Nils Goseberg et al in April 2009 423 """ 424 425 def __init__(self, filename, domain, time_thinning=1, 426 use_cache=False, verbose=False): 427 import time 428 from anuga.config import time_format 429 from anuga.abstract_2d_finite_volumes.util import file_function 430 431 Boundary.__init__(self) 432 433 # Get x,y vertex coordinates for all triangles 434 V = domain.vertex_coordinates 435 436 # Compute midpoint coordinates for all boundary elements 437 # Only a subset may be invoked when boundary is evaluated but 438 # we don't know which ones at this stage since this object can 439 # be attached to 440 # any tagged boundary later on. 441 442 if verbose: print 'Find midpoint coordinates of entire boundary' 443 self.midpoint_coordinates = num.zeros((len(domain.boundary), 2), num.float) 444 boundary_keys = domain.boundary.keys() 445 446 xllcorner = domain.geo_reference.get_xllcorner() 447 yllcorner = domain.geo_reference.get_yllcorner() 448 449 # Make ordering unique #FIXME: should this happen in domain.py? 450 boundary_keys.sort() 451 452 # Record ordering #FIXME: should this also happen in domain.py? 453 self.boundary_indices = {} 454 for i, (vol_id, edge_id) in enumerate(boundary_keys): 455 base_index = 3*vol_id 456 x0, y0 = V[base_index, :] 457 x1, y1 = V[base_index+1, :] 458 x2, y2 = V[base_index+2, :] 459 460 # Compute midpoints 461 if edge_id == 0: m = num.array([(x1 + x2)/2, (y1 + y2)/2]) 462 if edge_id == 1: m = num.array([(x0 + x2)/2, (y0 + y2)/2]) 463 if edge_id == 2: m = num.array([(x1 + x0)/2, (y1 + y0)/2]) 464 465 # Convert to absolute UTM coordinates 466 m[0] += xllcorner 467 m[1] += yllcorner 468 469 # Register point and index 470 self.midpoint_coordinates[i,:] = m 471 472 # Register index of this boundary edge for use with evaluate 473 self.boundary_indices[(vol_id, edge_id)] = i 474 475 476 if verbose: print 'Initialise file_function' 477 self.F = file_function(filename, domain, 478 interpolation_points=self.midpoint_coordinates, 479 time_thinning=time_thinning, 480 use_cache=use_cache, 481 verbose=verbose) 482 self.domain = domain 483 484 # Test 485 486 # Here we'll flag indices outside the mesh as a warning 487 # as suggested by Joaquim Luis in sourceforge posting 488 # November 2007 489 # We won't make it an error as it is conceivable that 490 # only part of mesh boundary is actually used with a given 491 # file boundary sww file. 492 if hasattr(self.F, 'indices_outside_mesh') and 493 len(self.F.indices_outside_mesh) > 0: 494 msg = 'WARNING: File_boundary has points outside the mesh ' 495 msg += 'given in %s. ' % filename 496 msg += 'See warning message issued by Interpolation_function ' 497 msg += 'for details (should appear above somewhere if ' 498 msg += 'verbose is True).\n' 499 msg += 'This is perfectly OK as long as the points that are ' 500 msg += 'outside aren\'t used on the actual boundary segment.' 501 if verbose is True: 502 print msg 503 #raise Exception(msg) 504 505 q = self.F(0, point_id=0) 506 507 d = len(domain.conserved_quantities) 508 msg = 'Values specified in file %s must be ' % filename 509 msg += 'a list or an array of length %d' % d 510 assert len(q) == d, msg 511 512 513 def __repr__(self): 514 return 'File boundary' 515 516 517 def evaluate(self, vol_id=None, edge_id=None): 518 """Return linearly interpolated values based on domain.time 519 at midpoint of segment defined by vol_id and edge_id. 520 """ 521 522 q = self.domain.get_conserved_quantities(vol_id, edge=edge_id) 523 t = self.domain.time 524 525 if vol_id is not None and edge_id is not None: 526 i = self.boundary_indices[vol_id, edge_id] 527 res = self.F(t, point_id=i) 528 529 if res == NAN: 530 x,y = self.midpoint_coordinates[i,:] 531 msg = 'NAN value found in file_boundary at ' 532 msg += 'point id #%d: (%.2f, %.2f).\n' % (i, x, y) 533 534 if (hasattr(self.F, 'indices_outside_mesh') and 535 len(self.F.indices_outside_mesh) > 0): 536 # Check if NAN point is due it being outside 537 # boundary defined in sww file. 538 539 if i in self.F.indices_outside_mesh: 540 msg += 'This point refers to one outside the ' 541 msg += 'mesh defined by the file %s.\n' % self.F.filename 542 msg += 'Make sure that the file covers ' 543 msg += 'the boundary segment it is assigned to ' 544 msg += 'in set_boundary.' 545 else: 546 msg += 'This point is inside the mesh defined ' 547 msg += 'the file %s.\n' % self.F.filename 548 msg += 'Check this file for NANs.' 549 raise Exception, msg 550 551 q[0] = res[0] # Take stage, leave momentum alone 552 return q 553 #return res 554 else: 555 # raise 'Boundary call without point_id not implemented' 556 # FIXME: What should the semantics be? 557 return self.F(t) 558 559 -
branches/numpy/anuga/abstract_2d_finite_volumes/quantity.py
r6902 r7035 459 459 raise Exception, msg 460 460 461 msg = 'Indices must be a list or None'462 assert (indices is None463 or isinstance(indices, (list, num.ndarray))), msg461 msg = 'Indices must be a list, array or None' 462 #assert (indices is None 463 assert isinstance(indices, (None, list, num.ndarray))), msg 464 464 465 465 # Determine which 'set_values_from_...' to use … … 1187 1187 import types 1188 1188 1189 msg = 'Indices must be a list or None' 1190 assert indices is None or isinstance(indices, (list, num.ndarray)), msg 1189 msg = 'Indices must be a list, array or None' 1190 #assert indices is None or isinstance(indices, (list, num.ndarray)), msg 1191 assert isinstance(indices, (list, None, num.ndarray)), msg 1191 1192 1192 1193 if location == 'centroids': -
branches/numpy/anuga/abstract_2d_finite_volumes/test_domain.py
r6902 r7035 614 614 615 615 sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4]) 616 denom = num.ones(4, num.float) -domain.timestep*sem616 denom = num.ones(4, num.float) - domain.timestep*sem 617 617 618 618 # x = array([1, 2, 3, 4]) + array( [.4,.3,.2,.1] ) -
branches/numpy/anuga/coordinate_transforms/geo_reference.py
r6689 r7035 319 319 """ 320 320 321 is_list = False 322 if type(points) == types.ListType: 323 is_list = True 321 # remember if we got a list 322 is_list = isinstance(points, list) 324 323 325 324 points = ensure_numeric(points, num.float) -
branches/numpy/anuga/culvert_flows/culvert_class.py
r6902 r7035 15 15 16 16 import numpy as num 17 17 from math import sqrt 18 18 19 19 class Below_interval(Exception): pass … … 137 137 manning=None, # Mannings Roughness for Culvert 138 138 sum_loss=None, 139 use_velocity_head=False, 139 use_velocity_head=False, # FIXME(Ole): Get rid of - always True 140 140 use_momentum_jet=False, # FIXME(Ole): Not yet implemented 141 141 label=None, … … 464 464 log_filename = self.log_filename 465 465 466 # Compute stage and energy at the466 # Compute stage, energy and velocity at the 467 467 # enquiry points at each end of the culvert 468 468 openings = self.openings … … 474 474 depth = h = stage-opening.elevation 475 475 476 476 477 # Get velocity 478 xmomentum = dq['xmomentum'].get_values(location='centroids', 479 indices=[idx])[0] 480 ymomentum = dq['xmomentum'].get_values(location='centroids', 481 indices=[idx])[0] 482 483 if h > minimum_allowed_height: 484 u = xmomentum/(h + velocity_protection/h) 485 v = ymomentum/(h + velocity_protection/h) 486 else: 487 u = v = 0.0 488 489 v_squared = u*u + v*v 490 477 491 if self.use_velocity_head is True: 478 xmomentum = dq['xmomentum'].get_values(location='centroids', 479 indices=[idx])[0] 480 ymomentum = dq['xmomentum'].get_values(location='centroids', 481 indices=[idx])[0] 482 483 if h > minimum_allowed_height: 484 u = xmomentum/(h + velocity_protection/h) 485 v = ymomentum/(h + velocity_protection/h) 486 else: 487 u = v = 0.0 488 489 velocity_head = 0.5*(u*u + v*v)/g 492 velocity_head = 0.5*v_squared/g 490 493 else: 491 494 velocity_head = 0.0 … … 495 498 opening.stage = stage 496 499 opening.depth = depth 500 opening.velocity = sqrt(v_squared) 497 501 498 502 … … 583 587 self.culvert_routine(inlet.depth, 584 588 outlet.depth, 589 inlet.velocity, 590 outlet.velocity, 585 591 inlet.specific_energy, 586 592 delta_total_energy, -
branches/numpy/anuga/culvert_flows/culvert_routines.py
r6902 r7035 19 19 def boyd_generalised_culvert_model(inlet_depth, 20 20 outlet_depth, 21 inlet_velocity, 22 outlet_velocity, 21 23 inlet_specific_energy, 22 24 delta_total_energy, -
branches/numpy/anuga/culvert_flows/test_culvert_routines.py
r6902 r7035 31 31 inlet_depth=2.0 32 32 outlet_depth=0.0 33 34 inlet_velocity=0.0, 35 outlet_velocity=0.0, 33 36 34 37 culvert_length=4.0 … … 49 52 Q, v, d = boyd_generalised_culvert_model(inlet_depth, 50 53 outlet_depth, 54 inlet_velocity, 55 outlet_velocity, 51 56 inlet_specific_energy, 52 57 delta_total_energy, … … 80 85 outlet_depth=0.0 81 86 87 inlet_velocity=0.0, 88 outlet_velocity=0.0, 89 82 90 culvert_length=4.0 83 91 culvert_width=1.2 … … 97 105 Q, v, d = boyd_generalised_culvert_model(inlet_depth, 98 106 outlet_depth, 107 inlet_velocity, 108 outlet_velocity, 99 109 inlet_specific_energy, 100 110 delta_total_energy, … … 187 197 Q, v, d = boyd_generalised_culvert_model(inlet_depth, 188 198 outlet_depth, 199 inlet_velocity, 200 outlet_velocity, 189 201 inlet_specific_energy, 190 202 delta_total_energy, -
branches/numpy/anuga/fit_interpolate/interpolate.py
r6689 r7035 705 705 imposing a particular order on the output vector. 706 706 vertex_coordinates: mx2 array of coordinates (float) 707 triangles: nx3 array of indices into vertex_coordinates ( Int)707 triangles: nx3 array of indices into vertex_coordinates (int) 708 708 interpolation_points: Nx2 array of coordinates to be interpolated to 709 709 verbose: Level of reporting -
branches/numpy/anuga/geospatial_data/test_geospatial_data.py
r7009 r7035 1530 1530 'Bad zone error!') 1531 1531 1532 # use self.failUnlessRaises(ValueError, Geospatial_data(latitudes=lats)) 1532 1533 try: 1533 1534 results = Geospatial_data(latitudes=lats) -
branches/numpy/anuga/load_mesh/loadASCII.py
r6904 r7035 1101 1101 def take_points(dict, indices_to_keep): 1102 1102 dict = point_atts2array(dict) 1103 # FIXME maybe the points data structure should become a class? 1103 1104 dict['pointlist'] = num.take(dict['pointlist'], indices_to_keep, axis=0) 1104 1105 -
branches/numpy/anuga/load_mesh/test_loadASCII.py
r6904 r7035 260 260 def test_load_bad_no_file_tsh(self): 261 261 fileName = tempfile.mktemp('.tsh') 262 # use self.faileUnlessRaises(IOError, import_mesh_file(fileName)) 262 263 try: 263 264 dict = import_mesh_file(fileName) -
branches/numpy/anuga/mesh_engine/mesh_engine.py
r6304 r7035 60 60 61 61 try: 62 # If int is used, instead ofint32, it fails in Linux62 # If num.int is used, instead of num.int32, it fails in Linux 63 63 segments = ensure_numeric(segments, num.int32) 64 64 -
branches/numpy/anuga/pmesh/mesh.py
r6304 r7035 134 134 self.attributes = [] 135 135 if not attributes is None: 136 self.attributes =attributes136 self.attributes = attributes 137 137 138 138 def setAttributes(self,attributes): -
branches/numpy/anuga/pmesh/test_mesh_interface.py
r6360 r7035 589 589 inner_polygon = [[800,400], [900,500], [800,600]] 590 590 interior_regions = [(inner_polygon, 5)] 591 592 m = create_mesh_from_regions(polygon, 593 boundary_tags, 594 10000000, 595 interior_regions=interior_regions) 591 596 try: 592 597 m = create_mesh_from_regions(polygon, … … 600 605 msg += 'does not cause an Exception to be raised' 601 606 raise Exception, msg 607 608 609 def test_create_mesh_with_segments_out_of_bounds(self): 610 """Test that create_mesh_from_regions fails when a segment is out of bounds. 611 """ 612 613 # These are the absolute values 614 min_x = 10 615 min_y = 88 616 polygon = [[min_x,min_y],[1000,100],[1000,1000],[100,1000]] 617 618 619 boundary_tags = {'walls': [0,1], 'bom':[2,3], 'out': [5]} 620 621 # This one is inside bounding polygon - should pass 622 inner_polygon = [[800,400],[900,500],[800,600]] 623 624 interior_regions = [(inner_polygon, 5)] 625 626 627 try: 628 m = create_mesh_from_regions(polygon, 629 boundary_tags, 630 10000000, 631 interior_regions=interior_regions) 632 except: 633 pass 634 else: 635 msg = 'Tags are listed repeatedly, but create mesh from regions ' 636 msg += 'does not cause an Exception to be raised' 637 raise Exception, msg 638 639 640 602 641 603 642 def test_create_mesh_from_regions_with_duplicate_verts(self): -
branches/numpy/anuga/shallow_water/__init__.py
r6553 r7035 13 13 Dirichlet_discharge_boundary,\ 14 14 Field_boundary,\ 15 Transmissive_stage_zero_momentum_boundary 15 Transmissive_stage_zero_momentum_boundary,\ 16 AWI_boundary 16 17 17 18 -
branches/numpy/anuga/shallow_water/data_manager.py
r7009 r7035 2782 2782 # @param verbose True if this function is to be verbose. 2783 2783 def _convert_dem_from_ascii2netcdf(basename_in, basename_out = None, 2784 verbose = False):2784 verbose = False): 2785 2785 """Read Digital Elevation model from the following ASCII format (.asc) 2786 2786 … … 2920 2920 if verbose and i % ((n+10)/10) == 0: 2921 2921 print 'Processing row %d of %d' % (i, nrows) 2922 2923 if len(fields) != ncols: 2924 msg = 'Wrong number of columns in file "%s" line %d\n' % (basename_in + '.asc', i) 2925 msg += 'I got %d elements, but there should have been %d\n' % (len(fields), ncols) 2926 raise Exception, msg 2927 2922 2928 elevation[i, :] = num.array([float(x) for x in fields]) 2923 2929 … … 5389 5395 5390 5396 if weights is None: 5391 weights = num.ones(numSrc , num.int) #array default#5397 weights = num.ones(numSrc) 5392 5398 5393 5399 if permutation is None: -
branches/numpy/anuga/shallow_water/shallow_water_domain.py
r6689 r7035 95 95 from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\ 96 96 import Transmissive_boundary 97 from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\ 98 import AWI_boundary 99 97 100 from anuga.pmesh.mesh_interface import create_mesh_from_regions 98 101 from anuga.utilities.numerical_tools import gradient, mean, ensure_numeric … … 271 274 # @param minimum_allowed_height 272 275 def set_minimum_allowed_height(self, minimum_allowed_height): 273 """Set the minimum depthrecognised in the numerical scheme.276 """Set minimum depth that will be recognised in the numerical scheme. 274 277 275 278 The minimum allowed depth is in meters. … … 1952 1955 s_vec, phi_vec, const): 1953 1956 """Python version of assigning wind field to update vectors. 1954 A cversion also exists (for speed)1957 A C version also exists (for speed) 1955 1958 """ 1956 1959 … … 2057 2060 2058 2061 # Update area if applicable 2059 self.exchange_area = None2060 2062 if center is not None and radius is not None: 2061 2063 assert len(center) == 2 2062 2064 msg = 'Polygon cannot be specified when center and radius are' 2063 2065 assert polygon is None, msg 2064 2065 self.exchange_area = radius**2*pi2066 2066 2067 2067 # Check that circle center lies within the mesh. -
branches/numpy/anuga/shallow_water/test_all.py
r6410 r7035 79 79 80 80 if __name__ == '__main__': 81 82 81 suite = regressionTest() 83 82 runner = unittest.TextTestRunner() #verbosity=2) -
branches/numpy/anuga/shallow_water/test_data_manager.py
r7009 r7035 4960 4960 4961 4961 ## 7th test 4962 m2d = num.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]] )4962 m2d = num.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]], num.int) #array default# 4963 4963 kmin, kmax, lmin, lmax = data_manager._get_min_max_indexes( 4964 4964 latitudes,longitudes, … … 5019 5019 longitudes = [148,149,150,151] 5020 5020 5021 m2d = num.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]] )5021 m2d = num.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]], num.int) #array default# 5022 5022 5023 5023 # k - lat … … 6043 6043 quantities_init[2].append(-va[i]) # South is negative in MUX 6044 6044 6045 file_handle, base_name = tempfile.mkstemp(" ")6045 file_handle, base_name = tempfile.mkstemp("write_mux2") 6046 6046 os.close(file_handle) 6047 6047 os.remove(base_name) -
branches/numpy/anuga/shallow_water/test_shallow_water_domain.py
r6902 r7035 3302 3302 domain.tight_slope_limiters = 0 3303 3303 domain.distribute_to_vertices_and_edges() 3304 assert num.allclose(L[1], [4.1, 16.1, 20.1]) 3304 assert num.allclose(L[1], [4.1, 16.1, 20.1]) 3305 3305 for i in range(len(L)): 3306 3306 assert num.allclose(volumes[i], num.sum(L[i])/3) 3307 3308 # Allow triangle to be flatter (closer to bed) 3309 domain.tight_slope_limiters = 1 3310 3307 3308 3309 domain.tight_slope_limiters = 1 # Allow triangle to be flatter (closer to bed) 3311 3310 domain.distribute_to_vertices_and_edges() 3312 3311 assert num.allclose(L[1], [4.2386, 16.0604, 20.001]) 3313 3312 for i in range(len(L)): 3314 assert num.allclose(volumes[i], num.sum(L[i])/3) 3313 assert num.allclose(volumes[i], num.sum(L[i])/3) 3314 3315 3315 3316 3316 domain._order_ = 2 3317 3318 domain.tight_slope_limiters = 0 3317 3318 domain.tight_slope_limiters = 0 3319 3319 domain.distribute_to_vertices_and_edges() 3320 3320 assert num.allclose(L[1], [4.1, 16.1, 20.1]) … … 3326 3326 3327 3327 domain.distribute_to_vertices_and_edges() 3328 assert (num.allclose(L[1], [4.23370103, 16.06529897, 20.001]) or 3329 num.allclose(L[1], [4.18944138, 16.10955862, 20.001]) or 3330 num.allclose(L[1], [4.19351461, 16.10548539, 20.001])) 3331 # old limiters 3332 3328 assert num.allclose(L[1], [4.23370103, 16.06529897, 20.001]) or\ 3329 num.allclose(L[1], [4.18944138, 16.10955862, 20.001]) or\ 3330 num.allclose(L[1], [4.19351461, 16.10548539, 20.001]) # old limiters 3331 3333 3332 for i in range(len(L)): 3334 3333 assert num.allclose(volumes[i], num.sum(L[i])/3) 3334 3335 3335 3336 3336 def test_second_order_distribute_real_data(self): … … 6117 6117 6118 6118 msg = "test_tags_to_boundaries failed. Single boundary wasn't added." 6119 self.failUnless( 6120 self.failUnless( 6121 self.failUnless( 6122 self.failUnless( 6119 self.failUnless(domain.boundary[(1, 0)] == '1', msg) 6120 self.failUnless(domain.boundary[(1, 2)] == '2', msg) 6121 self.failUnless(domain.boundary[(0, 1)] == '3', msg) 6122 self.failUnless(domain.boundary[(0, 0)] == 'exterior', msg) 6123 6123 msg = "test_pmesh2Domain Too many boundaries" 6124 self.failUnless( 6124 self.failUnless(len(domain.boundary) == 4, msg) 6125 6125 6126 6126 # FIXME change to use get_xllcorner … … 6179 6179 [ 2.66666667, 0.66666667], 6180 6180 [ 0.66666667, 2.66666667], 6181 [ 0.0, 1.0],6182 [ 0.0, 3.0],6183 [ 1.0, 0.0],6184 [ 1.0, 1.0],6185 [ 1.0, 2.0],6186 [ 1.0, 3.0],6187 [ 2.0, 1.0],6188 [ 3.0, 0.0],6189 [ 3.0, 1.0]]6181 [ 0.0, 1.0], 6182 [ 0.0, 3.0], 6183 [ 1.0, 0.0], 6184 [ 1.0, 1.0], 6185 [ 1.0, 2.0], 6186 [ 1.0, 3.0], 6187 [ 2.0, 1.0], 6188 [ 3.0, 0.0], 6189 [ 3.0, 1.0]] 6190 6190 6191 6191 data_geo_spatial = Geospatial_data(data_points_rel, … … 6201 6201 file = open(ptsfile, "w") 6202 6202 file.write(" x,y," + att + " \n") 6203 for data_point, attribute in map(None, data_points_absolute, attributes):6203 for data_point, attribute in map(None, data_points_absolute, attributes): 6204 6204 row = (str(data_point[0]) + ',' + 6205 6205 str(data_point[1]) + ',' + … … 6548 6548 6549 6549 6550 def Xtest_inflow_using_flowline(self):6550 def test_inflow_using_flowline(self): 6551 6551 """test_inflow_using_flowline 6552 6552 6553 6553 Test the ability of a flowline to match inflow above the flowline by 6554 creating constant inflow onto a circle at the head of a 20m wide by 300m 6555 long plane dipping at various slopes with a perpendicular flowline and 6556 gauge downstream of the inflow and a 45 degree flowlines at 200m 6557 downstream. 6554 creating constant inflow onto a circle at the head of a 20m 6555 wide by 300m long plane dipping at various slopes with a 6556 perpendicular flowline and gauge downstream of the inflow and 6557 a 45 degree flowlines at 200m downstream. 6558 6559 A more substantial version of this test with finer resolution and 6560 including the depth calculation using Manning's equation is 6561 available under the validate_all suite in the directory 6562 anuga_validation/automated_validation_tests/flow_tests. 6558 6563 """ 6559 6564 6560 # FIXME(Ole): Move this and the following test to validate_all.py as6561 # they are rather time consuming6562 6565 6563 verbose = True 6566 verbose = False 6567 6564 6568 6565 6569 #---------------------------------------------------------------------- … … 6581 6585 # Setup computational domain 6582 6586 #---------------------------------------------------------------------- 6583 6584 number_of_inflows = 2 # Number of inflows on top of each other 6585 finaltime = 1000.0 # 6000.0 6586 6587 length = 300. 6587 number_of_inflows = 2 # Number of inflows on top of each other 6588 finaltime = 500 #700.0 # If this is too short, steady state will not be achieved 6589 6590 length = 250. 6588 6591 width = 20. 6589 6592 dx = dy = 5 # Resolution: of grid on both axes … … 6594 6597 len2=width) 6595 6598 6596 for mannings_n in [0.150, 0.07, 0.035]: #[0.012, 0.035, 0.070, 0.150]: 6597 for slope in [1.0/300, 1.0/150, 1.0/75]: 6598 # Loop over a range of bedslopes representing sub to 6599 # super critical flows 6600 if verbose: 6601 print 6602 print 'Slope:', slope, 'Mannings n:', mannings_n 6599 for mannings_n in [0.1, 0.01]: 6600 # Loop over a range of roughnesses 6601 6602 for slope in [1.0/300, 1.0/100]: 6603 # Loop over a range of bedslopes representing 6604 # sub to super critical flows 6605 6606 6603 6607 domain = Domain(points, vertices, boundary) 6604 domain.set_name(' Inflow_flowline_test') # Output name6608 domain.set_name('inflow_flowline_test') # Output name 6605 6609 6606 6610 #-------------------------------------------------------------- … … 6620 6624 6621 6625 #-------------------------------------------------------------- 6622 # Setup boundary conditions6623 #--------------------------------------------------------------6624 6625 Br = Reflective_boundary(domain) # Solid reflective wall6626 # Outflow stage at -0.9m d=0.1m6627 Bo = Dirichlet_boundary([-100, 0, 0])6628 6629 domain.set_boundary({'left': Br, 'right': Bo,6630 'top': Br, 'bottom': Br})6631 6632 #--------------------------------------------------------------6633 6626 # Setup Inflow 6634 6627 #-------------------------------------------------------------- 6635 6628 6636 6629 # Fixed Flowrate onto Area 6637 fixed_inflow = Inflow(domain, center=(10.0, 10.0), 6638 radius=5.00, rate=10.00) 6630 fixed_inflow = Inflow(domain, 6631 center=(10.0, 10.0), 6632 radius=5.00, 6633 rate=10.00) 6639 6634 6640 6635 # Stack this flow … … 6644 6639 ref_flow = fixed_inflow.rate*number_of_inflows 6645 6640 6641 # Compute normal depth on plane using Mannings equation 6642 # v=1/n*(r^2/3)*(s^0.5) or r=(Q*n/(s^0.5*W))^0.6 6643 normal_depth=(ref_flow*mannings_n/(slope**0.5*width))**0.6 6644 if verbose: 6645 print 6646 print 'Slope:', slope, 'Mannings n:', mannings_n 6647 6648 6649 #-------------------------------------------------------------- 6650 # Setup boundary conditions 6651 #-------------------------------------------------------------- 6652 6653 Br = Reflective_boundary(domain) 6654 6655 # Define downstream boundary based on predicted depth 6656 def normal_depth_stage_downstream(t): 6657 return (-slope*length) + normal_depth 6658 6659 Bt = Transmissive_momentum_set_stage_boundary(domain=domain, 6660 function=normal_depth_stage_downstream) 6661 6662 6663 6664 6665 domain.set_boundary({'left': Br, 6666 'right': Bt, 6667 'top': Br, 6668 'bottom': Br}) 6669 6670 6671 6646 6672 #-------------------------------------------------------------- 6647 6673 # Evolve system through time … … 6653 6679 # print domain.timestepping_statistics() 6654 6680 6655 if verbose: 6656 print domain.volumetric_balance_statistics() 6681 # print domain.volumetric_balance_statistics() 6682 6683 6657 6684 #-------------------------------------------------------------- 6658 6685 # Compute flow thru flowlines ds of inflow … … 6682 6709 assert num.allclose(q, ref_flow, rtol=1.0e-2), msg 6683 6710 6684 # Stage recorder (gauge) in middle of plane at 200m 6685 x = 200.0 6686 y = 10.00 6687 w = domain.get_quantity('stage').\ 6688 get_values(interpolation_points=[[x, y]])[0] 6689 z = domain.get_quantity('elevation').\ 6690 get_values(interpolation_points=[[x, y]])[0] 6691 domain_depth = w-z 6692 6693 # Compute normal depth at gauge location using Manning equation 6694 # v=1/n*(r^2/3)*(s^0.5) or r=(Q*n/(s^0.5*W))^0.6 6695 normal_depth = (ref_flow*mannings_n/(slope**0.5*width))**0.6 6696 msg = ('Predicted depth of flow was %f, should have been %f' 6697 % (domain_depth, normal_depth)) 6698 if verbose: 6699 diff = abs(domain_depth-normal_depth) 6700 print ('Depth: ANUGA = %f, Mannings = %f, E=%f' 6701 % (domain_depth, normal_depth, diff/domain_depth)) 6702 assert diff < 0.1 6703 6704 if slope >= 1.0/100: 6705 # Really super critical flow is not as stable. 6706 #assert num.allclose(domain_depth, normal_depth, 6707 # rtol=1.0e-1), msg 6708 pass 6709 else: 6710 pass 6711 #assert num.allclose(domain_depth, normal_depth, 6712 # rtol=1.0e-2), msg 6713 6714 6711 6712 6715 6713 def Xtest_friction_dependent_flow_using_flowline(self): 6716 6714 """test_friction_dependent_flow_using_flowline -
branches/numpy/anuga/utilities/compile.py
r6304 r7035 264 264 % (compiler, FN, I_dirs, python_include, utilities_include_dir, root) 265 265 elif FN == "polygon_ext.c": 266 # gcc 4.3.x screws up inthis file if '-O3' is used266 # gcc 4.3.x is problematic with this file if '-O3' is used 267 267 s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -Wall'\ 268 268 %(compiler, FN, I_dirs, python_include, utilities_include_dir, root) -
branches/numpy/anuga/utilities/log.py
r6902 r7035 24 24 ''' 25 25 26 import sys27 26 import os 28 27 import sys … … 60 59 NOTSET = logging.NOTSET 61 60 62 # getTrue if python version 2.5 or later61 # set new_python to True if python version 2.5 or later 63 62 (version_major, version_minor, _, _, _) = sys.version_info 64 63 new_python = ((version_major == 2 and version_minor >= 5) or version_major > 2) … … 103 102 console.setFormatter(formatter) 104 103 logging.getLogger('').addHandler(console) 104 105 # catch exceptions 106 sys.excepthook = log_exception_hook 105 107 106 108 # tell the world how we are set up … … 122 124 frames = traceback.extract_stack() 123 125 frames.reverse() 124 (_, mod_name) = __name__.rsplit('.', 1) 126 try: 127 (_, mod_name) = __name__.rsplit('.', 1) 128 except ValueError: 129 mod_name = __name__ 125 130 for (fpath, lnum, mname, _) in frames: 126 131 (fname, _) = os.path.basename(fpath).rsplit('.', 1) … … 133 138 logging.log(level, msg) 134 139 140 ## 141 # @brief Hook function to process uncaught exceptions. 142 # @param type 143 # @param value 144 # @param traceback 145 # @note Same interface as sys.excepthook() 146 def log_exception_hook(type, value, tb): 147 msg = ''.join(traceback.format_exception(type, value, tb)) 148 critical(msg) 149 150 135 151 ################################################################################ 136 152 # Shortcut routines to make for simpler user code. … … 176 192 if sys.platform != 'win32': 177 193 _proc_status = '/proc/%d/status' % os.getpid() 178 _scale = {'KB': 1024 .0, 'MB': 1024.0*1024.0, 'GB': 1024.0*1024.0*1024.0,179 'kB': 1024 .0, 'mB': 1024.0*1024.0, 'gB': 1024.0*1024.0*1024.0}194 _scale = {'KB': 1024, 'MB': 1024*1024, 'GB': 1024*1024*1024, 195 'kB': 1024, 'mB': 1024*1024, 'gB': 1024*1024*1024} 180 196 181 197 def _VmB(VmKey): … … 214 230 return _VmB('VmStk:') - since 215 231 216 msg = ('Resource usage: memory=%.1f resident=%.1f stacksize=%.1f'217 % (memory()/_scale[' GB'], resident()/_scale['GB'],218 stacksize()/_scale[' GB']))232 msg = ('Resource usage: memory=%.1fMB resident=%.1fMB stacksize=%.1fMB' 233 % (memory()/_scale['MB'], resident()/_scale['MB'], 234 stacksize()/_scale['MB'])) 219 235 log(level, msg) 220 236 else: 221 pass 237 msg = ('Sorry, no memory statistics for Windows (yet).') 238 log(level, msg) 239 240 241 if __name__ == '__main__': 242 ## critical('Testing exception capturing') 243 def test_it(num=100): 244 if num > 0: 245 test_it(num-1) 246 else: 247 resource_usage() 248 249 import numpy as num 250 251 a = num.zeros((1000,1000), num.float) 252 253 test_it() -
branches/numpy/anuga/utilities/numerical_tools.py
r6462 r7035 83 83 # Compute angle 84 84 p = num.inner(v1, v2) 85 c = num.inner(v1, normal_vector(v2)) # Projection onto normal85 c = num.inner(v1, normal_vector(v2)) # Projection onto normal 86 86 # (negative cross product) 87 87 … … 238 238 def ensure_numeric(A, typecode=None): 239 239 """Ensure that sequence is a numeric array. 240 240 241 Inputs: 241 242 A: Sequence. If A is already a numeric array it will be returned -
branches/numpy/anuga/utilities/system_tools.py
r7024 r7035 11 11 import getpass 12 12 import tarfile 13 import md5 13 try: 14 import hashlib 15 except ImportError: 16 import md5 as hashlib 14 17 15 18 … … 556 559 def get_file_hexdigest(filename, blocksize=1024*1024*10): 557 560 '''Get a hex digest of a file.''' 558 559 m = md5.new() 561 562 if hashlib.__name__ == 'hashlib': 563 m = hashlib.md5() # new - 'hashlib' module 564 else: 565 m = hashlib.new() # old - 'md5' module - remove once py2.4 gone 560 566 fd = open(filename, 'r') 561 567 -
branches/numpy/anuga/utilities/test_polygon.py
r6689 r7035 1505 1505 1506 1506 1507 def zzztest_inside_polygon_main(self):1507 def test_inside_polygon_main(self): 1508 1508 # FIXME (Ole): Why is this disabled? 1509 print "inside",inside1510 print "outside",outside1509 #print "inside",inside 1510 #print "outside",outside 1511 1511 1512 1512 assert not inside_polygon((0.5, 1.5), polygon)
Note: See TracChangeset
for help on using the changeset viewer.