Changeset 6428
- Timestamp:
- Feb 27, 2009, 11:54:09 AM (16 years ago)
- Location:
- branches/numpy/anuga
- Files:
-
- 16 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/numpy/anuga/abstract_2d_finite_volumes/general_mesh.py
r6410 r6428 37 37 triangles = [ [1,0,2], [1,2,3] ] # bac, bce 38 38 39 # Create mesh with two triangles: bac and bce 39 # Create mesh with two triangles: bac and bce 40 40 mesh = Mesh(nodes, triangles) 41 41 … … 56 56 """ 57 57 58 #FIXME: It would be a good idea to use geospatial data as an alternative 59 #input 60 def __init__(self, nodes, triangles, 61 geo_reference=None, 58 # FIXME: It would be a good idea to use geospatial data as an alternative 59 # input 60 def __init__(self, 61 nodes, 62 triangles, 63 geo_reference=None, 62 64 number_of_full_nodes=None, 63 number_of_full_triangles=None, 65 number_of_full_triangles=None, 64 66 verbose=False): 65 67 """Build triangular 2d mesh from nodes and triangle information 66 68 67 69 Input: 68 70 69 71 nodes: x,y coordinates represented as a sequence of 2-tuples or 70 72 a Nx2 numeric array of floats. 71 73 72 74 triangles: sequence of 3-tuples or Mx3 numeric array of 73 75 non-negative integers representing indices into 74 76 the nodes array. 75 77 76 78 georeference (optional): If specified coordinates are 77 79 assumed to be relative to this origin. … … 83 85 In this case it is usefull to specify the number of real (called full) 84 86 nodes and triangles. If omitted they will default to all. 85 86 """ 87 88 if verbose: print 'General_mesh: Building basic mesh structure in ANUGA domain' 87 88 """ 89 90 if verbose: print 'General_mesh: Building basic mesh structure in ANUGA domain' 89 91 90 92 self.triangles = num.array(triangles, num.int) 91 93 self.nodes = num.array(nodes, num.float) 92 94 93 94 # Register number of elements and nodes 95 # Register number of elements and nodes 95 96 self.number_of_triangles = N = self.triangles.shape[0] 96 self.number_of_nodes = self.nodes.shape[0] 97 98 97 self.number_of_nodes = self.nodes.shape[0] 99 98 100 99 if number_of_full_nodes is None: … … 102 101 else: 103 102 assert int(number_of_full_nodes) 104 self.number_of_full_nodes = number_of_full_nodes 105 103 self.number_of_full_nodes = number_of_full_nodes 106 104 107 105 if number_of_full_triangles is None: 108 self.number_of_full_triangles = self.number_of_triangles 106 self.number_of_full_triangles = self.number_of_triangles 109 107 else: 110 assert int(number_of_full_triangles) 108 assert int(number_of_full_triangles) 111 109 self.number_of_full_triangles = number_of_full_triangles 112 113 114 #print self.number_of_full_nodes, self.number_of_nodes115 #print self.number_of_full_triangles, self.number_of_triangles116 117 118 110 119 111 # FIXME: this stores a geo_reference, but when coords are returned 120 112 # This geo_ref is not taken into account! 121 113 if geo_reference is None: 122 self.geo_reference = Geo_reference() #Use defaults114 self.geo_reference = Geo_reference() # Use defaults 123 115 else: 124 116 self.geo_reference = geo_reference 125 117 126 118 # Input checks 127 msg = 'Triangles must an Mx3 numeric array or a sequence of 3-tuples. '128 msg += 'The supplied array has the shape: %s'\129 % str(self.triangles.shape)119 msg = ('Triangles must an Mx3 numeric array or a sequence of 3-tuples. ' 120 'The supplied array has the shape: %s' 121 % str(self.triangles.shape)) 130 122 assert len(self.triangles.shape) == 2, msg 131 123 132 msg = 'Nodes must an Nx2 numeric array or a sequence of 2-tuples' 133 msg += 'The supplied array has the shape: %s'\ 134 %str(self.nodes.shape) 124 msg = ('Nodes must an Nx2 numeric array or a sequence of 2-tuples' 125 'The supplied array has the shape: %s' % str(self.nodes.shape)) 135 126 assert len(self.nodes.shape) == 2, msg 136 127 … … 138 129 assert max(self.triangles.flat) < self.nodes.shape[0], msg 139 130 140 141 131 # FIXME: Maybe move to statistics? 142 132 # Or use with get_extent 143 xy_extent = [ min(self.nodes[:,0]), min(self.nodes[:,1]),144 max(self.nodes[:,0]), max(self.nodes[:,1])]133 xy_extent = [min(self.nodes[:,0]), min(self.nodes[:,1]), 134 max(self.nodes[:,0]), max(self.nodes[:,1])] 145 135 146 136 self.xy_extent = num.array(xy_extent, num.float) 147 148 137 149 138 # Allocate space for geometric quantities … … 155 144 self.vertex_coordinates = V = self.compute_vertex_coordinates() 156 145 157 158 146 # Initialise each triangle 159 147 if verbose: 160 print 'General_mesh: Computing areas, normals and edgeleng hts'161 148 print 'General_mesh: Computing areas, normals and edgelengths' 149 162 150 for i in range(N): 163 if verbose and i % ((N+10)/10) == 0: print '(%d/%d)' % (i, N)164 151 if verbose and i % ((N+10)/10) == 0: print '(%d/%d)' % (i, N) 152 165 153 x0, y0 = V[3*i, :] 166 154 x1, y1 = V[3*i+1, :] 167 x2, y2 = V[3*i+2, :] 155 x2, y2 = V[3*i+2, :] 168 156 169 157 # Area 170 self.areas[i] = abs((x1*y0-x0*y1) +(x2*y1-x1*y2)+(x0*y2-x2*y0))/2171 172 msg = 'Triangle (%f,%f), (%f,%f), (%f, %f)' % (x0,y0,x1,y1,x2,y2)173 msg += ' is degenerate: area == %f' % self.areas[i]158 self.areas[i] = abs((x1*y0-x0*y1) + (x2*y1-x1*y2) + (x0*y2-x2*y0))/2 159 160 msg = 'Triangle (%f,%f), (%f,%f), (%f, %f)' % (x0,y0,x1,y1,x2,y2) 161 msg += ' is degenerate: area == %f' % self.areas[i] 174 162 assert self.areas[i] > 0.0, msg 175 176 163 177 164 # Normals … … 184 171 # the first vertex, etc) 185 172 # - Stored as six floats n0x,n0y,n1x,n1y,n2x,n2y per triangle 186 187 n0 = num.array([x2 - x1, y2 - y1], num.float) 173 n0 = num.array([x2-x1, y2-y1], num.float) 188 174 l0 = num.sqrt(num.sum(n0**2)) 189 175 190 n1 = num.array([x0 - x2, y0 -y2], num.float)176 n1 = num.array([x0-x2, y0-y2], num.float) 191 177 l1 = num.sqrt(num.sum(n1**2)) 192 178 193 n2 = num.array([x1 - x0, y1 -y0], num.float)179 n2 = num.array([x1-x0, y1-y0], num.float) 194 180 l2 = num.sqrt(num.sum(n2**2)) 195 181 … … 207 193 self.edgelengths[i, :] = [l0, l1, l2] 208 194 209 210 195 # Build structure listing which trianglse belong to which node. 211 if verbose: print 'Building inverted triangle structure' 196 if verbose: print 'Building inverted triangle structure' 212 197 self.build_inverted_triangle_structure() 213 214 215 198 216 199 def __len__(self): 217 200 return self.number_of_triangles 218 219 201 220 202 def __repr__(self): 221 return 'Mesh: %d vertices, %d triangles'\222 %(self.nodes.shape[0], len(self))203 return ('Mesh: %d vertices, %d triangles' 204 % (self.nodes.shape[0], len(self))) 223 205 224 206 def get_normals(self): 225 207 """Return all normal vectors. 208 226 209 Return normal vectors for all triangles as an Nx6 array 227 210 (ordered as x0, y0, x1, y1, x2, y2 for each triangle) 228 211 """ 212 229 213 return self.normals 230 231 214 232 215 def get_normal(self, i, j): 233 216 """Return normal vector j of the i'th triangle. 217 234 218 Return value is the numeric array slice [x, y] 235 219 """ 220 236 221 return self.normals[i, 2*j:2*j+2] 237 222 238 223 def get_number_of_nodes(self): 239 224 return self.number_of_nodes 240 225 241 226 def get_nodes(self, absolute=False): 242 227 """Return all nodes in mesh. … … 249 234 are to be made absolute by taking georeference into account 250 235 Default is False as many parts of ANUGA expects relative coordinates. 251 (To see which, switch to default absolute=True and run tests). 236 (To see which, switch to default absolute=True and run tests). 252 237 """ 253 238 … … 257 242 if not self.geo_reference.is_absolute(): 258 243 V = self.geo_reference.get_absolute(V) 259 244 260 245 return V 261 262 def get_node(self, i, 263 absolute=False): 246 247 def get_node(self, i, absolute=False): 264 248 """Return node coordinates for triangle i. 265 249 … … 267 251 are to be made absolute by taking georeference into account 268 252 Default is False as many parts of ANUGA expects relative coordinates. 269 (To see which, switch to default absolute=True and run tests). 270 """ 271 272 253 (To see which, switch to default absolute=True and run tests). 254 """ 255 273 256 V = self.nodes[i,:] 274 257 if absolute is True: 275 258 if not self.geo_reference.is_absolute(): 276 return V + num.array([self.geo_reference.get_xllcorner(), 277 self.geo_reference.get_yllcorner()], num.float) 278 else: 279 return V 280 else: 281 return V 282 283 284 285 def get_vertex_coordinates(self, 286 triangle_id=None, 287 absolute=False): 288 """Return vertex coordinates for all triangles. 289 259 V += num.array([self.geo_reference.get_xllcorner(), 260 self.geo_reference.get_yllcorner()], num.float) 261 return V 262 263 def get_vertex_coordinates(self, triangle_id=None, absolute=False): 264 """Return vertex coordinates for all triangles. 265 290 266 Return all vertex coordinates for all triangles as a 3*M x 2 array 291 267 where the jth vertex of the ith triangle is located in row 3*i+j and … … 294 270 if triangle_id is specified (an integer) the 3 vertex coordinates 295 271 for triangle_id are returned. 296 272 297 273 Boolean keyword argument absolute determines whether coordinates 298 274 are to be made absolute by taking georeference into account 299 275 Default is False as many parts of ANUGA expects relative coordinates. 300 276 """ 301 277 302 278 V = self.vertex_coordinates 303 279 304 if triangle_id is None: 280 if triangle_id is None: 305 281 if absolute is True: 306 282 if not self.geo_reference.is_absolute(): 307 283 V = self.geo_reference.get_absolute(V) 308 309 284 return V 310 285 else: … … 313 288 assert int(i) == i, msg 314 289 assert 0 <= i < self.number_of_triangles 315 316 i3 = 3*i 290 291 i3 = 3*i 317 292 if absolute is True and not self.geo_reference.is_absolute(): 318 293 offset=num.array([self.geo_reference.get_xllcorner(), … … 323 298 else: 324 299 return num.array([V[i3,:], V[i3+1,:], V[i3+2,:]], num.float) 325 326 327 300 328 301 def get_vertex_coordinate(self, i, j, absolute=False): … … 333 306 msg = 'vertex id j must be an integer in [0,1,2]' 334 307 assert j in [0,1,2], msg 335 336 V = self.get_vertex_coordinates(triangle_id=i, 337 absolute=absolute) 308 309 V = self.get_vertex_coordinates(triangle_id=i, absolute=absolute) 338 310 return V[j,:] 339 340 341 311 342 312 def compute_vertex_coordinates(self): … … 358 328 return vertex_coordinates 359 329 360 361 362 330 def get_triangles(self, indices=None): 363 331 """Get mesh triangles. … … 375 343 if indices is None: 376 344 return self.triangles 377 #indices = range(M)378 345 379 346 return num.take(self.triangles, indices, axis=0) 380 381 382 347 383 348 def get_disconnected_triangles(self): … … 398 363 399 364 The triangles created will have the format 400 401 365 [[0,1,2], 402 366 [3,4,5], 403 367 [6,7,8], 404 368 ... 405 [3*M-3 3*M-2 3*M-1]] 369 [3*M-3 3*M-2 3*M-1]] 406 370 """ 407 371 408 372 M = len(self) # Number of triangles 409 373 K = 3*M # Total number of unique vertices 410 411 T = num.reshape(num.arange(K, dtype=num.int), (M,3)) 412 413 return T 414 415 416 417 def get_unique_vertices(self, indices=None): 374 return num.reshape(num.arange(K, dtype=num.int), (M,3)) 375 376 def get_unique_vertices(self, indices=None): 418 377 """FIXME(Ole): This function needs a docstring""" 419 378 … … 421 380 unique_verts = {} 422 381 for triangle in triangles: 423 #print 'triangle(%s)=%s' % (type(triangle), str(triangle))424 382 unique_verts[triangle[0]] = 0 425 383 unique_verts[triangle[1]] = 0 … … 427 385 return unique_verts.keys() 428 386 429 430 387 def get_triangles_and_vertices_per_node(self, node=None): 431 388 """Get triangles associated with given node. … … 441 398 # Get index for this node 442 399 first = num.sum(self.number_of_triangles_per_node[:node]) 443 400 444 401 # Get number of triangles for this node 445 402 count = self.number_of_triangles_per_node[node] … … 459 416 # working directly with the inverted triangle structure 460 417 for i in range(self.number_of_full_nodes): 461 462 418 L = self.get_triangles_and_vertices_per_node(node=i) 463 464 419 triangle_list.append(L) 465 420 466 421 return triangle_list 467 468 422 469 423 def build_inverted_triangle_structure(self): … … 475 429 listing for each node how many triangles use it. N is the number of 476 430 nodes in mesh. 477 431 478 432 vertex_value_indices: An array of length M listing indices into 479 433 triangles ordered by node number. The (triangle_id, vertex_id) … … 483 437 used to average vertex values efficiently. 484 438 485 486 439 Example: 487 488 440 a = [0.0, 0.0] # node 0 489 441 b = [0.0, 2.0] # node 1 … … 492 444 e = [2.0, 2.0] # node 4 493 445 f = [4.0, 0.0] # node 5 494 495 446 nodes = array([a, b, c, d, e, f]) 496 497 #bac, bce, ecf, dbe, daf, dae 498 triangles = array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]]) 499 500 501 For this structure 502 447 448 # bac, bce, ecf, dbe 449 triangles = array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]]) 450 451 For this structure: 503 452 number_of_triangles_per_node = [1 3 3 1 3 1] 504 453 which means that node a has 1 triangle associated with it, node b 505 454 has 3, node has 3 and so on. 506 455 507 456 vertex_value_indices = [ 1 0 3 10 2 4 7 9 5 6 11 8] 508 457 which reflects the fact that … … 518 467 and by triangle 2, vertex 0 (index = 6) 519 468 and by triangle 3, vertex 2 (index = 11) 520 node 5 is used by triangle 2, vertex 2 (index = 8) 521 469 node 5 is used by triangle 2, vertex 2 (index = 8) 522 470 523 471 Preconditions: … … 526 474 Postcondition: 527 475 self.number_of_triangles_per_node is built 528 self.vertex_value_indices is built 476 self.vertex_value_indices is built 529 477 """ 530 478 … … 541 489 542 490 # Register (triangle, vertex) indices for each node 543 vertexlist = [None] *self.number_of_full_nodes491 vertexlist = [None] * self.number_of_full_nodes 544 492 for volume_id in range(self.number_of_full_triangles): 545 546 493 a = self.triangles[volume_id, 0] 547 494 b = self.triangles[volume_id, 1] 548 495 c = self.triangles[volume_id, 2] 549 496 550 for vertex_id, node_id in enumerate([a, b,c]):497 for vertex_id, node_id in enumerate([a, b, c]): 551 498 if vertexlist[node_id] is None: 552 499 vertexlist[node_id] = [] 553 554 vertexlist[node_id].append( (volume_id, vertex_id) ) 555 500 vertexlist[node_id].append((volume_id, vertex_id)) 556 501 557 502 # Build inverted triangle index array … … 561 506 for volume_id, vertex_id in vertices: 562 507 vertex_value_indices[k] = 3*volume_id + vertex_id 563 564 508 k += 1 565 509 … … 568 512 self.vertex_value_indices = vertex_value_indices 569 513 570 571 572 573 514 def get_extent(self, absolute=False): 574 515 """Return min and max of all x and y coordinates … … 577 518 are to be made absolute by taking georeference into account 578 519 """ 579 580 581 520 582 521 C = self.get_vertex_coordinates(absolute=absolute) … … 588 527 ymin = min(Y.flat) 589 528 ymax = max(Y.flat) 590 #print "C",C 529 591 530 return xmin, xmax, ymin, ymax 592 531 593 532 def get_areas(self): 594 """Get areas of all individual triangles.595 """ 596 return self.areas 533 """Get areas of all individual triangles.""" 534 535 return self.areas 597 536 598 537 def get_area(self): 599 """Return total area of mesh 600 """ 538 """Return total area of mesh""" 601 539 602 540 return num.sum(self.areas) … … 604 542 def set_georeference(self, g): 605 543 self.geo_reference = g 606 544 607 545 def get_georeference(self): 608 546 return self.geo_reference 609 610 611 547 -
branches/numpy/anuga/abstract_2d_finite_volumes/neighbour_mesh.py
r6304 r6428 13 13 14 14 import numpy as num 15 15 16 16 17 17 class Mesh(General_mesh): … … 91 91 verbose=verbose) 92 92 93 if verbose: print 'Initialising mesh' 93 if verbose: print 'Initialising mesh' 94 94 95 95 N = len(self) #Number_of_triangles … … 111 111 112 112 #Initialise each triangle 113 if verbose: print 'Mesh: Computing centroids and radii' 113 if verbose: print 'Mesh: Computing centroids and radii' 114 114 for i in range(N): 115 115 if verbose and i % ((N+10)/10) == 0: print '(%d/%d)' %(i, N) … … 117 117 x0, y0 = V[3*i, :] 118 118 x1, y1 = V[3*i+1, :] 119 x2, y2 = V[3*i+2, :] 119 x2, y2 = V[3*i+2, :] 120 120 121 121 #x0 = V[i, 0]; y0 = V[i, 1] … … 166 166 167 167 #Build neighbour structure 168 if verbose: print 'Mesh: Building neigbour structure' 168 if verbose: print 'Mesh: Building neigbour structure' 169 169 self.build_neighbour_structure() 170 170 … … 178 178 179 179 #Build tagged element dictionary mapping (tag) to array of elements 180 if verbose: print 'Mesh: Building tagged elements dictionary' 180 if verbose: print 'Mesh: Building tagged elements dictionary' 181 181 self.build_tagged_elements_dictionary(tagged_elements) 182 182 … … 184 184 self.lone_vertices = [] 185 185 #Check that all vertices have been registered 186 for node, count in enumerate(self.number_of_triangles_per_node): 186 for node, count in enumerate(self.number_of_triangles_per_node): 187 187 #msg = 'Node %d does not belong to an element.' %node 188 188 #assert count > 0, msg 189 189 if count == 0: 190 190 self.lone_vertices.append(node) 191 191 192 192 #Update boundary indices FIXME: OBSOLETE 193 193 #self.build_boundary_structure() 194 194 195 195 #FIXME check integrity? 196 if verbose: print 'Mesh: Done' 196 if verbose: print 'Mesh: Done' 197 197 198 198 def __repr__(self): … … 400 400 #print "tagged_elements", tagged_elements 401 401 self.tagged_elements = tagged_elements 402 402 403 403 def get_tagged_elements(self): 404 404 return self.tagged_elements … … 459 459 460 460 Using the mesh boundary, derive a bounding polygon for this mesh. 461 If multiple vertex values are present (vertices stored uniquely), 462 461 If multiple vertex values are present (vertices stored uniquely), 462 the algorithm will select the path that contains the entire mesh. 463 463 464 464 All points are in absolute UTM coordinates 465 465 """ 466 467 from anuga.utilities.numerical_tools import angle, ensure_numeric 468 466 467 from anuga.utilities.numerical_tools import angle, ensure_numeric 469 468 470 469 # Get mesh extent 471 470 xmin, xmax, ymin, ymax = self.get_extent(absolute=True) 472 471 pmin = ensure_numeric([xmin, ymin]) 473 pmax = ensure_numeric([xmax, ymax]) 474 472 pmax = ensure_numeric([xmax, ymax]) 475 473 476 474 # Assemble dictionary of boundary segments and choose starting point … … 478 476 inverse_segments = {} 479 477 p0 = None 480 mindist = num.sqrt(num.sum((pmax-pmin)**2)) # Start value across entire mesh 478 479 # Start value across entire mesh 480 mindist = num.sqrt(num.sum((pmax-pmin)**2)) 481 481 for i, edge_id in self.boundary.keys(): 482 482 # Find vertex ids for boundary segment … … 485 485 if edge_id == 2: a = 0; b = 1 486 486 487 A = self.get_vertex_coordinate(i, a, absolute=True) # Start 488 B = self.get_vertex_coordinate(i, b, absolute=True) # End 489 487 A = self.get_vertex_coordinate(i, a, absolute=True) # Start 488 B = self.get_vertex_coordinate(i, b, absolute=True) # End 490 489 491 490 # Take the point closest to pmin as starting point … … 503 502 p0 = B 504 503 505 506 504 # Sanity check 507 505 if p0 is None: … … 511 509 # Register potential paths from A to B 512 510 if not segments.has_key(tuple(A)): 513 segments[tuple(A)] = [] # Empty list for candidate points 514 515 segments[tuple(A)].append(B) 516 511 segments[tuple(A)] = [] # Empty list for candidate points 512 513 segments[tuple(A)].append(B) 517 514 518 515 # Start with smallest point and follow boundary (counter clock wise) 519 516 polygon = [list(p0)]# Storage for final boundary polygon 520 point_registry = {} # Keep track of storage to avoid multiple runs 521 # around boundary. This will only be the case if 522 517 point_registry = {} # Keep track of storage to avoid multiple runs 518 # around boundary. This will only be the case if 519 # there are more than one candidate. 523 520 # FIXME (Ole): Perhaps we can do away with polygon 524 521 # and use only point_registry to save space. 525 522 526 point_registry[tuple(p0)] = 0 527 523 point_registry[tuple(p0)] = 0 524 528 525 while len(point_registry) < len(self.boundary): 529 530 526 candidate_list = segments[tuple(p0)] 531 527 if len(candidate_list) > 1: 532 # Multiple points detected (this will be the case for meshes 533 # with duplicate points as those used for discontinuous 534 535 # Take the candidate that is furthest to the clockwise 536 537 538 539 528 # Multiple points detected (this will be the case for meshes 529 # with duplicate points as those used for discontinuous 530 # triangles with vertices stored uniquely). 531 # Take the candidate that is furthest to the clockwise 532 # direction, as that will follow the boundary. 533 # 534 # This will also be the case for pathological triangles 535 # that have no neighbours. 540 536 541 537 if verbose: 542 print 'Point %s has multiple candidates: %s'\543 %(str(p0), candidate_list)538 print ('Point %s has multiple candidates: %s' 539 % (str(p0), candidate_list)) 544 540 545 541 # Check that previous are not in candidate list … … 548 544 549 545 # Choose vector against which all angles will be measured 550 if len(polygon) > 1: 551 v_prev = p0 - polygon[-2] # Vector that leads to p0552 546 if len(polygon) > 1: 547 v_prev = p0 - polygon[-2] # Vector that leads to p0 548 # from previous point 553 549 else: 554 # FIXME (Ole): What do we do if the first point has 555 550 # FIXME (Ole): What do we do if the first point has 551 # multiple candidates? 556 552 # Being the lower left corner, perhaps we can use the 557 # vector [1, 0], but I really don't know if this is 558 553 # vector [1, 0], but I really don't know if this is 554 # completely watertight. 559 555 v_prev = [1.0, 0.0] 560 561 562 # Choose candidate with minimum angle 556 557 # Choose candidate with minimum angle 563 558 minimum_angle = 2*pi 564 559 for pc in candidate_list: 565 566 vc = pc-p0 # Candidate vector (from p0 to candidate pt) 567 560 vc = pc-p0 # Candidate vector (from p0 to candidate pt) 561 568 562 # Angle between each candidate and the previous vector 569 563 # in [-pi, pi] 570 564 ac = angle(vc, v_prev) 571 565 if ac > pi: 572 # Give preference to angles on the right hand side 573 # of v_prev 566 # Give preference to angles on the right hand side 567 # of v_prev 574 568 # print 'pc = %s, changing angle from %f to %f'\ 575 569 # %(pc, ac*180/pi, (ac-2*pi)*180/pi) 576 570 ac = ac-2*pi 577 571 578 # Take the minimal angle corresponding to the 579 572 # Take the minimal angle corresponding to the 573 # rightmost vector 580 574 if ac < minimum_angle: 581 575 minimum_angle = ac 582 p1 = pc # Best candidate 583 576 p1 = pc # Best candidate 584 577 585 578 if verbose is True: 586 579 print ' Best candidate %s, angle %f'\ 587 580 %(p1, minimum_angle*180/pi) 588 589 581 else: 590 582 p1 = candidate_list[0] 591 583 592 593 584 if point_registry.has_key(tuple(p1)): 594 # We have reached a point already visited. 595 596 if num.allclose(p1, polygon[0]): 597 # If it is the initial point, the polygon is complete. 598 585 # We have reached a point already visited. 586 if num.allclose(p1, polygon[0]): 587 # If it is the initial point, the polygon is complete. 599 588 if verbose is True: 600 601 print polygon 602 589 print ' Stop criterion fulfilled at point %s' %p1 590 print polygon 591 603 592 # We have completed the boundary polygon - yeehaa 604 605 else: 606 607 # This would be a pathological triangle, but the 608 609 610 593 break 594 else: 595 # The point already visited is not the initial point 596 # This would be a pathological triangle, but the 597 # algorithm must be able to deal with this 598 pass 599 611 600 else: 612 601 # We are still finding new points on the boundary 613 602 point_registry[tuple(p1)] = len(point_registry) 614 615 polygon.append(list(p1)) # De-numeric each point :-)603 604 polygon.append(list(p1)) # De-numeric each point :-) 616 605 p0 = p1 617 606 618 619 607 return polygon 620 621 608 622 609 def check_integrity(self): … … 641 628 x1, y1 = V[3*i+1, :] 642 629 x2, y2 = V[3*i+2, :] 643 630 644 631 # Check that area hasn't been compromised 645 632 area = self.areas[i] … … 678 665 679 666 x = (u[0]*v[0] + u[1]*v[1])/l_u # Inner product 680 667 681 668 msg = 'Normal vector (%f,%f) is not perpendicular to' %tuple(v) 682 669 msg += ' edge (%f,%f) in triangle %d.' %(tuple(u) + (i,)) 683 msg += ' Inner product is %e.' %x 670 msg += ' Inner product is %e.' %x 684 671 assert x < epsilon, msg 685 672 … … 690 677 for i in range(N): 691 678 # For each triangle 692 679 693 680 for k, neighbour_id in enumerate(self.neighbours[i,:]): 694 681 … … 752 739 # Node is lone - i.e. not part of the mesh 753 740 continue 754 741 755 742 k += 1 756 743 757 744 volume_id = index / 3 758 745 vertex_id = index % 3 759 746 760 747 msg = 'Triangle %d, vertex %d points to %d. Should have been %d'\ 761 748 %(volume_id, vertex_id, self.triangles[volume_id, vertex_id], current_node) 762 749 assert self.triangles[volume_id, vertex_id] == current_node, msg 763 750 764 751 if self.number_of_triangles_per_node[current_node] == k: 765 752 # Move on to next node … … 788 775 if not self.geo_reference.is_absolute(): 789 776 V = self.geo_reference.get_absolute(V) 790 777 791 778 return V 792 779 793 780 794 781 def get_radii(self): 795 782 """Return all radii. 796 783 Return radius of inscribed cirle for all triangles 797 784 """ 798 return self.radii 785 return self.radii 799 786 800 787 … … 826 813 str += ' Areas [m^2]:\n' 827 814 str += ' A in [%f, %f]\n' %(min(areas), max(areas)) 828 str += ' number of distinct areas: %d\n' %(len(areas)) 815 str += ' number of distinct areas: %d\n' %(len(areas)) 829 816 str += ' Histogram:\n' 830 817 … … 833 820 lo = hi 834 821 if i+1 < len(bins): 835 #Open upper interval 822 #Open upper interval 836 823 hi = bins[i+1] 837 str += ' [%f, %f[: %d\n' %(lo, hi, count) 824 str += ' [%f, %f[: %d\n' %(lo, hi, count) 838 825 else: 839 826 #Closed upper interval … … 849 836 k = 0 850 837 lower = min(areas) 851 for i, a in enumerate(areas): 852 if i % (N/10) == 0 and i != 0: #For every 10% of the sorted areas 838 for i, a in enumerate(areas): 839 if i % (N/10) == 0 and i != 0: #For every 10% of the sorted areas 853 840 str += ' %d triangles in [%f, %f]\n' %(i-k, lower, a) 854 841 lower = a 855 842 k = i 856 843 857 844 str += ' %d triangles in [%f, %f]\n'\ 858 %(N-k, lower, max(areas)) 859 860 845 %(N-k, lower, max(areas)) 846 847 861 848 str += ' Boundary:\n' 862 849 str += ' Number of boundary segments == %d\n' %(len(self.boundary)) 863 str += ' Boundary tags == %s\n' %self.get_boundary_tags() 850 str += ' Boundary tags == %s\n' %self.get_boundary_tags() 864 851 str += '------------------------------------------------\n' 865 852 866 853 867 854 return str 868 855 869 856 870 857 def get_triangle_containing_point(self, point): … … 874 861 875 862 """ 876 863 877 864 # FIXME(Ole): This function is currently brute force 878 865 # because I needed it for diagnostics. … … 884 871 polygon = self.get_boundary_polygon() 885 872 #print polygon, point 886 873 887 874 if is_outside_polygon(point, polygon): 888 875 msg = 'Point %s is outside mesh' %str(point) … … 899 886 if is_inside_polygon(point, poly, closed=True): 900 887 return i 901 888 902 889 return 903 890 … … 930 917 Resulting segments are unsorted 931 918 """ 932 919 933 920 V = self.get_vertex_coordinates() 934 921 N = len(self) 935 922 936 923 # Adjust polyline to mesh spatial origin 937 924 polyline = self.geo_reference.get_relative(polyline) … … 939 926 if use_cache is True: 940 927 segments = cache(get_intersecting_segments, 941 (V, N, polyline), 928 (V, N, polyline), 942 929 {'verbose': verbose}, 943 930 verbose=verbose) 944 else: 931 else: 945 932 segments = get_intersecting_segments(V, N, polyline, 946 933 verbose=verbose) 947 934 948 935 949 936 return segments 950 951 937 938 952 939 953 940 def get_triangle_neighbours(self, tri_id): … … 956 943 957 944 Negative returned triangle id's represent a boundary as a neighbour. 958 945 959 946 If the given triangle id is bad, return an empty list. 960 947 """ … … 964 951 except IndexError: 965 952 return [] 966 953 967 954 968 955 def get_interpolation_object(self): 969 956 """Get object I that will allow linear interpolation using this mesh 970 971 This is a time consuming process but it needs only to be 957 958 This is a time consuming process but it needs only to be 972 959 once for the mesh. 973 974 Interpolation can then be done using 975 976 result = I.interpolate_block(vertex_values, interpolation_points) 977 960 961 Interpolation can then be done using 962 963 result = I.interpolate_block(vertex_values, interpolation_points) 964 978 965 where vertex values have been obtained from a quantity using 979 966 vertex_values, triangles = self.get_vertex_values() … … 984 971 else: 985 972 from anuga.fit_interpolate.interpolate import Interpolate 986 987 # Get discontinuous mesh - this will match internal 973 974 # Get discontinuous mesh - this will match internal 988 975 # representation of vertex values 989 976 triangles = self.get_disconnected_triangles() … … 992 979 I = Interpolate(vertex_coordinates, triangles) 993 980 self.interpolation_object = I 994 995 return I 996 981 982 return I 983 997 984 998 985 class Triangle_intersection: 999 986 """Store information about line segments intersecting a triangle 1000 987 1001 988 Attributes are 1002 989 … … 1014 1001 length=None, 1015 1002 triangle_id=None): 1016 self.segment = segment 1003 self.segment = segment 1017 1004 self.normal = normal 1018 1005 self.length = length 1019 1006 self.triangle_id = triangle_id 1020 1007 1021 1008 1022 1009 def __repr__(self): … … 1027 1014 self.length, 1028 1015 self.triangle_id) 1029 1016 1030 1017 return s 1031 1018 1032 1019 1033 1020 1034 1021 def _get_intersecting_segments(V, N, line, … … 1051 1038 from anuga.utilities.polygon import intersection 1052 1039 from anuga.utilities.polygon import is_inside_polygon 1053 1040 1054 1041 msg = 'Line segment must contain exactly two points' 1055 1042 assert len(line) == 2, msg … … 1060 1047 eta0 = line[0][1] 1061 1048 1062 1049 1063 1050 # Check intersection with edge segments for all triangles 1064 1051 # FIXME (Ole): This should be implemented in C … … 1069 1056 x1, y1 = V[3*i+1, :] 1070 1057 x2, y2 = V[3*i+2, :] 1071 1058 1072 1059 1073 1060 edge_segments = [[[x0,y0], [x1, y1]], … … 1076 1063 1077 1064 # Find segments that are intersected by line 1078 1065 1079 1066 intersections = {} # Use dictionary to record points only once 1080 1067 for edge in edge_segments: … … 1082 1069 status, value = intersection(line, edge) 1083 1070 #if value is not None: print 'Triangle %d, Got' %i, status, value 1084 1071 1085 1072 if status == 1: 1086 1073 # Normal intersection of one edge or vertex 1087 intersections[tuple(value)] = i 1074 intersections[tuple(value)] = i 1088 1075 1089 1076 # Exclude singular intersections with vertices … … 1101 1088 # along this edge, it will be recorded here. 1102 1089 intersections[tuple(value[0,:])] = i 1103 intersections[tuple(value[1,:])] = i 1104 1105 1090 intersections[tuple(value[1,:])] = i 1091 1092 1106 1093 if len(intersections) == 1: 1107 1094 # Check if either line end point lies fully within this triangle … … 1113 1100 intersections[tuple(line[1])] = i 1114 1101 elif is_inside_polygon(line[0], poly, closed=False): 1115 intersections[tuple(line[0])] = i 1102 intersections[tuple(line[0])] = i 1116 1103 else: 1117 # Ignore situations where one vertex is touch, for instance 1104 # Ignore situations where one vertex is touch, for instance 1118 1105 continue 1119 1106 … … 1141 1128 z0 = num.array([x0 - xi0, y0 - eta0], num.float) 1142 1129 z1 = num.array([x1 - xi0, y1 - eta0], num.float) 1143 d0 = num.sqrt(num.sum(z0**2)) 1130 d0 = num.sqrt(num.sum(z0**2)) 1144 1131 d1 = num.sqrt(num.sum(z1**2)) 1145 1132 1146 1133 if d1 < d0: 1147 1134 # Swap … … 1151 1138 1152 1139 # (x0,y0) is now the origin of the intersecting segment 1153 1140 1154 1141 1155 1142 # Normal direction: … … 1160 1147 1161 1148 1162 segment = ((x0,y0), (x1, y1)) 1149 segment = ((x0,y0), (x1, y1)) 1163 1150 T = Triangle_intersection(segment=segment, 1164 1151 normal=normal, … … 1168 1155 1169 1156 # Add segment unless it was done earlier 1170 if not triangle_intersections.has_key(segment): 1157 if not triangle_intersections.has_key(segment): 1171 1158 triangle_intersections[segment] = T 1172 1159 1173 1160 1174 # Return segments as a list 1161 # Return segments as a list 1175 1162 return triangle_intersections.values() 1176 1163 1177 1164 1178 1165 def get_intersecting_segments(V, N, polyline, 1179 verbose=False): 1166 verbose=False): 1180 1167 """Internal function to find edges intersected by Polyline 1181 1168 1182 1169 Input: 1183 1170 V: Vertex coordinates as obtained by mesh.get_vertex_coordinates() 1184 1171 N: Number of triangles in mesh 1185 polyline - list of points forming a segmented line 1172 polyline - list of points forming a segmented line 1186 1173 verbose 1187 1174 Output: … … 1190 1177 This method is used by the public method 1191 1178 get_intersecting_segments(self, polyline) which also contains 1192 more documentation. 1179 more documentation. 1193 1180 """ 1194 1181 1195 1182 msg = 'Polyline must contain at least two points' 1196 1183 assert len(polyline) >= 2, msg 1197 1198 1184 1185 1199 1186 # For all segments in polyline 1200 1187 triangle_intersections = [] … … 1206 1193 print '(%.2f, %.2f) - (%.2f, %.2f)' %(point0[0], point0[1], 1207 1194 point1[0], point1[1]) 1208 1195 1209 1196 line = [point0, point1] 1210 1197 triangle_intersections += _get_intersecting_segments(V, N, line, … … 1214 1201 msg = 'No segments found' 1215 1202 assert len(triangle_intersections) > 0, msg 1216 1217 1203 1204 1218 1205 return triangle_intersections 1219 1220 1221 1222 1223 1206 1207 1208 1209 1210 1224 1211 def segment_midpoints(segments): 1225 1212 """Calculate midpoints of all segments 1226 1213 1227 1214 Inputs: 1228 1215 segments: List of instances of class Segment 1229 1216 1230 1217 Ouputs: 1231 1218 midpoints: List of points 1232 1219 """ 1233 1220 1234 1221 midpoints = [] 1235 1222 msg = 'Elements of input list to segment_midpoints must be of class Triangle_intersection' 1236 1223 for segment in segments: 1237 1224 assert isinstance(segment, Triangle_intersection), msg 1238 1239 midpoint = num.sum(num.array(segment.segment, num.float) )/21225 1226 midpoint = num.sum(num.array(segment.segment, num.float), axis=0)/2 1240 1227 midpoints.append(midpoint) 1241 1228 1242 1229 return midpoints 1243 1244 1245 1230 1231 1232 -
branches/numpy/anuga/abstract_2d_finite_volumes/test_general_mesh.py
r6410 r6428 53 53 e = [2.0, 2.0] 54 54 f = [4.0, 0.0] 55 56 55 nodes = num.array([a, b, c, d, e, f]) 57 56 58 57 nodes_absolute = geo.get_absolute(nodes) 59 58 60 # bac, bce, ecf, dbe, daf, dae59 # bac, bce, ecf, dbe 61 60 triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int) 62 61 63 domain = General_mesh(nodes, triangles, 64 geo_reference = geo) 65 66 verts = domain.get_vertex_coordinates(triangle_id=0) 67 msg = ("num.array([b,a,c])=\n%s\nshould be the same as 'verts'=\n%s" 62 domain = General_mesh(nodes, triangles, geo_reference=geo) 63 64 verts = domain.get_vertex_coordinates(triangle_id=0) # bac 65 msg = ("num.array([b,a,c])=\n%s\nshould be close to 'verts'=\n%s" 68 66 % (str(num.array([b,a,c])), str(verts))) 69 #self.assert_(num.allclose(num.array([b,a,c]), verts)) 70 assert num.allclose(num.array([b,a,c]), verts), msg 67 self.failUnless(num.allclose(num.array([b,a,c]), verts), msg) 71 68 72 69 verts = domain.get_vertex_coordinates(triangle_id=0) 73 self.assert_(num.allclose(num.array([b,a,c]), verts)) 70 msg = ("num.array([b,a,c])=\n%s\nshould be close to 'verts'=\n%s" 71 % (str(num.array([b,a,c])), str(verts))) 72 self.assert_(num.allclose(num.array([b,a,c]), verts), msg) 73 74 verts = domain.get_vertex_coordinates(triangle_id=0, absolute=True) 75 msg = ("num.array([...])=\n%s\nshould be close to 'verts'=\n%s" 76 % (str(num.array([nodes_absolute[1], 77 nodes_absolute[0], 78 nodes_absolute[2]])), 79 str(verts))) 80 self.assert_(num.allclose(num.array([nodes_absolute[1], 81 nodes_absolute[0], 82 nodes_absolute[2]]), 83 verts), msg) 84 74 85 verts = domain.get_vertex_coordinates(triangle_id=0, 75 86 absolute=True) 87 msg = ("num.array([...])=\n%s\nshould be close to 'verts'=\n%s" 88 % (str(num.array([nodes_absolute[1], 89 nodes_absolute[0], 90 nodes_absolute[2]])), 91 str(verts))) 76 92 self.assert_(num.allclose(num.array([nodes_absolute[1], 77 nodes_absolute[0], 78 nodes_absolute[2]]), verts)) 79 verts = domain.get_vertex_coordinates(triangle_id=0, 80 absolute=True) 81 self.assert_(num.allclose(num.array([nodes_absolute[1], 82 nodes_absolute[0], 83 nodes_absolute[2]]), verts)) 84 85 93 nodes_absolute[0], 94 nodes_absolute[2]]), 95 verts), msg) 86 96 87 97 def test_get_vertex_coordinates_triangle_id(self): … … 283 293 nodes_absolute = geo.get_absolute(nodes) 284 294 285 # bac, bce, ecf, dbe, daf, dae295 # bac, bce, ecf, dbe 286 296 triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]]) 287 297 288 domain = General_mesh(nodes, triangles, 289 geo_reference = geo) 298 domain = General_mesh(nodes, triangles, geo_reference = geo) 290 299 node = domain.get_node(2) 291 #self.assertEqual(c, node) 292 msg = ('\nc=%s\nmode=%s' % (str(c), str(node))) 300 msg = ('\nc=%s\nnode=%s' % (str(c), str(node))) 293 301 self.failUnless(num.alltrue(c == node), msg) 302 303 # repeat get_node(), see if result same 304 node = domain.get_node(2) 305 msg = ('\nc=%s\nnode=%s' % (str(c), str(node))) 306 self.failUnless(num.alltrue(c == node), msg) 294 307 295 308 node = domain.get_node(2, absolute=True) 296 #self.assertEqual(nodes_absolute[2], node) 297 self.failUnless(num.alltrue(nodes_absolute[2] == node)) 298 309 msg = ('\nnodes_absolute[2]=%s\nnode=%s' 310 % (str(nodes_absolute[2]), str(node))) 311 self.failUnless(num.alltrue(nodes_absolute[2] == node), msg) 312 313 # repeat get_node(absolute=True), see if result same 299 314 node = domain.get_node(2, absolute=True) 300 #self.assertEqual(nodes_absolute[2], node) 301 self.failUnless(num.alltrue(nodes_absolute[2] == node)) 315 msg = ('\nnodes_absolute[2]=%s\nnode=%s' 316 % (str(nodes_absolute[2]), str(node))) 317 self.failUnless(num.alltrue(nodes_absolute[2] == node), msg) 302 318 303 319 … … 337 353 self.failUnlessRaises(AssertionError, General_mesh, 338 354 nodes, triangles, geo_reference=geo) 355 356 def test_raw_change_points_geo_ref(self): 357 x0 = 1000.0 358 y0 = 2000.0 359 geo = Geo_reference(56, x0, y0) 360 339 361 340 362 … … 343 365 344 366 if __name__ == "__main__": 345 suite = unittest.makeSuite(Test_General_Mesh,'test') 367 suite = unittest.makeSuite(Test_General_Mesh, 'test') 368 #suite = unittest.makeSuite(Test_General_Mesh, 'test_get_vertex_coordinates_with_geo_ref') 346 369 runner = unittest.TextTestRunner() 347 370 runner.run(suite) -
branches/numpy/anuga/abstract_2d_finite_volumes/test_neighbour_mesh.py
r6410 r6428 1169 1169 """ 1170 1170 1171 1172 1171 # test 1173 1172 a = [0.0, 0.0] … … 1176 1175 1177 1176 absolute_points = [a, b, c] 1178 vertices = [[0, 1,2]]1179 1180 geo = Geo_reference(56, 67,-56)1177 vertices = [[0, 1, 2]] 1178 1179 geo = Geo_reference(56, 67, -56) 1181 1180 1182 1181 relative_points = geo.change_points_geo_ref(absolute_points) 1183 1184 #print 'Relative', relative_points1185 #print 'Absolute', absolute_points1186 1182 1187 1183 mesh = Mesh(relative_points, vertices, geo_reference=geo) … … 1842 1838 1843 1839 if __name__ == "__main__": 1844 suite = unittest.makeSuite(Test_Mesh, 'test')1840 suite = unittest.makeSuite(Test_Mesh, 'test') 1845 1841 runner = unittest.TextTestRunner() 1846 1842 runner.run(suite) -
branches/numpy/anuga/coordinate_transforms/geo_reference.py
r6360 r6428 101 101 self.read_ASCII(ASCIIFile, read_title=read_title) 102 102 103 # # Might be better to have this method instead of the following 3.104 # def get_origin(self):105 # return (self.zone, self.xllcorner, self.yllcorner)106 107 103 ## 108 104 # @brief Get the X coordinate of the origin of this georef. … … 238 234 ################################################################################ 239 235 236 ## 237 # @brief Change points to be absolute wrt new georef 'points_geo_ref'. 238 # @param points The points to change. 239 # @param points_geo_ref The new georef to make points absolute wrt. 240 # @return The changed points. 241 # @note If 'points' is a list then a changed list is returned. 242 # @note The input points data is changed. 240 243 def change_points_geo_ref(self, points, points_geo_ref=None): 244 """Change the geo reference of a list or numeric array of points to 245 be this reference.(The reference used for this object) 246 If the points do not have a geo ref, assume 'absolute' input values 241 247 """ 242 Change the geo reference of a list or numeric array of points to 243 be this reference.(The reference used for this object) 244 If the points do not have a geo ref, assume 'absolute' values 245 """ 246 247 is_list = False 248 if type(points) == types.ListType: 249 is_list = True 248 249 # remember if we got a list 250 is_list = isinstance(points, list) 250 251 251 252 points = ensure_numeric(points, num.float) 252 253 254 # sanity checks 253 255 if len(points.shape) == 1: 254 256 # One point has been passed … … 288 290 # @return True if ??? 289 291 def is_absolute(self): 290 """Return True if xllcorner==yllcorner==0 291 indicating that points in question are absolute. 292 """ 292 """Return True if xllcorner==yllcorner==0""" 293 293 294 294 return num.allclose([self.xllcorner, self.yllcorner], 0) … … 298 298 # @param points 299 299 # @return 300 # @note 300 # @note This method changes the input points! 301 301 def get_absolute(self, points): 302 """Given a set of points geo referenced to this instance, 302 """Given a set of points geo referenced to this instance 303 303 304 return the points as absolute values. 304 305 """ 305 306 306 #if self.is_absolute:307 # return points308 309 307 # remember if we got a list 310 is_list = False 311 if type(points) == types.ListType: 312 is_list = True 313 308 is_list = isinstance(points, list) 309 310 # convert to numeric array 314 311 points = ensure_numeric(points, num.float) 312 313 # sanity checks 315 314 if len(points.shape) == 1: 316 315 #One point has been passed … … 326 325 327 326 # Add geo ref to points 328 #if not self.is_absolute:329 327 if not self.is_absolute(): 330 328 points[:,0] += self.xllcorner -
branches/numpy/anuga/coordinate_transforms/test_geo_reference.py
r6410 r6428 503 503 'bad shape did not raise error!') 504 504 os.remove(point_file) 505 506 def test_functionality_get_absolute(self): 507 x0 = 1000.0 508 y0 = 2000.0 509 geo = Geo_reference(56, x0, y0) 510 511 # iterable points (*not* num.array()) 512 points = ((2,3), (3,1), (5,2)) 513 abs_points = geo.get_absolute(points) 514 # check we haven't changed 'points' itself 515 self.failIf(num.alltrue(abs_points == points)) 516 new_points = abs_points.copy() 517 new_points[:,0] -= x0 518 new_points[:,1] -= y0 519 self.failUnless(num.alltrue(new_points == points)) 520 521 # points in num.array() 522 points = num.array(((2,3), (3,1), (5,2)), num.float) 523 abs_points = geo.get_absolute(points) 524 # check we haven't changed 'points' itself 525 self.failIf(num.alltrue(abs_points == points)) 526 new_points = abs_points.copy() 527 new_points[:,0] -= x0 528 new_points[:,1] -= y0 529 self.failUnless(num.alltrue(new_points == points)) 530 505 531 506 532 #------------------------------------------------------------- 507 533 508 534 if __name__ == "__main__": 509 suite = unittest.makeSuite(geo_referenceTestCase,'test') 535 suite = unittest.makeSuite(geo_referenceTestCase, 'test') 536 #suite = unittest.makeSuite(geo_referenceTestCase, 'test_functionality_get_absolute') 510 537 runner = unittest.TextTestRunner() #verbosity=2) 511 538 runner.run(suite) -
branches/numpy/anuga/fit_interpolate/interpolate.py
r6410 r6428 305 305 t = self.interpolate_block(f, point_coordinates[start:end], 306 306 verbose=verbose) 307 z = num.concatenate((z, t) )307 z = num.concatenate((z, t), axis=0) #??default# 308 308 start = end 309 309 … … 311 311 t = self.interpolate_block(f, point_coordinates[start:end], 312 312 verbose=verbose) 313 z = num.concatenate((z, t) )313 z = num.concatenate((z, t), axis=0) #??default# 314 314 return z 315 315 … … 1189 1189 1190 1190 #Add the x and y together 1191 vertex_coordinates = num.concatenate((x[:,num.newaxis], y[:,num.newaxis]),axis=1) 1191 vertex_coordinates = num.concatenate((x[:,num.newaxis], y[:,num.newaxis]), 1192 axis=1) 1192 1193 1193 1194 #Will return the quantity values at the specified times and locations -
branches/numpy/anuga/geospatial_data/geospatial_data.py
r6410 r6428 1 """Class Geospatial_data - Manipulation of locations on the planet and2 associated attributes. 3 1 """Class Geospatial_data 2 3 Manipulation of locations on the planet and associated attributes. 4 4 """ 5 5 … … 11 11 from RandomArray import randint, seed, get_seed 12 12 from copy import deepcopy 13 13 14 from Scientific.IO.NetCDF import NetCDFFile 14 15 15 import numpy as num 16 16 … … 25 25 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 26 26 from anuga.config import netcdf_float 27 27 28 28 29 DEFAULT_ATTRIBUTE = 'elevation' … … 139 140 140 141 self.set_verbose(verbose) 141 self.geo_reference = None # create the attribute142 self.geo_reference = None 142 143 self.file_name = file_name 143 144 … … 148 149 149 150 if file_name is None: 150 if latitudes is not None \ 151 or longitudes is not None \ 152 or points_are_lats_longs: 151 if (latitudes is not None or longitudes is not None 152 or points_are_lats_longs): 153 153 data_points, geo_reference = \ 154 154 _set_using_lat_long(latitudes=latitudes, … … 156 156 geo_reference=geo_reference, 157 157 data_points=data_points, 158 points_are_lats_longs= \159 points_are_lats_longs)158 points_are_lats_longs= 159 points_are_lats_longs) 160 160 self.check_data_points(data_points) 161 161 self.set_attributes(attributes) … … 213 213 msg = 'There is no data or file provided!' 214 214 raise ValueError, msg 215 216 215 else: 217 216 self.data_points = ensure_numeric(data_points) … … 257 256 """ 258 257 259 from anuga.coordinate_transforms.geo_reference import Geo_reference260 261 258 if geo_reference is None: 262 259 # Use default - points are in absolute coordinates … … 269 266 # FIXME (Ole): This exception will be raised even 270 267 # if geo_reference is None. Is that the intent Duncan? 271 msg = 'Argument geo_reference must be a valid Geo_reference '272 msg += 'object or None.'268 msg = ('Argument geo_reference must be a valid Geo_reference ' 269 'object or None.') 273 270 raise Expection, msg 274 271 … … 378 375 # @param isSouthHemisphere If True, return lat/lon points in S.Hemi. 379 376 # @return A set of data points, in appropriate form. 380 def get_data_points(self, absolute=True, geo_reference=None, 381 as_lat_long=False, isSouthHemisphere=True): 377 def get_data_points(self, 378 absolute=True, 379 geo_reference=None, 380 as_lat_long=False, 381 isSouthHemisphere=True): 382 382 """Get coordinates for all data points as an Nx2 array 383 383 … … 460 460 # @return The new geospatial object. 461 461 def __add__(self, other): 462 """Returns the addition of 2 geospati cal objects,462 """Returns the addition of 2 geospatial objects, 463 463 objects are concatencated to the end of each other 464 464 … … 488 488 if self.attributes is None: 489 489 if other.attributes is not None: 490 msg = 'Geospatial data must have the same '491 msg += 'attributes to allow addition.'490 msg = ('Geospatial data must have the same ' 491 'attributes to allow addition.') 492 492 raise Exception, msg 493 493 … … 499 499 attrib1 = self.attributes[x] 500 500 attrib2 = other.attributes[x] 501 new_attributes[x] = num.concatenate((attrib1, attrib2)) 501 new_attributes[x] = num.concatenate((attrib1, attrib2), 502 axis=0) #??default# 502 503 else: 503 msg = 'Geospatial data must have the same \n'504 msg += 'attributes to allow addition.'504 msg = ('Geospatial data must have the same ' 505 'attributes to allow addition.') 505 506 raise Exception, msg 506 507 else: … … 523 524 return self + other 524 525 525 526 527 526 ################################################################################ 527 # IMPORT/EXPORT POINTS FILES 528 ################################################################################ 528 529 529 530 ## … … 560 561 except IOError, e: 561 562 # This should only be if a file is not found 562 msg = 'Could not open file %s. ' % file_name563 msg += 'Check the file location.'563 msg = ('Could not open file %s. Check the file location.' 564 % file_name) 564 565 raise IOError, msg 565 566 except SyntaxError, e: 566 567 # This should only be if there is a format error 567 msg = 'Problem with format of file %s. \n' %file_name568 msg += Error_message['IOError']568 msg = ('Problem with format of file %s.\n%s' 569 % (file_name, Error_message['IOError'])) 569 570 raise SyntaxError, msg 570 571 else: 571 msg = 'Extension %s is unknown' % file_name[-4:]572 msg = 'Extension %s is unknown' % file_name[-4:] 572 573 raise IOError, msg 573 574 … … 614 615 self.get_all_attributes(), 615 616 self.get_geo_reference()) 616 617 617 elif file_name[-4:] == ".txt" or file_name[-4:] == ".csv": 618 618 msg = "ERROR: trying to write a .txt file with relative data." … … 621 621 self.get_data_points(absolute=True, 622 622 as_lat_long=as_lat_long, 623 isSouthHemisphere=isSouthHemisphere),623 isSouthHemisphere=isSouthHemisphere), 624 624 self.get_all_attributes(), 625 625 as_lat_long=as_lat_long) 626 627 626 elif file_name[-4:] == ".urs" : 628 627 msg = "ERROR: Can not write a .urs file as a relative file." … … 630 629 _write_urs_file(file_name, 631 630 self.get_data_points(as_lat_long=True, 632 isSouthHemisphere=isSouthHemisphere)) 633 631 isSouthHemisphere=isSouthHemisphere)) 634 632 else: 635 633 msg = 'Unknown file type %s ' %file_name … … 694 692 random_list = [] 695 693 remainder_list = [] 696 new_size = round(factor *self_size)694 new_size = round(factor * self_size) 697 695 698 696 # Find unique random numbers … … 713 711 # Set seed if provided, mainly important for unit test! 714 712 # plus recalcule seed when no seed provided. 715 if seed_num !=None:713 if seed_num is not None: 716 714 seed(seed_num, seed_num) 717 715 else: … … 734 732 735 733 # pops array index (random_num) from remainder_list 736 # (which starts as the 737 # total_list and appends to random_list 734 # (which starts as the total_list and appends to random_list) 738 735 random_num_len = len(random_num) 739 736 for i in random_num: … … 746 743 747 744 # FIXME: move to tests, it might take a long time 748 # then create an array of random leng htbetween 500 and 1000,745 # then create an array of random length between 500 and 1000, 749 746 # and use a random factor between 0 and 1 750 747 # setup for assertion … … 752 749 test_total.extend(remainder_list) 753 750 test_total.sort() 754 msg = 'The two random lists made from the original list when added ' \755 'together DO NOT equal the original list'751 msg = ('The two random lists made from the original list when added ' 752 'together DO NOT equal the original list') 756 753 assert total_list == test_total, msg 757 754 … … 770 767 file pointer position 771 768 """ 772 from Scientific.IO.NetCDF import NetCDFFile 769 773 770 # FIXME - what to do if the file isn't there 774 771 … … 799 796 self.number_of_blocks = self.number_of_points/self.max_read_lines 800 797 # This computes the number of full blocks. The last block may be 801 # smaller and won't be i rcluded in this estimate.798 # smaller and won't be included in this estimate. 802 799 803 800 if self.verbose is True: 804 print 'Reading %d points (in ~%d blocks) from file %s. ' \ 805 % (self.number_of_points, 806 self.number_of_blocks, 807 self.file_name), 808 print 'Each block consists of %d data points' \ 809 % self.max_read_lines 810 801 print ('Reading %d points (in ~%d blocks) from file %s. ' 802 % (self.number_of_points, self.number_of_blocks, 803 self.file_name)), 804 print ('Each block consists of %d data points' 805 % self.max_read_lines) 811 806 else: 812 807 # Assume the file is a csv file … … 839 834 840 835 if self.verbose is True: 841 if self.show_verbose >= self.start_row \ 842 and self.show_verbose < fin_row: 843 print 'Reading block %d (points %d to %d) out of %d'\ 844 %(self.block_number, 845 self.start_row, 846 fin_row, 847 self.number_of_blocks) 836 if (self.show_verbose >= self.start_row 837 and self.show_verbose < fin_row): 838 print ('Reading block %d (points %d to %d) out of %d' 839 % (self.block_number, self.start_row, 840 fin_row, self.number_of_blocks)) 848 841 849 842 self.show_verbose += max(self.max_read_lines, 850 843 self.verbose_block_size) 851 852 844 853 845 # Read next block … … 861 853 862 854 self.block_number += 1 863 864 855 else: 865 856 # Assume the file is a csv file … … 868 859 att_dict, 869 860 geo_ref, 870 self.file_pointer) = \871 _read_csv_file_blocking(self.file_pointer,872 self.header[:],873 max_read_lines=\874 self.max_read_lines,875 verbose=self.verbose)861 self.file_pointer) = _read_csv_file_blocking(self.file_pointer, 862 self.header[:], 863 max_read_lines= \ 864 self.max_read_lines, 865 verbose= \ 866 self.verbose) 876 867 877 868 # Check that the zones haven't changed. … … 880 871 self.blocking_georef = geo_ref 881 872 elif self.blocking_georef is not None: 882 msg = 'Geo reference given, then not given.'883 msg += ' This should not happen.'873 msg = ('Geo reference given, then not given.' 874 ' This should not happen.') 884 875 raise ValueError, msg 885 876 geo = Geospatial_data(pointlist, att_dict, geo_ref) … … 899 890 del self.file_pointer 900 891 # This should only be if there is a format error 901 msg = 'Could not open file %s. \n' % self.file_name902 msg += Error_message['IOError']892 msg = ('Could not open file %s.\n%s' 893 % (self.file_name, Error_message['IOError'])) 903 894 raise SyntaxError, msg 904 895 return geo 905 906 896 907 897 ##################### Error messages ########### 908 898 Error_message = {} 909 899 Em = Error_message 910 Em['IOError'] = "NOTE: The format for a comma separated .txt/.csv file is:\n"911 Em['IOError'] += " 1st line: [column names]\n" 912 Em['IOError'] += " other lines: [x value], [y value], [attributes]\n" 913 Em['IOError'] += "\n" 914 Em['IOError'] += " for example:\n" 915 Em['IOError'] += " x, y, elevation, friction\n" 916 Em['IOError'] += " 0.6, 0.7, 4.9, 0.3\n" 917 Em['IOError'] += " 1.9, 2.8, 5, 0.3\n" 918 Em['IOError'] += " 2.7, 2.4, 5.2, 0.3\n" 919 Em['IOError'] += "\n" 920 Em['IOError'] += "The first two columns are assumed to be x, y coordinates.\n" 921 Em['IOError'] += "The attribute values must be numeric.\n" 900 Em['IOError'] = ('NOTE: The format for a comma separated .txt/.csv file is:\n' 901 ' 1st line: [column names]\n' 902 ' other lines: [x value], [y value], [attributes]\n' 903 '\n' 904 ' for example:\n' 905 ' x, y, elevation, friction\n' 906 ' 0.6, 0.7, 4.9, 0.3\n' 907 ' 1.9, 2.8, 5, 0.3\n' 908 ' 2.7, 2.4, 5.2, 0.3\n' 909 '\n' 910 'The first two columns are assumed to be x, y coordinates.\n' 911 'The attribute values must be numeric.\n') 922 912 923 913 ## … … 936 926 937 927 if geo_reference is not None: 938 msg = "A georeference is specified yet latitude and longitude " \939 "are also specified!"928 msg = ('A georeference is specified yet latitude and longitude ' 929 'are also specified!') 940 930 raise ValueError, msg 941 931 942 932 if data_points is not None and not points_are_lats_longs: 943 msg = "Data points are specified yet latitude and longitude are " \944 "also specified."933 msg = ('Data points are specified yet latitude and longitude are ' 934 'also specified.') 945 935 raise ValueError, msg 946 936 … … 983 973 dic['attributelist']['elevation'] = [[7.0,5.0]] 984 974 """ 985 986 from Scientific.IO.NetCDF import NetCDFFile987 975 988 976 if verbose: print 'Reading ', file_name … … 1127 1115 if len(header) != len(numbers): 1128 1116 file_pointer.close() 1129 msg = "File load error. " \1130 "There might be a problem with the file header."1117 msg = ('File load error. ' 1118 'There might be a problem with the file header.') 1131 1119 raise SyntaxError, msg 1132 1120 for i,n in enumerate(numbers): 1133 1121 n.strip() 1134 1122 if n != '\n' and n != '': 1135 #attributes.append(float(n))1136 1123 att_dict.setdefault(header[i],[]).append(float(n)) 1137 1124 except ValueError: … … 1174 1161 # @note Will throw IOError and AttributeError exceptions. 1175 1162 def _read_pts_file_header(fid, verbose=False): 1176 """Read the geo_reference and number_of_points from a .pts file"""1163 '''Read the geo_reference and number_of_points from a .pts file''' 1177 1164 1178 1165 keys = fid.variables.keys() … … 1202 1189 # @return Tuple of (pointlist, attributes). 1203 1190 def _read_pts_file_blocking(fid, start_row, fin_row, keys): 1204 """Read the body of a .csv file."""1191 '''Read the body of a .csv file.''' 1205 1192 1206 1193 pointlist = num.array(fid.variables['points'][start_row:fin_row]) … … 1240 1227 """ 1241 1228 1242 from Scientific.IO.NetCDF import NetCDFFile1243 1244 1229 # NetCDF file definition 1245 1230 outfile = NetCDFFile(file_name, netcdf_mode_w) … … 1256 1241 1257 1242 # Variable definition 1258 outfile.createVariable('points', netcdf_float, ('number_of_points',1259 1243 outfile.createVariable('points', netcdf_float, 1244 ('number_of_points', 'number_of_dimensions')) 1260 1245 1261 1246 # create variables … … 1385 1370 """Convert points_dictionary to geospatial data object""" 1386 1371 1387 msg = 'Points dictionary must have key pointlist'1372 msg = "Points dictionary must have key 'pointlist'" 1388 1373 assert points_dictionary.has_key('pointlist'), msg 1389 1374 1390 msg = 'Points dictionary must have key attributelist'1375 msg = "Points dictionary must have key 'attributelist'" 1391 1376 assert points_dictionary.has_key('attributelist'), msg 1392 1377 … … 1398 1383 return Geospatial_data(points_dictionary['pointlist'], 1399 1384 points_dictionary['attributelist'], 1400 geo_reference =geo)1385 geo_reference=geo) 1401 1386 1402 1387 … … 1436 1421 # Sort of geo_reference and convert points 1437 1422 if geo_reference is None: 1438 geo = None # Geo_reference()1423 geo = None # Geo_reference() 1439 1424 else: 1440 1425 if isinstance(geo_reference, Geo_reference): … … 1572 1557 from anuga.fit_interpolate.benchmark_least_squares import mem_usage 1573 1558 1574 1575 1559 attribute_smoothed = 'elevation' 1576 1560 … … 1579 1563 mesh_file = 'temp.msh' 1580 1564 1581 if north_boundary is None or south_boundary is None \1582 or east_boundary is None or west_boundary is None:1565 if (north_boundary is None or south_boundary is None 1566 or east_boundary is None or west_boundary is None): 1583 1567 no_boundary = True 1584 1568 else: … … 1589 1573 raise Expection, msg 1590 1574 1591 poly_topo = [[east_boundary, south_boundary],1592 [east_boundary, north_boundary],1593 [west_boundary, north_boundary],1594 [west_boundary, south_boundary]]1575 poly_topo = [[east_boundary, south_boundary], 1576 [east_boundary, north_boundary], 1577 [west_boundary, north_boundary], 1578 [west_boundary, south_boundary]] 1595 1579 1596 1580 create_mesh_from_regions(poly_topo, … … 1622 1606 if alpha_list == None: 1623 1607 alphas = [0.001,0.01,100] 1624 #alphas = [0.000001, 0.00001, 0.0001, 0.001, 0.01, \1625 #0.1, 1.0, 10.0, 100.0,1000.0,10000.0]1608 #alphas = [0.000001, 0.00001, 0.0001, 0.001, 0.01, 1609 # 0.1, 1.0, 10.0, 100.0,1000.0,10000.0] 1626 1610 else: 1627 1611 alphas = alpha_list … … 1647 1631 # add G_other data to domains with different alphas 1648 1632 if verbose: 1649 print '\n Calculating domain and mesh for Alpha =', alpha, '\n'1633 print '\nCalculating domain and mesh for Alpha =', alpha, '\n' 1650 1634 domain = Domain(mesh_file, use_cache=cache, verbose=verbose) 1651 1635 if verbose: print domain.statistics() … … 1671 1655 sample_cov = cov(elevation_sample) 1672 1656 ele_cov = cov(elevation_sample - elevation_predicted) 1673 normal_cov[i,:] = [alpha, ele_cov / sample_cov]1657 normal_cov[i,:] = [alpha, ele_cov / sample_cov] 1674 1658 1675 1659 if verbose: … … 1694 1678 print 'Final results:' 1695 1679 for i, alpha in enumerate(alphas): 1696 print 'covariance for alpha %s = %s ' \1697 % (normal_cov[i][0], normal_cov[i][1])1698 print '\n Optimal alpha is: %s ' \1699 % normal_cov_new[(num.argmin(normal_cov_new, axis=0))[1], 0]1680 print ('covariance for alpha %s = %s ' 1681 % (normal_cov[i][0], normal_cov[i][1])) 1682 print ('\nOptimal alpha is: %s ' 1683 % normal_cov_new[(num.argmin(normal_cov_new, axis=0))[1], 0]) 1700 1684 1701 1685 # covariance and optimal alpha … … 1779 1763 from anuga.fit_interpolate.benchmark_least_squares import mem_usage 1780 1764 1781 1782 1765 attribute_smoothed = 'elevation' 1783 1766 … … 1785 1768 mesh_file = 'temp.msh' 1786 1769 1787 if north_boundary is None or south_boundary is None \1788 or east_boundary is None or west_boundary is None:1770 if (north_boundary is None or south_boundary is None 1771 or east_boundary is None or west_boundary is None): 1789 1772 no_boundary = True 1790 1773 else: … … 1795 1778 raise Expection, msg 1796 1779 1797 poly_topo = [[east_boundary, south_boundary],1798 [east_boundary, north_boundary],1799 [west_boundary, north_boundary],1800 [west_boundary, south_boundary]]1780 poly_topo = [[east_boundary, south_boundary], 1781 [east_boundary, north_boundary], 1782 [west_boundary, north_boundary], 1783 [west_boundary, south_boundary]] 1801 1784 1802 1785 create_mesh_from_regions(poly_topo, … … 1822 1805 points = G_small.get_data_points() 1823 1806 1824 # FIXME: Remove points outside boundary polygon1825 # print 'new point',len(points)1826 #1827 # new_points=[]1828 # new_points=array([],dtype=float)1829 # new_points=resize(new_points,(len(points),2))1830 # print "BOUNDARY", boundary_poly1831 # for i,point in enumerate(points):1832 # if is_inside_polygon(point,boundary_poly, verbose=True):1833 # new_points[i] = point1834 # print"WOW",i,new_points[i]1835 # points = new_points1836 1837 1807 if verbose: print "Number of points in sample to compare: ", len(points) 1838 1808 1839 1809 if alpha_list == None: 1840 1810 alphas = [0.001,0.01,100] 1841 #alphas = [0.000001, 0.00001, 0.0001, 0.001, 0.01, \1842 #0.1, 1.0, 10.0, 100.0,1000.0,10000.0]1811 #alphas = [0.000001, 0.00001, 0.0001, 0.001, 0.01, 1812 # 0.1, 1.0, 10.0, 100.0,1000.0,10000.0] 1843 1813 else: 1844 1814 alphas = alpha_list … … 1851 1821 # add G_other data to domains with different alphas 1852 1822 if verbose: 1853 print '\n Calculating domain and mesh for Alpha =', alpha, '\n'1823 print '\nCalculating domain and mesh for Alpha =', alpha, '\n' 1854 1824 domain = Domain(mesh_file, use_cache=cache, verbose=verbose) 1855 1825 if verbose: print domain.statistics() … … 1878 1848 if verbose: 1879 1849 print 'Determine difference between predicted results and actual data' 1850 1880 1851 for i, alpha in enumerate(domains): 1881 1852 if verbose: print'Alpha =', alpha -
branches/numpy/anuga/geospatial_data/test_geospatial_data.py
r6410 r6428 341 341 P = G.get_data_points(absolute=True) 342 342 343 assert num.allclose(P, num.concatenate( (P1,P2) ))343 assert num.allclose(P, num.concatenate((P1,P2), axis=0)) #??default# 344 344 msg = ('P=\n%s\nshould be close to\n' 345 345 '[[2.0, 4.1], [4.0, 7.3],\n' … … 389 389 P = G.get_data_points(absolute=True) 390 390 391 assert num.allclose(P, num.concatenate((points1, points2) ))391 assert num.allclose(P, num.concatenate((points1, points2), axis=0)) #??default# 392 392 393 393 def test_add_with_None(self): -
branches/numpy/anuga/load_mesh/loadASCII.py
r6410 r6428 66 66 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 67 67 from anuga.config import netcdf_float, netcdf_char, netcdf_int 68 from anuga.utilities.system_tools import * 68 69 69 70 from Scientific.IO.NetCDF import NetCDFFile … … 624 625 num.array(mesh['vertex_attributes'], num.float) 625 626 mesh['vertex_attribute_titles'] = \ 626 num.array( mesh['vertex_attribute_titles'], num.character)627 num.array(string_to_char(mesh['vertex_attribute_titles']), num.character) 627 628 mesh['segments'] = num.array(mesh['segments'], IntType) 628 mesh['segment_tags'] = num.array(mesh['segment_tags'], num.character) 629 mesh['segment_tags'] = num.array(string_to_char(mesh['segment_tags']), 630 num.character) 629 631 mesh['triangles'] = num.array(mesh['triangles'], IntType) 630 mesh['triangle_tags'] = num.array(mesh['triangle_tags']) 632 mesh['triangle_tags'] = num.array(string_to_char(mesh['triangle_tags']), 633 num.character) 631 634 mesh['triangle_neighbors'] = \ 632 635 num.array(mesh['triangle_neighbors'], IntType) … … 637 640 mesh['outline_segments'] = num.array(mesh['outline_segments'], IntType) 638 641 mesh['outline_segment_tags'] = \ 639 num.array( mesh['outline_segment_tags'], num.character)642 num.array(string_to_char(mesh['outline_segment_tags']), num.character) 640 643 mesh['holes'] = num.array(mesh['holes'], num.float) 641 644 mesh['regions'] = num.array(mesh['regions'], num.float) 642 mesh['region_tags'] = num.array( mesh['region_tags'], num.character)645 mesh['region_tags'] = num.array(string_to_char(mesh['region_tags']), num.character) 643 646 mesh['region_max_areas'] = num.array(mesh['region_max_areas'], num.float) 644 647 … … 697 700 ('num_of_segments', 'num_of_segment_ends')) 698 701 outfile.variables['segments'][:] = mesh['segments'] 699 if mesh['segment_tags'].shape[ 1] > 0:702 if mesh['segment_tags'].shape[0] > 0: 700 703 outfile.createDimension('num_of_segment_tag_chars', 701 704 mesh['segment_tags'].shape[1]) … … 747 750 'num_of_segment_ends')) 748 751 outfile.variables['outline_segments'][:] = mesh['outline_segments'] 749 if (mesh['outline_segment_tags'].shape[1] > 0):752 if mesh['outline_segment_tags'].shape[1] > 0: 750 753 outfile.createDimension('num_of_outline_segment_tag_chars', 751 754 mesh['outline_segment_tags'].shape[1]) … … 817 820 try: 818 821 titles = fid.variables['vertex_attribute_titles'][:] 819 for i, title in enumerate(titles): 820 mesh['vertex_attribute_titles'].append(titles[i].tostring().strip()) 821 except KeyError: 822 mesh['vertex_attribute_titles'] = [x.tostring().strip() for x in titles] 823 except: 822 824 pass 823 825 … … 827 829 mesh['segments'] = num.array([], num.int) #array default# 828 830 829 mesh['segment_tags'] = []831 mesh['segment_tags'] = [] 830 832 try: 831 833 tags = fid.variables['segment_tags'][:] 832 for i, tag in enumerate(tags): 833 mesh['segment_tags'].append(tags[i].tostring().strip()) 834 except KeyError: 835 for ob in mesh['segments']: 836 mesh['segment_tags'].append('') 834 mesh['segment_tags'] = [x.tostring().strip() for x in tags] 835 except: 836 pass 837 837 838 838 try: … … 846 846 try: 847 847 tags = fid.variables['triangle_tags'][:] 848 for i, tag in enumerate(tags): 849 mesh['triangle_tags'].append(tags[i].tostring().strip()) 848 mesh['triangle_tags'] = [x.tostring().strip() for x in tags] 850 849 except KeyError: 851 850 for ob in mesh['triangles']: -
branches/numpy/anuga/load_mesh/test_loadASCII.py
r6410 r6428 209 209 os.remove(fileName) 210 210 dict = self.dict 211 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_ msh_file')211 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_tsh_file') 212 212 213 213 def test_read_write_tsh_fileII(self): … … 227 227 os.remove(fileName) 228 228 dict = self.blank_dict 229 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_ msh_fileIII')229 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_tsh_fileIII') 230 230 231 231 def test_read_write_tsh_file4(self): … … 236 236 os.remove(fileName) 237 237 dict = self.seg_dict 238 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_ msh_file4')238 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_tsh_file4') 239 239 240 240 def test_read_write_tsh_file5(self): … … 244 244 loaded_dict = import_mesh_file(fileName) 245 245 dict = self.triangle_tags_dict 246 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_ msh_file5')246 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_tsh_file5') 247 247 os.remove(fileName) 248 248 … … 253 253 loaded_dict = import_mesh_file(fileName) 254 254 dict = self.tri_dict 255 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_ msh_file6')255 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_tsh_file6') 256 256 os.remove(fileName) 257 257 … … 312 312 ############### .MSH ########## 313 313 314 def test_read_write_msh_file (self):314 def test_read_write_msh_file1(self): 315 315 dict = self.dict.copy() 316 316 fileName = tempfile.mktemp('.msh') … … 319 319 os.remove(fileName) 320 320 dict = self.dict 321 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file ')321 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file1') 322 322 323 323 def test_read_write_msh_fileII(self): … … 399 399 num.array(loaded_dict['segments'])) 400 400 401 self.failUnlessEqual(dict['triangle_tags'], loaded_dict['triangle_tags']) 402 401 403 for ob, ldob in map(None, dict['triangle_tags'], 402 404 loaded_dict['triangle_tags']): 405 msg = ('ob=\n%s\nshould be same as ldob=\n%s' % (str(ob), str(ldob))) 403 406 self.failUnless(ob == ldob, 404 fail_string + ' failed !! Test triangle_tags')407 fail_string + ' failed\n' + msg) 405 408 406 409 # A bit hacky 407 self.failUnless( (loaded_dict['vertex_attributes'] ==408 dict['vertex_attributes']) or \409 (loaded_dict['vertex_attributes'] == None and \410 self.failUnless(num.alltrue(loaded_dict['vertex_attributes'] == 411 dict['vertex_attributes']) or 412 (loaded_dict['vertex_attributes'] == None and 410 413 dict['vertex_attributes'] == []), 411 414 fail_string + ' failed!! Test vertex_attributes') … … 416 419 for seg, ldseg in map(None, dict['segment_tags'], 417 420 loaded_dict['segment_tags']): 418 self.failUnless(seg == ldseg, 419 fail_string + ' failed!! Test 8') 421 msg = ('seg=\n"%s"\nshould be same as ldseg=\n"%s"' 422 % (str(seg), str(ldseg))) 423 self.failUnless(seg == ldseg, fail_string + ' failed\n' + msg) 420 424 421 425 dict_array = num.array(dict['vertex_attribute_titles']) … … 429 433 430 434 try: 435 msg = ("loaded_dict['geo_reference']=\n%s\n" 436 "should be same as dict['geo_reference']=%s" 437 % (str(loaded_dict['geo_reference']), 438 str(dict['geo_reference']))) 431 439 self.failUnless(loaded_dict['geo_reference'] == 432 440 dict['geo_reference'], 433 fail_string + ' failed !! Test geo_reference')441 fail_string + ' failed\n' + msg) 434 442 except KeyError: #??# 2 lines below?? 435 # self.failUnless(not dict.has_key('geo_reference' and 436 # loaded_dict['geo_reference'] == None), 437 # fail_string + ' failed!! Test geo_reference') 443 msg = ("'dict' has no key 'geo_reference' " 444 "but loaded_dict['geo_reference'] isn't None") 438 445 self.failUnless(not dict.has_key('geo_reference') and 439 446 loaded_dict['geo_reference'] == None, 440 fail_string + ' failed !! Test geo_reference')447 fail_string + ' failed\n' + msg) 441 448 442 449 ########################## BAD .MSH ########################## -
branches/numpy/anuga/shallow_water/test_data_manager.py
r6410 r6428 2795 2795 # Invoke interpolation for vertex points 2796 2796 points = num.concatenate( (x[:,num.newaxis],y[:,num.newaxis]), axis=1 ) 2797 points = num.ascontiguousarray(points) 2797 2798 sww2pts(self.domain.get_name(), 2798 2799 quantity = 'elevation', … … 10908 10909 domain.set_quantity('xmomentum', uh) 10909 10910 domain.set_boundary( {'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) 10910 10911 10911 for t in domain.evolve(yieldstep=1, finaltime = t_end): 10912 10912 pass … … 11337 11337 if __name__ == "__main__": 11338 11338 suite = unittest.makeSuite(Test_Data_Manager,'test') 11339 #suite = unittest.makeSuite(Test_Data_Manager,'test_get_maximum_inundation')11340 11339 11341 11340 # FIXME (Ole): This is the test that fails under Windows -
branches/numpy/anuga/shallow_water/test_smf.py
r6410 r6428 52 52 slide = slide_tsunami(length=len, depth=dep, slope=th, x0=x0, \ 53 53 width = wid, thickness=thk, kappa=kappa, kappad=kappad, \ 54 54 verbose=False) 55 55 56 56 assert num.allclose(slide.a3D, 0.07775819) … … 111 111 slide = slide_tsunami(length, dep, th, x0, y0, \ 112 112 wid, thk, kappa, kappad, \ 113 113 domain=domain,verbose=False) 114 114 115 115 domain.set_quantity('stage', slide) 116 117 116 stage = domain.get_quantity('stage') 117 w = stage.get_values() 118 118 119 ## 119 ## check = [[-0.0 -0.0 -0.0], 120 120 ## [-.189709745 -517.877716 -0.0], 121 121 ## [-0.0 -0.0 -2.7695931e-08], … … 126 126 ## [-0.0 -0.0 -0.0]] 127 127 128 assert num.allclose( min(min(w)), -517.877771593)129 assert num.allclose( max(max(w)), 0.0)128 assert num.allclose(num.min(w), -517.877771593) 129 assert num.allclose(num.max(w), 0.0) 130 130 assert num.allclose(slide.a3D, 518.38797486) 131 131 -
branches/numpy/anuga/utilities/numerical_tools.py
r6304 r6428 284 284 285 285 n = num.searchsorted(num.sort(a), bins) 286 n = num.concatenate( [n, [len(a)]] )286 n = num.concatenate([n, [len(a)]], axis=0) #??default# 287 287 288 288 hist = n[1:]-n[:-1] -
branches/numpy/anuga/utilities/system_tools.py
r6415 r6428 294 294 '''Convert 1-D list of strings to 2-D list of chars.''' 295 295 296 if not l: 297 return [] 298 299 if l == ['']: 300 l = [' '] 301 296 302 maxlen = reduce(max, map(len, l)) 297 303 ll = [x.ljust(maxlen) for x in l] -
branches/numpy/anuga/utilities/test_system_tools.py
r6415 r6428 5 5 import numpy as num 6 6 import zlib 7 import os 7 8 from os.path import join, split, sep 9 from Scientific.IO.NetCDF import NetCDFFile 8 10 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 9 from anuga.config import netcdf_float 11 from anuga.config import netcdf_float, netcdf_char, netcdf_int 10 12 11 13 … … 57 59 58 60 os.remove(tmp_name) 59 61 60 62 61 63 … … 74 76 75 77 os.remove(tmp_name) 76 78 77 79 # Binary NetCDF File X 2 (use mktemp's name) 78 80 … … 94 96 fid.variables['test_array'][:] = test_array 95 97 fid.close() 96 98 97 99 # Second file 98 100 filename2 = mktemp(suffix='.nc', dir='.') … … 103 105 fid.variables['test_array'][:] = test_array 104 106 fid.close() 105 106 107 108 107 109 checksum1 = compute_checksum(filename1) 108 110 checksum2 = compute_checksum(filename2) … … 125 127 if path == '': 126 128 path = '.' + sep 127 129 128 130 filename = path + sep + 'crc_test_file.png' 129 131 … … 190 192 191 193 MAX_CHARS = 10 192 MAX_ENTRIES = 10000 0194 MAX_ENTRIES = 10000 193 195 A_INT = ord('a') 194 196 Z_INT = ord('z') … … 208 210 self.failUnlessEqual(new_str_list, str_list) 209 211 212 # special test - input list is [''] 213 def test_string_to_char2(self): 214 # generate a special list shown bad in load_mesh testing 215 str_list = [''] 216 217 x = string_to_char(str_list) 218 new_str_list = char_to_string(x) 219 220 self.failUnlessEqual(new_str_list, str_list) 221 210 222 211 223 ################################################################################ … … 214 226 ################################################################################ 215 227 228 ## 229 # @brief Helper function to write a list of strings to a NetCDF file. 230 # @param filename Path to the file to write. 231 # @param l The list of strings to write. 232 def helper_write_msh_file(self, filename, l): 233 # open the NetCDF file 234 fd = NetCDFFile(filename, netcdf_mode_w) 235 fd.description = 'Test file - string arrays' 236 237 # convert list of strings to num.array 238 al = num.array(string_to_char(l), num.character) 239 240 # write the list 241 fd.createDimension('num_of_strings', al.shape[0]) 242 fd.createDimension('size_of_strings', al.shape[1]) 243 244 var = fd.createVariable('strings', netcdf_char, 245 ('num_of_strings', 'size_of_strings')) 246 var[:] = al 247 248 fd.close() 249 250 251 ## 252 # @brief Helper function to read a NetCDF file and return a list of strings. 253 # @param filename Path to the file to read. 254 # @return A list of strings from the file. 255 def helper_read_msh_file(self, filename): 256 fid = NetCDFFile(filename, netcdf_mode_r) 257 mesh = {} 258 259 # Get the 'strings' variable 260 strings = fid.variables['strings'][:] 261 262 fid.close() 263 264 return char_to_string(strings) 265 266 267 # test random strings to a NetCDF file 268 def test_string_to_netcdf(self): 269 import random 270 271 MAX_CHARS = 10 272 MAX_ENTRIES = 10000 273 274 A_INT = ord('a') 275 Z_INT = ord('z') 276 277 FILENAME = 'test.msh' 278 279 # generate some random strings in a list, with guaranteed lengths 280 str_list = ['x' * MAX_CHARS] # make first maximum length 281 for entry in xrange(MAX_ENTRIES): 282 length = random.randint(1, MAX_CHARS) 283 s = '' 284 for c in range(length): 285 s += chr(random.randint(A_INT, Z_INT)) 286 str_list.append(s) 287 288 self.helper_write_msh_file(FILENAME, str_list) 289 new_str_list = self.helper_read_msh_file(FILENAME) 290 291 self.failUnlessEqual(new_str_list, str_list) 292 os.remove(FILENAME) 293 294 # special test - list [''] to a NetCDF file 295 def test_string_to_netcdf2(self): 296 FILENAME = 'test.msh' 297 298 # generate some random strings in a list, with guaranteed lengths 299 str_list = [''] 300 301 self.helper_write_msh_file(FILENAME, str_list) 302 new_str_list = self.helper_read_msh_file(FILENAME) 303 304 self.failUnlessEqual(new_str_list, str_list) 305 os.remove(FILENAME) 306 307 # print ('test_string_to_char: str_list=%s, new_str_list=%s' 308 # % (str(str_list), str(new_str_list))) 216 309 ################################################################################ 217 310 218 311 if __name__ == "__main__": 219 #suite = unittest.makeSuite(Test_system_tools, 'test') 220 suite = unittest.makeSuite(Test_system_tools, 'test_string_to_char') 312 suite = unittest.makeSuite(Test_system_tools, 'test') 221 313 runner = unittest.TextTestRunner() 222 314 runner.run(suite)
Note: See TracChangeset
for help on using the changeset viewer.