Changeset 6304 for branches/numpy/anuga
- Timestamp:
- Feb 10, 2009, 11:11:04 AM (16 years ago)
- Location:
- branches/numpy
- Files:
-
- 1 deleted
- 93 edited
- 1 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/numpy/anuga/abstract_2d_finite_volumes/domain.py
r6246 r6304 31 31 from quantity import Quantity 32 32 33 import Numericas num33 import numpy as num 34 34 35 35 … … 185 185 buffer_shape = self.full_send_dict[key][0].shape[0] 186 186 self.full_send_dict[key].append(num.zeros((buffer_shape, self.nsys), 187 num. Float))187 num.float)) 188 188 189 189 for key in self.ghost_recv_dict: 190 190 buffer_shape = self.ghost_recv_dict[key][0].shape[0] 191 191 self.ghost_recv_dict[key].append(num.zeros((buffer_shape, self.nsys), 192 num. Float))192 num.float)) 193 193 194 194 # Setup cell full flag … … 197 197 N = len(self) #number_of_elements 198 198 self.number_of_elements = N 199 self.tri_full_flag = num.ones(N, num. Int)199 self.tri_full_flag = num.ones(N, num.int) 200 200 for i in self.ghost_recv_dict.keys(): 201 201 for id in self.ghost_recv_dict[i][0]: … … 258 258 # (boolean) array, to be used during the flux calculation. 259 259 N = len(self) # Number_of_triangles 260 self.already_computed_flux = num.zeros((N, 3), num. Int)260 self.already_computed_flux = num.zeros((N, 3), num.int) 261 261 262 262 # Storage for maximal speeds computed for each triangle by 263 263 # compute_fluxes. 264 264 # This is used for diagnostics only (reset at every yieldstep) 265 self.max_speed = num.zeros(N, num. Float)265 self.max_speed = num.zeros(N, num.float) 266 266 267 267 if mesh_filename is not None: … … 375 375 raise Exception, msg 376 376 377 q = num.zeros(len(self.conserved_quantities), num. Float)377 q = num.zeros(len(self.conserved_quantities), num.float) 378 378 379 379 for i, name in enumerate(self.conserved_quantities): … … 447 447 448 448 name: Name of quantity 449 value: Compatible list, Numeric array, const or function (see below)449 value: Compatible list, numeric array, const or function (see below) 450 450 451 451 The values will be stored in elements following their internal ordering. … … 879 879 880 880 msg += '------------------------------------------------\n' 881 msg += ' Speeds in [%f, %f]\n' % (min(self.max_speed ),882 max(self.max_speed ))881 msg += ' Speeds in [%f, %f]\n' % (min(self.max_speed.flat), 882 max(self.max_speed.flat)) 883 883 msg += ' Histogram:\n' 884 884 … … 892 892 else: 893 893 # Closed upper interval 894 hi = max(self.max_speed )894 hi = max(self.max_speed.flat) 895 895 msg += ' [%f, %f]: %d\n' % (lo, hi, count) 896 896 897 N = len(self.max_speed )897 N = len(self.max_speed.flat) 898 898 if N > 10: 899 899 msg += ' Percentiles (10%):\n' … … 1357 1357 self.number_of_steps = 0 1358 1358 self.number_of_first_order_steps = 0 1359 self.max_speed = num.zeros(N, num. Float)1359 self.max_speed = num.zeros(N, num.float) 1360 1360 1361 1361 ## … … 1626 1626 # momentum 1627 1627 if self.protect_against_isolated_degenerate_timesteps is True and \ 1628 self.max_speed> 10.0: # FIXME (Ole): Make this configurable1628 num.max(self.max_speed) > 10.0: # FIXME (Ole): Make this configurable 1629 1629 1630 1630 # Setup 10 bins for speed histogram … … 1641 1641 1642 1642 # Find triangles in last bin 1643 # FIXME - speed up using Numeric1643 # FIXME - speed up using numeric package 1644 1644 d = 0 1645 1645 for i in range(self.number_of_full_triangles): -
branches/numpy/anuga/abstract_2d_finite_volumes/ermapper_grids.py
r6161 r6304 2 2 3 3 # from os import open, write, read 4 import Numericas num5 6 celltype_map = {'IEEE4ByteReal': num. Float32, 'IEEE8ByteReal': num.Float64}4 import numpy as num 5 6 celltype_map = {'IEEE4ByteReal': num.float32, 'IEEE8ByteReal': num.float64} 7 7 8 8 … … 11 11 write_ermapper_grid(ofile, data, header = {}): 12 12 13 Function to write a 2D Numeric array to an ERMapper grid. There are a series of conventions adopted within13 Function to write a 2D numeric array to an ERMapper grid. There are a series of conventions adopted within 14 14 this code, specifically: 15 15 1) The registration coordinate for the data is the SW (or lower-left) corner of the data 16 16 2) The registration coordinates refer to cell centres 17 3) The data is a 2D Numeric array with the NW-most data in element (0,0) and the SE-most data in element (N,M)17 3) The data is a 2D numeric array with the NW-most data in element (0,0) and the SE-most data in element (N,M) 18 18 where N is the last line and M is the last column 19 19 4) There has been no testng of the use of a rotated grid. Best to keep data in an NS orientation … … 163 163 return header 164 164 165 def write_ermapper_data(grid, ofile, data_format = num.Float32):165 def write_ermapper_data(grid, ofile, data_format=num.float32): 166 166 167 167 … … 193 193 194 194 195 def read_ermapper_data(ifile, data_format = num. Float32):195 def read_ermapper_data(ifile, data_format = num.float32): 196 196 # open input file in a binary format and read the input string 197 197 fid = open(ifile,'rb') … … 199 199 fid.close() 200 200 201 # convert input string to required format (Note default format is num. Float32)201 # convert input string to required format (Note default format is num.float32) 202 202 grid_as_float = num.fromstring(input_string,data_format) 203 203 return grid_as_float -
branches/numpy/anuga/abstract_2d_finite_volumes/general_mesh.py
r6191 r6304 1 import Numericas num1 import numpy as num 2 2 3 3 from anuga.coordinate_transforms.geo_reference import Geo_reference … … 10 10 which is represented as a coordinate set (x,y). 11 11 Vertices from different triangles can point to the same node. 12 The nodes are implemented as an Nx2 Numeric array containing the12 The nodes are implemented as an Nx2 numeric array containing the 13 13 x and y coordinates. 14 14 … … 19 19 where 20 20 21 nodes is either a list of 2-tuples or an Nx2 Numeric array of21 nodes is either a list of 2-tuples or an Nx2 numeric array of 22 22 floats representing all x, y coordinates in the mesh. 23 23 24 triangles is either a list of 3-tuples or an Mx3 Numeric array of24 triangles is either a list of 3-tuples or an Mx3 numeric array of 25 25 integers representing indices of all vertices in the mesh. 26 26 Each vertex is identified by its index i in [0, N-1]. … … 68 68 69 69 nodes: x,y coordinates represented as a sequence of 2-tuples or 70 a Nx2 Numeric array of floats.70 a Nx2 numeric array of floats. 71 71 72 triangles: sequence of 3-tuples or Mx3 Numeric array of72 triangles: sequence of 3-tuples or Mx3 numeric array of 73 73 non-negative integers representing indices into 74 74 the nodes array. … … 88 88 if verbose: print 'General_mesh: Building basic mesh structure in ANUGA domain' 89 89 90 self.triangles = num.array(triangles, num. Int)91 self.nodes = num.array(nodes, num. Float)90 self.triangles = num.array(triangles, num.int) 91 self.nodes = num.array(nodes, num.float) 92 92 93 93 … … 125 125 126 126 # Input checks 127 msg = 'Triangles must an Mx3 Numeric array or a sequence of 3-tuples. '127 msg = 'Triangles must an Mx3 numeric array or a sequence of 3-tuples. ' 128 128 msg += 'The supplied array has the shape: %s'\ 129 129 %str(self.triangles.shape) 130 130 assert len(self.triangles.shape) == 2, msg 131 131 132 msg = 'Nodes must an Nx2 Numeric array or a sequence of 2-tuples'132 msg = 'Nodes must an Nx2 numeric array or a sequence of 2-tuples' 133 133 msg += 'The supplied array has the shape: %s'\ 134 134 %str(self.nodes.shape) … … 144 144 max(self.nodes[:,0]), max(self.nodes[:,1]) ] 145 145 146 self.xy_extent = num.array(xy_extent, num. Float)146 self.xy_extent = num.array(xy_extent, num.float) 147 147 148 148 149 149 # Allocate space for geometric quantities 150 self.normals = num.zeros((N, 6), num. Float)151 self.areas = num.zeros(N, num. Float)152 self.edgelengths = num.zeros((N, 3), num. Float)150 self.normals = num.zeros((N, 6), num.float) 151 self.areas = num.zeros(N, num.float) 152 self.edgelengths = num.zeros((N, 3), num.float) 153 153 154 154 # Get x,y coordinates for all triangles and store … … 185 185 # - Stored as six floats n0x,n0y,n1x,n1y,n2x,n2y per triangle 186 186 187 n0 = num.array([x2 - x1, y2 - y1], num. Float)187 n0 = num.array([x2 - x1, y2 - y1], num.float) 188 188 l0 = num.sqrt(num.sum(n0**2)) 189 189 190 n1 = num.array([x0 - x2, y0 - y2], num. Float)190 n1 = num.array([x0 - x2, y0 - y2], num.float) 191 191 l1 = num.sqrt(num.sum(n1**2)) 192 192 193 n2 = num.array([x1 - x0, y1 - y0], num. Float)193 n2 = num.array([x1 - x0, y1 - y0], num.float) 194 194 l2 = num.sqrt(num.sum(n2**2)) 195 195 … … 275 275 if not self.geo_reference.is_absolute(): 276 276 return V + num.array([self.geo_reference.get_xllcorner(), 277 self.geo_reference.get_yllcorner()], num. Float)277 self.geo_reference.get_yllcorner()], num.float) 278 278 else: 279 279 return V … … 317 317 if absolute is True and not self.geo_reference.is_absolute(): 318 318 offset=num.array([self.geo_reference.get_xllcorner(), 319 self.geo_reference.get_yllcorner()], num. Float)319 self.geo_reference.get_yllcorner()], num.float) 320 320 return num.array([V[i3,:]+offset, 321 321 V[i3+1,:]+offset, 322 V[i3+2,:]+offset], num. Float)322 V[i3+2,:]+offset], num.float) 323 323 else: 324 return num.array([V[i3,:], V[i3+1,:], V[i3+2,:]], num. Float)324 return num.array([V[i3,:], V[i3+1,:], V[i3+2,:]], num.float) 325 325 326 326 … … 349 349 350 350 M = self.number_of_triangles 351 vertex_coordinates = num.zeros((3*M, 2), num. Float)351 vertex_coordinates = num.zeros((3*M, 2), num.float) 352 352 353 353 for i in range(M): … … 409 409 K = 3*M # Total number of unique vertices 410 410 411 T = num.reshape(num.arange(K, typecode=num.Int), (M,3))411 T = num.reshape(num.arange(K, dtype=num.int), (M,3)) 412 412 413 413 return T … … 416 416 417 417 def get_unique_vertices(self, indices=None): 418 """FIXME(Ole): This function needs a docstring 419 """ 418 """FIXME(Ole): This function needs a docstring""" 419 420 420 triangles = self.get_triangles(indices=indices) 421 421 unique_verts = {} 422 422 for triangle in triangles: 423 unique_verts[triangle[0]] = 0 424 unique_verts[triangle[1]] = 0 425 unique_verts[triangle[2]] = 0 423 #print 'triangle(%s)=%s' % (type(triangle), str(triangle)) 424 unique_verts[triangle[0]] = 0 425 unique_verts[triangle[1]] = 0 426 unique_verts[triangle[2]] = 0 426 427 return unique_verts.keys() 427 428 … … 452 453 triangle_list.append( (volume_id, vertex_id) ) 453 454 454 triangle_list = num.array(triangle_list, num. Int) #array default#455 triangle_list = num.array(triangle_list, num.int) #array default# 455 456 else: 456 457 # Get info for all nodes recursively. … … 529 530 530 531 # Count number of triangles per node 531 number_of_triangles_per_node = num.zeros(self.number_of_full_nodes) 532 number_of_triangles_per_node = num.zeros(self.number_of_full_nodes, 533 num.int) #array default# 532 534 for volume_id, triangle in enumerate(self.get_triangles()): 533 535 for vertex_id in triangle: … … 536 538 # Allocate space for inverted structure 537 539 number_of_entries = num.sum(number_of_triangles_per_node) 538 vertex_value_indices = num.zeros(number_of_entries )540 vertex_value_indices = num.zeros(number_of_entries, num.int) #array default# 539 541 540 542 # Register (triangle, vertex) indices for each node -
branches/numpy/anuga/abstract_2d_finite_volumes/generic_boundary_conditions.py
r6174 r6304 8 8 from anuga.fit_interpolate.interpolate import Modeltime_too_early 9 9 10 import Numericas num10 import numpy as num 11 11 12 12 … … 69 69 raise Exception, msg 70 70 71 self.conserved_quantities=num.array(conserved_quantities, num. Float)71 self.conserved_quantities=num.array(conserved_quantities, num.float) 72 72 73 73 def __repr__(self): … … 99 99 100 100 try: 101 q = num.array(q, num. Float)101 q = num.array(q, num.float) 102 102 except: 103 103 msg = 'Return value from time boundary function could ' 104 msg += 'not be converted into a Numeric array of floats.\n'104 msg += 'not be converted into a numeric array of floats.\n' 105 105 msg += 'Specified function should return either list or array.\n' 106 106 msg += 'I got %s' %str(q) … … 180 180 181 181 if verbose: print 'Find midpoint coordinates of entire boundary' 182 self.midpoint_coordinates = num.zeros((len(domain.boundary), 2), num. Float)182 self.midpoint_coordinates = num.zeros((len(domain.boundary), 2), num.float) 183 183 boundary_keys = domain.boundary.keys() 184 184 … … 200 200 201 201 # Compute midpoints 202 if edge_id == 0: m = num.array([(x1 + x2)/2, (y1 + y2)/2], num. Float)203 if edge_id == 1: m = num.array([(x0 + x2)/2, (y0 + y2)/2], num. Float)204 if edge_id == 2: m = num.array([(x1 + x0)/2, (y1 + y0)/2], num. Float)202 if edge_id == 0: m = num.array([(x1 + x2)/2, (y1 + y2)/2], num.float) 203 if edge_id == 1: m = num.array([(x0 + x2)/2, (y0 + y2)/2], num.float) 204 if edge_id == 2: m = num.array([(x1 + x0)/2, (y1 + y0)/2], num.float) 205 205 206 206 # Convert to absolute UTM coordinates … … 309 309 # See http://docs.python.org/lib/warning-filter.html 310 310 self.default_boundary_invoked = True 311 312 313 if res == NAN: 311 312 if num.any(res == NAN): 314 313 x,y=self.midpoint_coordinates[i,:] 315 314 msg = 'NAN value found in file_boundary at ' -
branches/numpy/anuga/abstract_2d_finite_volumes/mesh_factory.py
r6145 r6304 3 3 """ 4 4 5 import Numericas num5 import numpy as num 6 6 7 7 … … 94 94 index = Index(n,m) 95 95 96 points = num.zeros((Np, 2), num. Float)96 points = num.zeros((Np, 2), num.float) 97 97 98 98 for i in range(m+1): … … 106 106 107 107 108 elements = num.zeros((Nt, 3), num. Int)108 elements = num.zeros((Nt, 3), num.int) 109 109 boundary = {} 110 110 nt = -1 -
branches/numpy/anuga/abstract_2d_finite_volumes/neighbour_mesh.py
r6191 r6304 12 12 from math import pi, sqrt 13 13 14 import Numericas num14 import numpy as num 15 15 16 16 … … 24 24 coordinate set. 25 25 26 Coordinate sets are implemented as an N x 2 Numeric array containing26 Coordinate sets are implemented as an N x 2 numeric array containing 27 27 x and y coordinates. 28 28 … … 33 33 where 34 34 35 coordinates is either a list of 2-tuples or an Mx2 Numeric array of35 coordinates is either a list of 2-tuples or an Mx2 numeric array of 36 36 floats representing all x, y coordinates in the mesh. 37 37 38 triangles is either a list of 3-tuples or an Nx3 Numeric array of38 triangles is either a list of 3-tuples or an Nx3 numeric array of 39 39 integers representing indices of all vertices in the mesh. 40 40 Each vertex is identified by its index i in [0, M-1]. … … 76 76 """ 77 77 Build triangles from x,y coordinates (sequence of 2-tuples or 78 Mx2 Numeric array of floats) and triangles (sequence of 3-tuples79 or Nx3 Numeric array of non-negative integers).78 Mx2 numeric array of floats) and triangles (sequence of 3-tuples 79 or Nx3 numeric array of non-negative integers). 80 80 """ 81 81 … … 98 98 99 99 #Allocate space for geometric quantities 100 self.centroid_coordinates = num.zeros((N, 2), num. Float)101 102 self.radii = num.zeros(N, num. Float)103 104 self.neighbours = num.zeros((N, 3), num. Int)105 self.neighbour_edges = num.zeros((N, 3), num. Int)106 self.number_of_boundaries = num.zeros(N, num. Int)107 self.surrogate_neighbours = num.zeros((N, 3), num. Int)100 self.centroid_coordinates = num.zeros((N, 2), num.float) 101 102 self.radii = num.zeros(N, num.float) 103 104 self.neighbours = num.zeros((N, 3), num.int) 105 self.neighbour_edges = num.zeros((N, 3), num.int) 106 self.number_of_boundaries = num.zeros(N, num.int) 107 self.surrogate_neighbours = num.zeros((N, 3), num.int) 108 108 109 109 #Get x,y coordinates for all triangles and store … … 124 124 125 125 #Compute centroid 126 centroid = num.array([(x0 + x1 + x2)/3, (y0 + y1 + y2)/3], num. Float)126 centroid = num.array([(x0 + x1 + x2)/3, (y0 + y1 + y2)/3], num.float) 127 127 self.centroid_coordinates[i] = centroid 128 128 … … 133 133 134 134 #Midpoints 135 m0 = num.array([(x1 + x2)/2, (y1 + y2)/2], num. Float)136 m1 = num.array([(x0 + x2)/2, (y0 + y2)/2], num. Float)137 m2 = num.array([(x1 + x0)/2, (y1 + y0)/2], num. Float)135 m0 = num.array([(x1 + x2)/2, (y1 + y2)/2], num.float) 136 m1 = num.array([(x0 + x2)/2, (y0 + y2)/2], num.float) 137 m2 = num.array([(x1 + x0)/2, (y1 + y0)/2], num.float) 138 138 139 139 #The radius is the distance from the centroid of … … 394 394 #Check that all keys in given boundary exist 395 395 for tag in tagged_elements.keys(): 396 tagged_elements[tag] = num.array(tagged_elements[tag], num. Int)396 tagged_elements[tag] = num.array(tagged_elements[tag], num.int) 397 397 398 398 msg = 'Not all elements exist. ' … … 506 506 # Sanity check 507 507 if p0 is None: 508 raise Exception('Impossible')509 508 msg = 'Impossible: p0 is None!?' 509 raise Exception, msg 510 510 511 511 # Register potential paths from A to B … … 613 613 point_registry[tuple(p1)] = len(point_registry) 614 614 615 polygon.append(list(p1)) # De- Numeric each point :-)615 polygon.append(list(p1)) # De-numeric each point :-) 616 616 p0 = p1 617 617 … … 1139 1139 1140 1140 # Distances from line origin to the two intersections 1141 z0 = num.array([x0 - xi0, y0 - eta0], num. Float)1142 z1 = num.array([x1 - xi0, y1 - eta0], num. Float)1141 z0 = num.array([x0 - xi0, y0 - eta0], num.float) 1142 z1 = num.array([x1 - xi0, y1 - eta0], num.float) 1143 1143 d0 = num.sqrt(num.sum(z0**2)) 1144 1144 d1 = num.sqrt(num.sum(z1**2)) … … 1155 1155 # Normal direction: 1156 1156 # Right hand side relative to line direction 1157 vector = num.array([x1 - x0, y1 - y0], num. Float) # Segment vector1157 vector = num.array([x1 - x0, y1 - y0], num.float) # Segment vector 1158 1158 length = num.sqrt(num.sum(vector**2)) # Segment length 1159 normal = num.array([vector[1], -vector[0]], num. Float)/length1159 normal = num.array([vector[1], -vector[0]], num.float)/length 1160 1160 1161 1161 … … 1237 1237 assert isinstance(segment, Triangle_intersection), msg 1238 1238 1239 midpoint = num.sum(num.array(segment.segment, num. Float))/21239 midpoint = num.sum(num.array(segment.segment, num.float))/2 1240 1240 midpoints.append(midpoint) 1241 1241 -
branches/numpy/anuga/abstract_2d_finite_volumes/pmesh2domain.py
r6145 r6304 1 """Class pmesh2domain - Converting .tsh files to do amains1 """Class pmesh2domain - Converting .tsh files to domains 2 2 3 3 … … 8 8 9 9 import sys 10 11 import Numeric as num 12 13 14 def pmesh_instance_to_domain_instance(mesh, 15 DomainClass): 16 """ 17 Convert a pmesh instance/object into a domain instance. 18 19 Use pmesh_to_domain_instance to convert a mesh file to a domain instance. 20 """ 21 22 vertex_coordinates, vertices, tag_dict, vertex_quantity_dict \ 23 ,tagged_elements_dict, geo_reference = \ 24 pmesh_to_domain(mesh_instance=mesh) 10 import numpy as num 11 12 13 ## 14 # @brief Convert a pmesh instance to a domain instance. 15 # @param mesh The pmesh instance to convert. 16 # @param DomainClass The class to instantiate and return. 17 # @return The converted pmesh instance (as a 'DomainClass' instance). 18 def pmesh_instance_to_domain_instance(mesh, DomainClass): 19 """Convert a pmesh instance/object into a domain instance. 20 21 Uses pmesh_to_domain_instance to convert a mesh file to a domain instance. 22 """ 23 24 (vertex_coordinates, vertices, tag_dict, vertex_quantity_dict, 25 tagged_elements_dict, geo_reference) = pmesh_to_domain(mesh_instance=mesh) 26 27 # NOTE(Ole): This import cannot be at the module level 28 # due to mutual dependency with domain.py 29 from anuga.abstract_2d_finite_volumes.domain import Domain 30 31 # ensure that the required 'DomainClass' actually is an instance of Domain 32 msg = ('The class %s is not a subclass of the generic domain class %s' 33 % (DomainClass, Domain)) 34 assert issubclass(DomainClass, Domain), msg 35 36 # instantiate the result class 37 result = DomainClass(coordinates=vertex_coordinates, 38 vertices=vertices, 39 boundary=tag_dict, 40 tagged_elements=tagged_elements_dict, 41 geo_reference=geo_reference) 42 43 # set the water stage to be the elevation 44 if (vertex_quantity_dict.has_key('elevation') and 45 not vertex_quantity_dict.has_key('stage')): 46 vertex_quantity_dict['stage'] = vertex_quantity_dict['elevation'] 47 result.set_quantity_vertices_dict(vertex_quantity_dict) 48 49 return result 50 51 52 ## 53 # @brief Convert a mesh file to a Domain instance. 54 # @param file_name Name of the file to convert (TSH or MSH). 55 # @param DomainClass Class of return instance. 56 # @param use_cache True if caching is to be used. 57 # @param verbose True if this function is to be verbose. 58 # @return An instance of 'DomainClass' containing the file data. 59 def pmesh_to_domain_instance(file_name, DomainClass, use_cache=False, 60 verbose=False): 61 """Converts a mesh file(.tsh or .msh), to a Domain instance. 62 63 file_name is the name of the mesh file to convert, including the extension 64 65 DomainClass is the Class that will be returned. 66 It must be a subclass of Domain, with the same interface as domain. 67 68 use_cache: True means that caching is attempted for the computed domain. 69 """ 70 71 if use_cache is True: 72 from caching import cache 73 result = cache(_pmesh_to_domain_instance, (file_name, DomainClass), 74 dependencies=[file_name], verbose=verbose) 75 else: 76 result = apply(_pmesh_to_domain_instance, (file_name, DomainClass)) 77 78 return result 79 80 81 ## 82 # @brief Convert a mesh file to a Domain instance. 83 # @param file_name Name of the file to convert (TSH or MSH). 84 # @param DomainClass Class of return instance. 85 # @return The DomainClass instance containing the file data. 86 def _pmesh_to_domain_instance(file_name, DomainClass): 87 """Converts a mesh file(.tsh or .msh), to a Domain instance. 88 89 Internal function. See public interface pmesh_to_domain_instance for details 90 """ 91 92 (vertex_coordinates, vertices, tag_dict, vertex_quantity_dict, 93 tagged_elements_dict, geo_reference) = pmesh_to_domain(file_name=file_name) 25 94 26 95 # NOTE(Ole): This import cannot be at the module level due to mutual … … 28 97 from anuga.abstract_2d_finite_volumes.domain import Domain 29 98 30 31 32 33 msg = 'The class %s is not a subclass of the generic domain class %s'\ 34 %(DomainClass, Domain) 99 # ensure the required class is a subclass of Domain 100 msg = ('The class %s is not a subclass of the generic domain class %s' 101 % (DomainClass, Domain)) 35 102 assert issubclass(DomainClass, Domain), msg 36 37 103 38 104 domain = DomainClass(coordinates = vertex_coordinates, … … 42 108 geo_reference = geo_reference ) 43 109 44 # set the water stage to be the elevation 45 if vertex_quantity_dict.has_key('elevation') and not vertex_quantity_dict.has_key('stage'): 46 vertex_quantity_dict['stage'] = vertex_quantity_dict['elevation'] 47 48 domain.set_quantity_vertices_dict(vertex_quantity_dict) 49 #print "vertex_quantity_dict",vertex_quantity_dict 50 return domain 51 52 53 54 def pmesh_to_domain_instance(file_name, DomainClass, use_cache = False, verbose = False): 55 """ 56 Converts a mesh file(.tsh or .msh), to a Domain instance. 57 58 file_name is the name of the mesh file to convert, including the extension 59 60 DomainClass is the Class that will be returned. 61 It must be a subclass of Domain, with the same interface as domain. 62 63 use_cache: True means that caching is attempted for the computed domain. 64 """ 65 66 if use_cache is True: 67 from caching import cache 68 result = cache(_pmesh_to_domain_instance, (file_name, DomainClass), 69 dependencies = [file_name], 70 verbose = verbose) 71 72 else: 73 result = apply(_pmesh_to_domain_instance, (file_name, DomainClass)) 74 75 return result 76 77 78 79 80 def _pmesh_to_domain_instance(file_name, DomainClass): 81 """ 82 Converts a mesh file(.tsh or .msh), to a Domain instance. 83 84 Internal function. See public interface pmesh_to_domain_instance for details 85 """ 86 87 vertex_coordinates, vertices, tag_dict, vertex_quantity_dict, \ 88 tagged_elements_dict, geo_reference = \ 89 pmesh_to_domain(file_name=file_name) 90 91 92 # NOTE(Ole): This import cannot be at the module level due to mutual 93 # dependency with domain.py 94 from anuga.abstract_2d_finite_volumes.domain import Domain 95 96 97 msg = 'The class %s is not a subclass of the generic domain class %s'\ 98 %(DomainClass, Domain) 99 assert issubclass(DomainClass, Domain), msg 100 101 102 103 domain = DomainClass(coordinates = vertex_coordinates, 104 vertices = vertices, 105 boundary = tag_dict, 106 tagged_elements = tagged_elements_dict, 107 geo_reference = geo_reference ) 108 109 110 111 #FIXME (Ole): Is this really the right place to apply the a default 112 #value specific to the shallow water wave equation? 113 #The 'assert' above indicates that any subclass of Domain is acceptable. 114 #Suggestion - module shallow_water.py will eventually take care of this 115 #(when I get around to it) so it should be removed from here. 110 # FIXME (Ole): Is this really the right place to apply a default 111 # value specific to the shallow water wave equation? 112 # The 'assert' above indicates that any subclass of Domain is acceptable. 113 # Suggestion - module shallow_water.py will eventually take care of this 114 # (when I get around to it) so it should be removed from here. 116 115 117 116 # This doesn't work on the domain instance. 118 117 # This is still needed so -ve elevations don't cuase 'lakes' 119 118 # The fixme we discussed was to only create a quantity when its values 120 # are set.119 # are set. 121 120 # I think that's the way to go still 122 121 123 122 # set the water stage to be the elevation 124 if vertex_quantity_dict.has_key('elevation') and not vertex_quantity_dict.has_key('stage'): 123 if (vertex_quantity_dict.has_key('elevation') and 124 not vertex_quantity_dict.has_key('stage')): 125 125 vertex_quantity_dict['stage'] = vertex_quantity_dict['elevation'] 126 127 126 domain.set_quantity_vertices_dict(vertex_quantity_dict) 128 #print "vertex_quantity_dict",vertex_quantity_dict 127 129 128 return domain 130 129 131 130 132 def pmesh_to_domain(file_name=None, 133 mesh_instance=None, 134 use_cache=False, 131 ## 132 # @brief Convert pmesh file/instance to list(s) that can instantiate a Domain. 133 # @param file_name Path to file to convert. 134 # @param mesh_instance Instance to convert. 135 # @param use_cache True if we are to cache. 136 # @param verbose True if this function is to be verbose. 137 # @return ?? 138 def pmesh_to_domain(file_name=None, mesh_instance=None, use_cache=False, 135 139 verbose=False): 136 """ 137 Convert a pmesh file or a pmesh mesh instance to a bunch of lists 140 """Convert a pmesh file or a pmesh mesh instance to a bunch of lists 138 141 that can be used to instanciate a domain object. 139 142 … … 144 147 from caching import cache 145 148 result = cache(_pmesh_to_domain, (file_name, mesh_instance), 146 dependencies = [file_name], 147 verbose = verbose) 149 dependencies=[file_name], verbose=verbose) 148 150 149 151 else: … … 153 155 154 156 155 def _pmesh_to_domain(file_name=None, 156 mesh_instance=None, 157 use_cache=False, 157 ## 158 # @brief Convert pmesh file/instance to list(s) that can instantiate a Domain. 159 # @param file_name Path to file to convert. 160 # @param mesh_instance Instance to convert. 161 # @param use_cache True if we are to cache. 162 # @param verbose True if this function is to be verbose. 163 # @return ?? 164 def _pmesh_to_domain(file_name=None, mesh_instance=None, use_cache=False, 158 165 verbose=False): 159 """ 160 Convert a pmesh file or a pmesh mesh instance to a bunch of lists 166 """Convert a pmesh file or a pmesh mesh instance to a bunch of lists 161 167 that can be used to instanciate a domain object. 162 168 """ … … 164 170 from load_mesh.loadASCII import import_mesh_file 165 171 172 # get data from mesh instance or file 166 173 if file_name is None: 167 174 mesh_dict = mesh_instance.Mesh2IODict() 168 175 else: 169 176 mesh_dict = import_mesh_file(file_name) 170 #print "mesh_dict",mesh_dict 177 178 # extract required data from the mesh dictionary 171 179 vertex_coordinates = mesh_dict['vertices'] 172 180 volumes = mesh_dict['triangles'] 173 181 vertex_quantity_dict = {} 174 point_atts = num.transpose(mesh_dict['vertex_attributes'])182 point_atts = mesh_dict['vertex_attributes'] 175 183 point_titles = mesh_dict['vertex_attribute_titles'] 176 184 geo_reference = mesh_dict['geo_reference'] 177 if point_atts != None: 178 for quantity, value_vector in map (None, point_titles, point_atts): 185 if point_atts is not None: 186 point_atts = num.transpose(mesh_dict['vertex_attributes']) 187 for quantity, value_vector in map(None, point_titles, point_atts): 179 188 vertex_quantity_dict[quantity] = value_vector 180 189 tag_dict = pmesh_dict_to_tag_dict(mesh_dict) 181 190 tagged_elements_dict = build_tagged_elements_dictionary(mesh_dict) 182 return vertex_coordinates, volumes, tag_dict, vertex_quantity_dict, tagged_elements_dict, geo_reference 183 191 192 return (vertex_coordinates, volumes, tag_dict, vertex_quantity_dict, 193 tagged_elements_dict, geo_reference) 184 194 185 195 186 196 def build_tagged_elements_dictionary(mesh_dict): 187 197 """Build the dictionary of element tags. 198 188 199 tagged_elements is a dictionary of element arrays, 189 keyed by tag: 190 { (tag): [e1, e2, e3..] }191 """ 200 keyed by tag: { (tag): [e1, e2, e3..] } 201 """ 202 192 203 tri_atts = mesh_dict['triangle_tags'] 193 204 tagged_elements = {} … … 198 209 tagged_elements.setdefault(tri_atts[tri_att_index], 199 210 []).append(tri_att_index) 211 200 212 return tagged_elements 213 201 214 202 215 def pmesh_dict_to_tag_dict(mesh_dict): … … 204 217 to a dictionary of tags, indexed with volume id and face number. 205 218 """ 219 206 220 triangles = mesh_dict['triangles'] 207 221 sides = calc_sides(triangles) 208 222 tag_dict = {} 209 for seg, tag in map(None, mesh_dict['segments'], 210 mesh_dict['segment_tags']): 223 for seg, tag in map(None, mesh_dict['segments'], mesh_dict['segment_tags']): 211 224 v1 = int(seg[0]) 212 225 v2 = int(seg[1]) … … 222 235 223 236 def calc_sides(triangles): 224 #Build dictionary mapping from sides (2-tuple of points) 225 #to left hand side neighbouring triangle 237 '''Build dictionary mapping from sides (2-tuple of points) 238 to left hand side neighbouring triangle 239 ''' 240 226 241 sides = {} 242 227 243 for id, triangle in enumerate(triangles): 228 244 a = int(triangle[0]) 229 245 b = int(triangle[1]) 230 246 c = int(triangle[2]) 247 231 248 sides[a,b] = (id, 2) #(id, face) 232 249 sides[b,c] = (id, 0) #(id, face) 233 250 sides[c,a] = (id, 1) #(id, face) 251 234 252 return sides 253 -
branches/numpy/anuga/abstract_2d_finite_volumes/quantity.py
r6244 r6304 23 23 from anuga.caching import cache 24 24 25 import Numeric as num 25 import anuga.utilities.numerical_tools as aunt 26 27 import numpy as num 26 28 27 29 … … 43 45 if vertex_values is None: 44 46 N = len(domain) # number_of_elements 45 self.vertex_values = num.zeros((N, 3), num. Float)47 self.vertex_values = num.zeros((N, 3), num.float) 46 48 else: 47 self.vertex_values = num.array(vertex_values, num. Float)49 self.vertex_values = num.array(vertex_values, num.float) 48 50 49 51 N, V = self.vertex_values.shape … … 57 59 58 60 # Allocate space for other quantities 59 self.centroid_values = num.zeros(N, num. Float)60 self.edge_values = num.zeros((N, 3), num. Float)61 self.centroid_values = num.zeros(N, num.float) 62 self.edge_values = num.zeros((N, 3), num.float) 61 63 62 64 # Allocate space for Gradient 63 self.x_gradient = num.zeros(N, num. Float)64 self.y_gradient = num.zeros(N, num. Float)65 self.x_gradient = num.zeros(N, num.float) 66 self.y_gradient = num.zeros(N, num.float) 65 67 66 68 # Allocate space for Limiter Phi 67 self.phi = num.zeros(N, num. Float)69 self.phi = num.zeros(N, num.float) 68 70 69 71 # Intialise centroid and edge_values … … 72 74 # Allocate space for boundary values 73 75 L = len(domain.boundary) 74 self.boundary_values = num.zeros(L, num. Float)76 self.boundary_values = num.zeros(L, num.float) 75 77 76 78 # Allocate space for updates of conserved quantities by … … 78 80 79 81 # Allocate space for update fields 80 self.explicit_update = num.zeros(N, num. Float )81 self.semi_implicit_update = num.zeros(N, num. Float )82 self.centroid_backup_values = num.zeros(N, num. Float)82 self.explicit_update = num.zeros(N, num.float ) 83 self.semi_implicit_update = num.zeros(N, num.float ) 84 self.centroid_backup_values = num.zeros(N, num.float) 83 85 84 86 self.set_beta(1.0) … … 316 318 317 319 numeric: 318 Compatible list, Numeric array (see below) or constant.320 Compatible list, numeric array (see below) or constant. 319 321 If callable it will treated as a function (see below) 320 322 If instance of another Quantity it will be treated as such. … … 357 359 358 360 In case of location == 'centroids' the dimension values must 359 be a list of a Numerical array of length N,361 be a list of a numerical array of length N, 360 362 N being the number of elements. 361 363 Otherwise it must be of dimension Nx3 … … 458 460 459 461 msg = 'Indices must be a list or None' 460 assert type(indices) in [ListType, NoneType, num.ArrayType], msg 462 assert (type(indices) in [ListType, NoneType] 463 or isinstance(indices, num.ndarray)), msg 461 464 462 465 # Determine which 'set_values_from_...' to use 463 466 if numeric is not None: 464 if type(numeric) in [FloatType, IntType, LongType]: 465 self.set_values_from_constant(numeric, location, 466 indices, verbose) 467 elif type(numeric) in [num.ArrayType, ListType]: 467 if isinstance(numeric, num.ndarray) or isinstance(numeric, list): 468 468 self.set_values_from_array(numeric, location, indices, 469 469 use_cache=use_cache, verbose=verbose) … … 479 479 indices, verbose=verbose, 480 480 use_cache=use_cache) 481 # if (isinstance(numeric, float) or isinstance(numeric, int) 482 # or isinstance(numeric, long)): 481 483 else: 482 msg = 'Illegal type for argument numeric: %s' % str(numeric) 483 raise msg 484 try: 485 numeric = float(numeric) 486 except ValueError: 487 msg = ("Illegal type for variable 'numeric': " 488 "%s, shape=%s\n%s" 489 % (type(numeric), numeric.shape, str(numeric))) 490 msg += ('\ntype(numeric)==FloatType is %s' 491 % str(type(numeric)==FloatType)) 492 msg += ('\nisinstance(numeric, float)=%s' 493 % str(isinstance(numeric, float))) 494 msg += ('\nisinstance(numeric, num.ndarray)=%s' 495 % str(isinstance(numeric, num.ndarray))) 496 raise Exception, msg 497 self.set_values_from_constant(numeric, location, 498 indices, verbose) 499 elif quantity is not None: 500 if type(numeric) in [FloatType, IntType, LongType]: 501 self.set_values_from_constant(numeric, location, 502 indices, verbose) 503 else: 504 msg = ("Illegal type for variable 'numeric': %s, shape=%s\n%s" 505 % (type(numeric), numeric.shape, str(numeric))) 506 msg += ('\ntype(numeric)==FloatType is %s' 507 % str(type(numeric)==FloatType)) 508 msg += ('\nisinstance(numeric, float)=%s' 509 % str(isinstance(numeric, float))) 510 msg += ('\nisinstance(numeric, num.ndarray)=%s' 511 % str(isinstance(numeric, num.ndarray))) 512 raise Exception, msg 484 513 elif quantity is not None: 485 514 self.set_values_from_quantity(quantity, location, indices, verbose) … … 583 612 """Set values for quantity 584 613 585 values: Numeric array614 values: numeric array 586 615 location: Where values are to be stored. 587 616 Permissible options are: vertices, centroid, unique vertices … … 593 622 594 623 In case of location == 'centroid' the dimension values must 595 be a list of a Numerical array of length N, N being the number624 be a list of a numerical array of length N, N being the number 596 625 of elements. 597 626 … … 607 636 """ 608 637 609 values = num.array(values, num. Float)638 values = num.array(values, num.float) 610 639 611 640 if indices is not None: 612 indices = num.array(indices, num. Int)641 indices = num.array(indices, num.int) 613 642 msg = ('Number of values must match number of indices: You ' 614 643 'specified %d values and %d indices' … … 637 666 'Values array must be 1d') 638 667 639 self.set_vertex_values(values.flat , indices=indices,668 self.set_vertex_values(values.flatten(), indices=indices, 640 669 use_cache=use_cache, verbose=verbose) 641 670 else: … … 788 817 from anuga.coordinate_transforms.geo_reference import Geo_reference 789 818 790 points = ensure_numeric(points, num. Float)791 values = ensure_numeric(values, num. Float)819 points = ensure_numeric(points, num.float) 820 values = ensure_numeric(values, num.float) 792 821 793 822 if location != 'vertices': … … 1080 1109 1081 1110 # Ensure that interpolation points is either a list of 1082 # points, Nx2 array, or geospatial and convert to Numeric array1111 # points, Nx2 array, or geospatial and convert to numeric array 1083 1112 if isinstance(interpolation_points, Geospatial_data): 1084 1113 # Ensure interpolation points are in absolute UTM coordinates … … 1119 1148 """Get values for quantity 1120 1149 1121 Extract values for quantity as a Numeric array.1150 Extract values for quantity as a numeric array. 1122 1151 1123 1152 Inputs: … … 1137 1166 1138 1167 In case of location == 'centroids' the dimension of returned 1139 values will be a list or a Numerical array of length N, N being1168 values will be a list or a numerical array of length N, N being 1140 1169 the number of elements. 1141 1170 … … 1173 1202 'edges', 'unique vertices']: 1174 1203 msg = 'Invalid location: %s' % location 1175 raise msg1204 raise Exception, msg 1176 1205 1177 1206 import types 1178 1207 1179 1208 assert type(indices) in [types.ListType, types.NoneType, 1180 num. ArrayType], \1181 'Indices must be a list or None' 1209 num.ndarray], \ 1210 'Indices must be a list or None' #??# 1182 1211 1183 1212 if location == 'centroids': … … 1210 1239 sum += self.vertex_values[triangle_id, vertex_id] 1211 1240 vert_values.append(sum / len(triangles)) 1212 return num.array(vert_values, num. Float)1241 return num.array(vert_values, num.float) 1213 1242 else: 1214 1243 if (indices is None): … … 1236 1265 1237 1266 # Check that A can be converted to array and is of appropriate dim 1238 A = ensure_numeric(A, num. Float)1267 A = ensure_numeric(A, num.float) 1239 1268 assert len(A.shape) == 1 1240 1269 … … 1336 1365 1337 1366 if precision is None: 1338 precision = num. Float1367 precision = num.float 1339 1368 1340 1369 if smooth is True: … … 1342 1371 V = self.domain.get_triangles() 1343 1372 N = self.domain.number_of_full_nodes # Ignore ghost nodes if any 1344 A = num.zeros(N, num. Float)1373 A = num.zeros(N, num.float) 1345 1374 points = self.domain.get_nodes() 1346 1375 … … 1360 1389 if current_node == N: 1361 1390 msg = 'Current node exceeding number of nodes (%d) ' % N 1362 raise msg1391 raise Exception, msg 1363 1392 1364 1393 k += 1 … … 1381 1410 V = self.domain.get_disconnected_triangles() 1382 1411 points = self.domain.get_vertex_coordinates() 1383 A = self.vertex_values.flat .astype(precision)1412 A = self.vertex_values.flatten().astype(precision) 1384 1413 1385 1414 # Return -
branches/numpy/anuga/abstract_2d_finite_volumes/quantity_ext.c
r5897 r6304 11 11 12 12 #include "Python.h" 13 #include " Numeric/arrayobject.h"13 #include "numpy/arrayobject.h" 14 14 #include "math.h" 15 15 -
branches/numpy/anuga/abstract_2d_finite_volumes/region.py
r6145 r6304 8 8 # FIXME (DSG-DSG) add better comments 9 9 10 import Numericas num10 import numpy as num 11 11 12 12 -
branches/numpy/anuga/abstract_2d_finite_volumes/test_domain.py
r6195 r6304 7 7 from anuga.config import epsilon 8 8 9 import Numericas num9 import numpy as num 10 10 11 11 … … 65 65 66 66 67 assert domain.get_conserved_quantities(0, edge=1) == 0.67 assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.) 68 68 69 69 … … 345 345 346 346 347 A = num.array([[1,2,3], [5,5,-5], [0,0,9], [-6,3,3]], num. Float)348 B = num.array([[2,4,4], [3,2,1], [6,-3,4], [4,5,-1]], num. Float)347 A = num.array([[1,2,3], [5,5,-5], [0,0,9], [-6,3,3]], num.float) 348 B = num.array([[2,4,4], [3,2,1], [6,-3,4], [4,5,-1]], num.float) 349 349 350 350 #print A … … 613 613 614 614 sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4]) 615 denom = num.ones(4, num. Float)-domain.timestep*sem615 denom = num.ones(4, num.float)-domain.timestep*sem 616 616 617 617 # x = array([1, 2, 3, 4]) + array( [.4,.3,.2,.1] ) -
branches/numpy/anuga/abstract_2d_finite_volumes/test_ermapper.py
r6145 r6304 7 7 from os import remove 8 8 9 import Numericas num9 import numpy as num 10 10 11 11 … … 45 45 46 46 # Write test data 47 ermapper_grids.write_ermapper_data(original_grid, filename, num. Float64)47 ermapper_grids.write_ermapper_data(original_grid, filename, num.float64) 48 48 49 49 # Read in the test data 50 new_grid = ermapper_grids.read_ermapper_data(filename, num. Float64)50 new_grid = ermapper_grids.read_ermapper_data(filename, num.float64) 51 51 52 52 # Check that the test data that has been read in matches the original data -
branches/numpy/anuga/abstract_2d_finite_volumes/test_general_mesh.py
r6174 r6304 10 10 from anuga.coordinate_transforms.geo_reference import Geo_reference 11 11 12 import Numericas num12 import numpy as num 13 13 14 14 … … 59 59 60 60 #bac, bce, ecf, dbe, daf, dae 61 triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num. Int)61 triangles = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.int) 62 62 63 63 domain = General_mesh(nodes, triangles, … … 277 277 geo_reference = geo) 278 278 node = domain.get_node(2) 279 self.assertEqual(c, node) 279 #self.assertEqual(c, node) 280 self.failUnless(num.alltrue(c == node)) 280 281 281 282 node = domain.get_node(2, absolute=True) 282 self.assertEqual(nodes_absolute[2], node) 283 #self.assertEqual(nodes_absolute[2], node) 284 self.failUnless(num.alltrue(nodes_absolute[2] == node)) 283 285 284 286 node = domain.get_node(2, absolute=True) 285 self.assertEqual(nodes_absolute[2], node) 287 #self.assertEqual(nodes_absolute[2], node) 288 self.failUnless(num.alltrue(nodes_absolute[2] == node)) 286 289 287 290 -
branches/numpy/anuga/abstract_2d_finite_volumes/test_generic_boundary_conditions.py
r6195 r6304 8 8 from anuga.config import epsilon 9 9 10 import Numericas num10 import numpy as num 11 11 12 12 -
branches/numpy/anuga/abstract_2d_finite_volumes/test_ghost.py
r6195 r6304 6 6 from anuga.abstract_2d_finite_volumes.domain import * 7 7 from anuga.config import epsilon 8 9 import numpy as num 8 10 9 11 … … 40 42 41 43 42 assert domain.get_conserved_quantities(0, edge=1) == 0.44 assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.) 43 45 44 46 -
branches/numpy/anuga/abstract_2d_finite_volumes/test_neighbour_mesh.py
r6174 r6304 18 18 from anuga.utilities.numerical_tools import ensure_numeric 19 19 20 import Numericas num20 import numpy as num 21 21 22 22 … … 988 988 [ 75735.4765625 , 23762.00585938], 989 989 [ 52341.70703125, 38563.39453125]] 990 991 ##points = ensure_numeric(points, Int)/1000 # Simplify for ease of interpretation992 990 993 991 triangles = [[19, 0,15], … … 1092 1090 [ 35406.3359375 , 79332.9140625 ]] 1093 1091 1094 scaled_points = ensure_numeric(points, num. Int)/1000 # Simplify for ease of interpretation1092 scaled_points = ensure_numeric(points, num.int)/1000 # Simplify for ease of interpretation 1095 1093 1096 1094 triangles = [[ 0, 1, 2], -
branches/numpy/anuga/abstract_2d_finite_volumes/test_pmesh2domain.py
r6191 r6304 14 14 from anuga.pmesh.mesh import importMeshFromFile 15 15 16 import Numericas num16 import numpy as num 17 17 18 18 -
branches/numpy/anuga/abstract_2d_finite_volumes/test_quantity.py
r6195 r6304 15 15 from anuga.utilities.polygon import * 16 16 17 import Numericas num17 import numpy as num 18 18 19 19 … … 1765 1765 quantity = Quantity(self.mesh4) 1766 1766 1767 quantity.vertex_values = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num. Float)1767 quantity.vertex_values = num.array([[1,0,2], [1,2,4], [4,2,5], [3,1,4]], num.float) 1768 1768 1769 1769 quantity.interpolate_from_vertices_to_edges() … … 1781 1781 [3., 2.5, 1.5], 1782 1782 [3.5, 4.5, 3.], 1783 [2.5, 3.5, 2]], num. Float)1783 [2.5, 3.5, 2]], num.float) 1784 1784 1785 1785 quantity.interpolate_from_edges_to_vertices() … … 1835 1835 1836 1836 sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4]) 1837 denom = num.ones(4, num. Float)-timestep*sem1837 denom = num.ones(4, num.float)-timestep*sem 1838 1838 1839 1839 x = num.array([1, 2, 3, 4])/denom … … 1859 1859 1860 1860 sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4]) 1861 denom = num.ones(4, num. Float)-timestep*sem1861 denom = num.ones(4, num.float)-timestep*sem 1862 1862 1863 1863 x = num.array([1., 2., 3., 4.]) … … 1901 1901 1902 1902 bed = domain.quantities['elevation'].vertex_values 1903 stage = num.zeros(bed.shape, num. Float)1903 stage = num.zeros(bed.shape, num.float) 1904 1904 1905 1905 h = 0.03 … … 1985 1985 1986 1986 bed = domain.quantities['elevation'].vertex_values 1987 stage = num.zeros(bed.shape, num. Float)1987 stage = num.zeros(bed.shape, num.float) 1988 1988 1989 1989 h = 0.03 … … 1999 1999 stage = domain.quantities['stage'] 2000 2000 A, V = stage.get_vertex_values(xy=False, smooth=False) 2001 Q = stage.vertex_values.flat 2001 Q = stage.vertex_values.flatten() 2002 2002 2003 2003 for k in range(8): … … 2511 2511 suite = unittest.makeSuite(Test_Quantity, 'test') 2512 2512 #suite = unittest.makeSuite(Test_Quantity, 'test_set_values_from_file_using_polygon') 2513 2514 #suite = unittest.makeSuite(Test_Quantity, 'test_set_vertex_values_using_general_interface_subset_and_geo')2515 #print "restricted test"2516 #suite = unittest.makeSuite(Test_Quantity,'verbose_test_set_values_from_UTM_pts')2517 2513 runner = unittest.TextTestRunner() 2518 2514 runner.run(suite) -
branches/numpy/anuga/abstract_2d_finite_volumes/test_region.py
r6145 r6304 8 8 #from anuga.config import epsilon 9 9 10 import Numericas num10 import numpy as num 11 11 12 12 … … 42 42 43 43 def test_region_tags(self): 44 """ 45 get values based on triangle lists. 46 """ 47 from mesh_factory import rectangular 48 from shallow_water import Domain 49 50 #Create basic mesh 51 points, vertices, boundary = rectangular(1, 3) 52 53 #Create shallow water domain 54 domain = Domain(points, vertices, boundary) 55 domain.build_tagged_elements_dictionary({'bottom':[0,1], 56 'top':[4,5], 57 'all':[0,1,2,3,4,5]}) 58 44 """get values based on triangle lists.""" 45 46 from mesh_factory import rectangular 47 from shallow_water import Domain 48 49 #Create basic mesh 50 points, vertices, boundary = rectangular(1, 3) 51 52 #Create shallow water domain 53 domain = Domain(points, vertices, boundary) 54 domain.build_tagged_elements_dictionary({'bottom': [0,1], 55 'top': [4,5], 56 'all': [0,1,2,3,4,5]}) 59 57 60 58 #Set friction … … 65 63 b = Set_region('top', 'friction', 1.0) 66 64 domain.set_region([a, b]) 67 #print domain.quantities['friction'].get_values() 68 assert num.allclose(domain.quantities['friction'].get_values(),\ 69 [[ 0.09, 0.09, 0.09], 70 [ 0.09, 0.09, 0.09], 71 [ 0.07, 0.07, 0.07], 72 [ 0.07, 0.07, 0.07], 73 [ 1.0, 1.0, 1.0], 74 [ 1.0, 1.0, 1.0]]) 65 66 expected = [[ 0.09, 0.09, 0.09], 67 [ 0.09, 0.09, 0.09], 68 [ 0.07, 0.07, 0.07], 69 [ 0.07, 0.07, 0.07], 70 [ 1.0, 1.0, 1.0], 71 [ 1.0, 1.0, 1.0]] 72 msg = ("\ndomain.quantities['friction']=%s\nexpected value=%s" 73 % (str(domain.quantities['friction'].get_values()), 74 str(expected))) 75 assert num.allclose(domain.quantities['friction'].get_values(), 76 expected), msg 75 77 76 78 #c = Add_Value_To_region('all', 'friction', 10.0) … … 126 128 127 129 def test_unique_vertices(self): 128 """ 129 get values based on triangle lists. 130 """ 130 """get values based on triangle lists.""" 131 131 132 from mesh_factory import rectangular 132 133 from shallow_water import Domain … … 147 148 a = Set_region('bottom', 'friction', 0.09, location = 'unique vertices') 148 149 domain.set_region(a) 149 #print domain.quantities['friction'].get_values() 150 assert num.allclose(domain.quantities['friction'].get_values(),\ 150 assert num.allclose(domain.quantities['friction'].get_values(), 151 151 [[ 0.09, 0.09, 0.09], 152 152 [ 0.09, 0.09, 0.09], … … 217 217 #print domain.quantities['friction'].get_values() 218 218 frict_points = domain.quantities['friction'].get_values() 219 assert num.allclose(frict_points[0],\ 220 [ calc_frict, calc_frict, calc_frict]) 221 assert num.allclose(frict_points[1],\ 222 [ calc_frict, calc_frict, calc_frict]) 219 expected = [calc_frict, calc_frict, calc_frict] 220 msg = ('frict_points[0]=%s\nexpected=%s' % (str(frict_points[0]), 221 str(expected))) 222 assert num.allclose(frict_points[0], expected), msg 223 msg = ('frict_points[1]=%s\nexpected=%s' % (str(frict_points[1]), 224 str(expected))) 225 assert num.allclose(frict_points[1], expected), msg 223 226 224 227 def test_unique_vertices_average_loc_unique_vert(self): … … 262 265 #------------------------------------------------------------- 263 266 if __name__ == "__main__": 264 suite = unittest.makeSuite(Test_Region, 'test')267 suite = unittest.makeSuite(Test_Region, 'test') 265 268 runner = unittest.TextTestRunner() 266 269 runner.run(suite) -
branches/numpy/anuga/abstract_2d_finite_volumes/test_util.py
r6175 r6304 22 22 import string 23 23 24 import Numericas num24 import numpy as num 25 25 26 26 … … 630 630 q1 = F(t+60, point_id=id) 631 631 632 if q0 == NAN:632 if num.alltrue(q0 == NAN): 633 633 actual = q0 634 634 else: … … 641 641 #print "actual", actual 642 642 #print 643 if q0 == NAN:644 self.failUnless( q == actual, 'Fail!')643 if num.alltrue(q0 == NAN): 644 self.failUnless(num.alltrue(q == actual), 'Fail!') 645 645 else: 646 646 assert num.allclose(q, actual) … … 1181 1181 #FIXME: Division is not expected to work for integers. 1182 1182 #This must be caught. 1183 foo = num.array([[1,2,3], [4,5,6]], num. Float)1184 1185 bar = num.array([[-1,0,5], [6,1,1]], num. Float)1183 foo = num.array([[1,2,3], [4,5,6]], num.float) 1184 1185 bar = num.array([[-1,0,5], [6,1,1]], num.float) 1186 1186 1187 1187 D = {'X': foo, 'Y': bar} … … 1201 1201 1202 1202 # make an error for zero on zero 1203 # this is really an error in Numeric, SciPy core can handle it1203 # this is really an error in numeric, SciPy core can handle it 1204 1204 # Z = apply_expression_to_dictionary('0/Y', D) 1205 1205 -
branches/numpy/anuga/abstract_2d_finite_volumes/util.py
r6194 r6304 27 27 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 28 28 29 import Numericas num29 import numpy as num 30 30 31 31 … … 554 554 expression e.g. by overloading 555 555 556 Due to a limitation with Numeric, this can not evaluate 0/0556 Due to a limitation with numeric, this can not evaluate 0/0 557 557 In general, the user can fix by adding 1e-30 to the numerator. 558 558 SciPy core can handle this situation. … … 789 789 - easting, northing, name , elevation? 790 790 - OR (this is not yet done) 791 - structure which can be converted to a Numeric array,791 - structure which can be converted to a numeric array, 792 792 such as a geospatial data object 793 793 … … 1255 1255 n0 = int(n0) 1256 1256 m = len(locations) 1257 model_time = num.zeros((n0, m, p), num. Float)1258 stages = num.zeros((n0, m, p), num. Float)1259 elevations = num.zeros((n0, m, p), num. Float)1260 momenta = num.zeros((n0, m, p), num. Float)1261 xmom = num.zeros((n0, m, p), num. Float)1262 ymom = num.zeros((n0, m, p), num. Float)1263 speed = num.zeros((n0, m, p), num. Float)1264 bearings = num.zeros((n0, m, p), num. Float)1265 due_east = 90.0*num.ones((n0, 1), num. Float)1266 due_west = 270.0*num.ones((n0, 1), num. Float)1267 depths = num.zeros((n0, m, p), num. Float)1268 eastings = num.zeros((n0, m, p), num. Float)1257 model_time = num.zeros((n0, m, p), num.float) 1258 stages = num.zeros((n0, m, p), num.float) 1259 elevations = num.zeros((n0, m, p), num.float) 1260 momenta = num.zeros((n0, m, p), num.float) 1261 xmom = num.zeros((n0, m, p), num.float) 1262 ymom = num.zeros((n0, m, p), num.float) 1263 speed = num.zeros((n0, m, p), num.float) 1264 bearings = num.zeros((n0, m, p), num.float) 1265 due_east = 90.0*num.ones((n0, 1), num.float) 1266 due_west = 270.0*num.ones((n0, 1), num.float) 1267 depths = num.zeros((n0, m, p), num.float) 1268 eastings = num.zeros((n0, m, p), num.float) 1269 1269 min_stages = [] 1270 1270 max_stages = [] … … 1278 1278 min_speeds = [] 1279 1279 max_depths = [] 1280 model_time_plot3d = num.zeros((n0, m), num. Float)1281 stages_plot3d = num.zeros((n0, m), num. Float)1282 eastings_plot3d = num.zeros((n0, m),num. Float)1280 model_time_plot3d = num.zeros((n0, m), num.float) 1281 stages_plot3d = num.zeros((n0, m), num.float) 1282 eastings_plot3d = num.zeros((n0, m),num.float) 1283 1283 if time_unit is 'mins': scale = 60.0 1284 1284 if time_unit is 'hours': scale = 3600.0 … … 1832 1832 """ 1833 1833 1834 xc = num.zeros(triangles.shape[0], num. Float) # Space for centroid info1834 xc = num.zeros(triangles.shape[0], num.float) # Space for centroid info 1835 1835 1836 1836 for k in range(triangles.shape[0]): … … 2119 2119 #add tide to stage if provided 2120 2120 if quantity == 'stage': 2121 quantity_value[quantity] = num.array(quantity_value[quantity], num. Float) \2121 quantity_value[quantity] = num.array(quantity_value[quantity], num.float) \ 2122 2122 + directory_add_tide 2123 2123 … … 2469 2469 2470 2470 #convert to array for file_function 2471 points_array = num.array(points,num. Float)2471 points_array = num.array(points,num.float) 2472 2472 2473 2473 points_array = ensure_absolute(points_array) -
branches/numpy/anuga/advection/advection.py
r6146 r6304 33 33 from anuga.abstract_2d_finite_volumes.domain import * 34 34 35 import Numericas num35 import numpy as num 36 36 37 37 … … 252 252 stage_bdry = Stage.boundary_values 253 253 254 flux = num.zeros(1, num. Float) #Work array for summing up fluxes254 flux = num.zeros(1, num.float) #Work array for summing up fluxes 255 255 256 256 #Loop -
branches/numpy/anuga/advection/advection_ext.c
r5162 r6304 10 10 11 11 #include "Python.h" 12 #include " Numeric/arrayobject.h"12 #include "numpy/arrayobject.h" 13 13 #include "math.h" 14 14 #include "stdio.h" -
branches/numpy/anuga/advection/test_advection.py
r6146 r6304 8 8 from anuga.advection.advection import Domain, Transmissive_boundary, Dirichlet_boundary 9 9 10 import Numericas num10 import numpy as num 11 11 12 12 … … 142 142 143 143 X = domain.quantities['stage'].explicit_update 144 # print 'X=%s' % str(X) 144 145 assert X[0] == -X[1] 145 146 -
branches/numpy/anuga/alpha_shape/alpha_shape.py
r6174 r6304 25 25 from anuga.geospatial_data.geospatial_data import Geospatial_data 26 26 27 import Numericas num27 import numpy as num 28 28 29 29 … … 88 88 raise PointError, "Three points on a straight line" 89 89 90 #Convert input to Numeric arrays91 self.points = num.array(points, num. Float)90 #Convert input to numeric arrays 91 self.points = num.array(points, num.float) 92 92 93 93 … … 288 288 zeroind = [k for k in range(len(denom)) if \ 289 289 (denom[k]< EPSILON and denom[k] > -EPSILON)] 290 try: 291 dx = num.divide_safe(y31*dist21 - y21*dist31,denom) 292 dy = num.divide_safe(x21*dist31 - x31*dist21,denom) 293 except ZeroDivisionError: 294 raise AlphaError 295 290 291 if num.any(denom == 0.0): 292 raise AlphaError 293 294 dx = num.divide(y31*dist21 - y21*dist31, denom) 295 dy = num.divide(x21*dist31 - x31*dist21, denom) 296 296 297 self.triradius = 0.5*num.sqrt(dx*dx + dy*dy) 297 298 #print "triangle radii", self.triradius -
branches/numpy/anuga/alpha_shape/test_alpha_shape.py
r6147 r6304 5 5 import unittest 6 6 7 import Numericas num7 import numpy as num 8 8 9 9 try: -
branches/numpy/anuga/caching/caching.py
r6232 r6304 51 51 unix = True 52 52 53 import Numericas num53 import numpy as num 54 54 55 55 … … 1390 1390 I.sort() 1391 1391 val = myhash(I, ids) 1392 elif type(T) == num.ArrayType:1392 elif isinstance(T, num.ndarray): 1393 1393 T = num.array(T) # Ensure array is contiguous 1394 1394 … … 1461 1461 identical = compare(a, b, ids) 1462 1462 1463 elif type(A) == num.ArrayType:1463 elif isinstance(A, num.ndarray): 1464 1464 # Use element by element comparison 1465 1465 identical = num.alltrue(A==B) … … 2435 2435 argstr = argstr + "'"+str(args)+"'" 2436 2436 else: 2437 # Truncate large Numeric arrays before using str()2438 if type(args) == num.ArrayType:2437 # Truncate large numeric arrays before using str() 2438 if isinstance(args, num.ndarray): 2439 2439 # if len(args.flat) > textwidth: 2440 2440 # Changed by Duncan and Nick 21/2/07 .flat has problems with -
branches/numpy/anuga/caching/test_caching.py
r6232 r6304 7 7 from anuga.caching.dummy_classes_for_testing import Dummy, Dummy_memorytest 8 8 9 import Numericas num9 import numpy as num 10 10 11 11 … … 26 26 27 27 def f_numeric(A, B): 28 """Operation on Numeric arrays28 """Operation on numeric arrays 29 29 """ 30 30 … … 123 123 """test_caching_of_numeric_arrays 124 124 125 Test that Numeric arrays can be recognised by caching even if their id's are different125 Test that numeric arrays can be recognised by caching even if their id's are different 126 126 """ 127 127 … … 160 160 161 161 162 assert T1 == T2, 'Cached result does not match computed result'163 assert T2 == T3, 'Cached result does not match computed result'162 assert num.alltrue(T1 == T2), 'Cached result does not match computed result' 163 assert num.alltrue(T2 == T3), 'Cached result does not match computed result' 164 164 165 165 166 166 def test_hash_collision(self): 167 """test_hash_collision(self): 168 169 Test that hash collisons are dealt with correctly 170 """ 167 """Test that hash collisons are dealt with correctly""" 171 168 172 169 verbose = False … … 202 199 T2 = cache(f_numeric, (A1, A1), 203 200 compression=comp, verbose=verbose) 204 205 206 #print T1 207 #print T2 208 assert T2 != T1 209 210 211 212 213 201 202 T1_ref = f_numeric(A0, A0) 203 T2_ref = f_numeric(A1, A1) 204 205 assert num.alltrue(T1 == T1_ref) 206 assert num.alltrue(T2 == T2_ref) 207 208 214 209 def test_caching_of_dictionaries(self): 215 210 """test_caching_of_dictionaries … … 412 407 413 408 414 x = num.arange(10).astype(num. Float)409 x = num.arange(10).astype(num.float) 415 410 416 411 ref1 = f1(x) -
branches/numpy/anuga/config.py
r6108 r6304 4 4 import os 5 5 import sys 6 7 ################################################################################ 8 # Numerical constants 6 import numpy as num 7 8 9 ################################################################################ 10 # numerical constants 9 11 ################################################################################ 10 12 … … 160 162 # Too large (100) creates 'flopping' water 161 163 # Too small (0) creates 'creep' 162 164 163 165 maximum_froude_number = 100.0 # To be used in limiters. 164 166 … … 181 183 182 184 ################################################################################ 185 # NetCDF-specific type constants. Used when defining NetCDF file variables. 186 ################################################################################ 187 188 netcdf_char = 'c' 189 netcdf_byte = 'b' 190 netcdf_int = 'i' 191 netcdf_float = 'd' 192 netcdf_float64 = 'd' 193 netcdf_float32 = 'f' 194 195 ################################################################################ 183 196 # Dynamically-defined constants. 184 197 ################################################################################ … … 191 204 # Code to set the write mode depending on 192 205 # whether Scientific.IO supports large NetCDF files 193 s = """from Scientific.IO.NetCDF import NetCDFFile; fid = NetCDFFile('tmpfilenamexx', 'wl')""" 206 s = """ 207 from Scientific.IO.NetCDF import NetCDFFile 208 fid = NetCDFFile('tmpfilenamexx', 'wl') 209 """ 194 210 195 211 # Need to run in a separate process due an -
branches/numpy/anuga/coordinate_transforms/geo_reference.py
r6149 r6304 11 11 from anuga.utilities.anuga_exceptions import ANUGAError, TitleError, ParsingError, \ 12 12 ShapeError 13 14 import Numeric as num 13 from anuga.config import netcdf_float, netcdf_int, netcdf_float32 14 15 import numpy as num 15 16 16 17 … … 64 65 self.xllcorner = xllcorner 65 66 self.yllcorner = yllcorner 67 #self.is_absolute = num.allclose([self.xllcorner, self.yllcorner], 0) 66 68 67 69 if NetCDFObject is not None: … … 99 101 100 102 # Fix some assertion failures 101 if type(self.zone) == num.ArrayTypeand self.zone.shape == ():103 if isinstance(self.zone, num.ndarray) and self.zone.shape == (): 102 104 self.zone = self.zone[0] 103 if type(self.xllcorner) == num.ArrayTypeand self.xllcorner.shape == ():105 if isinstance(self.xllcorner, num.ndarray) and self.xllcorner.shape == (): 104 106 self.xllcorner = self.xllcorner[0] 105 if type(self.yllcorner) == num.ArrayTypeand self.yllcorner.shape == ():107 if isinstance(self.yllcorner, num.ndarray) and self.yllcorner.shape == (): 106 108 self.yllcorner = self.yllcorner[0] 107 109 108 assert ( type(self.xllcorner) == types.FloatType or\109 type(self.xllcorner) == types.IntType)110 assert ( type(self.yllcorner) == types.FloatType or\111 type(self.yllcorner) == types.IntType)112 assert ( type(self.zone) == types.IntType)110 assert (self.xllcorner.dtype.kind in num.typecodes['Float'] or 111 self.xllcorner.dtype.kind in num.typecodes['Integer']) 112 assert (self.yllcorner.dtype.kind in num.typecodes['Float'] or 113 self.yllcorner.dtype.kind in num.typecodes['Integer']) 114 assert (self.zone.dtype.kind in num.typecodes['Integer']) 113 115 114 116 try: … … 173 175 174 176 # Fix some assertion failures 175 if (type(self.zone) == num.ArrayType and self.zone.shape == ()):177 if isinstance(self.zone, num.ndarray) and self.zone.shape == (): 176 178 self.zone = self.zone[0] 177 if type(self.xllcorner) == num.ArrayTypeand self.xllcorner.shape == ():179 if isinstance(self.xllcorner, num.ndarray) and self.xllcorner.shape == (): 178 180 self.xllcorner = self.xllcorner[0] 179 if type(self.yllcorner) == num.ArrayTypeand self.yllcorner.shape == ():181 if isinstance(self.yllcorner, num.ndarray) and self.yllcorner.shape == (): 180 182 self.yllcorner = self.yllcorner[0] 181 182 assert (type(self.xllcorner) == types.FloatType) 183 assert (type(self.yllcorner) == types.FloatType) 184 assert (type(self.zone) == types.IntType) 185 183 184 # useless asserts - see try/except code above 185 # assert (type(self.xllcorner) == types.FloatType) 186 # assert (type(self.yllcorner) == types.FloatType) 187 # assert (type(self.zone) == types.IntType) 188 186 189 187 190 def change_points_geo_ref(self, points, 188 191 points_geo_ref=None): 189 192 """ 190 Change the geo reference of a list or Numeric array of points to193 Change the geo reference of a list or numeric array of points to 191 194 be this reference.(The reference used for this object) 192 195 If the points do not have a geo ref, assume 'absolute' values … … 197 200 is_list = True 198 201 199 points = ensure_numeric(points, num. Float)202 points = ensure_numeric(points, num.float) 200 203 201 204 if len(points.shape) == 1: … … 243 246 244 247 245 248 ## 249 # @brief 250 # @param points 251 # @return 252 # @note 246 253 def get_absolute(self, points): 247 """ 248 Given a set of points geo referenced to this instance, 254 """Given a set of points geo referenced to this instance, 249 255 return the points as absolute values. 250 256 """ 251 257 252 #if self.is_absolute ():258 #if self.is_absolute: 253 259 # return points 260 254 261 is_list = False 255 262 if type(points) == types.ListType: 256 263 is_list = True 257 264 258 points = ensure_numeric(points, num. Float)265 points = ensure_numeric(points, num.float) 259 266 if len(points.shape) == 1: 260 267 #One point has been passed … … 264 271 #points = reshape(points, (1,2)) 265 272 266 267 273 msg = 'Input must be an N x 2 array or list of (x,y) values. ' 268 274 msg += 'I got an %d x %d array' %points.shape 269 275 if not points.shape[1] == 2: 270 276 raise ShapeError, msg 271 272 277 273 278 # Add geo ref to points 279 #if not self.is_absolute: 274 280 if not self.is_absolute(): 275 281 points[:,0] += self.xllcorner 276 282 points[:,1] += self.yllcorner 277 283 #self.is_absolute = True 278 284 279 285 if is_list: … … 296 302 is_list = True 297 303 298 points = ensure_numeric(points, num. Float)304 points = ensure_numeric(points, num.float) 299 305 if len(points.shape) == 1: 300 306 #One point has been passed -
branches/numpy/anuga/coordinate_transforms/test_geo_reference.py
r6149 r6304 9 9 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 10 10 11 import Numericas num11 import numpy as num 12 12 13 13 … … 171 171 #print "4 new_lofl",new_lofl 172 172 173 self.failUnless( type(new_lofl) == num.ArrayType, ' failed')173 self.failUnless(isinstance(new_lofl, num.ndarray), ' failed') 174 174 self.failUnless(type(new_lofl) == type(lofl), ' failed') 175 175 lofl[:,0] -= x … … 189 189 #print "5 new_lofl",new_lofl 190 190 191 self.failUnless( type(new_lofl) == num.ArrayType, ' failed')191 self.failUnless(isinstance(new_lofl, num.ndarray), ' failed') 192 192 self.failUnless(type(new_lofl) == type(lofl), ' failed') 193 193 … … 206 206 #print "new_lofl",new_lofl 207 207 208 self.failUnless( type(new_lofl) == num.ArrayType, ' failed')208 self.failUnless(isinstance(new_lofl, num.ndarray), ' failed') 209 209 self.failUnless(type(new_lofl) == type(lofl), ' failed') 210 210 for point,new_point in map(None,[lofl],new_lofl): … … 229 229 self.failUnless(point[0]+point_x-x==new_point[0], ' failed') 230 230 self.failUnless(point[1]+point_y-y==new_point[1], ' failed') 231 232 233 def test_get_absolute(self):231 232 def test_get_absolute_list(self): 233 # test with supplied offsets 234 234 x = 7.0 235 235 y = 3.0 236 236 237 g = Geo_reference(56,x,y) 238 lofl = [[3.0,34.0], [64.0,6.0]] 239 new_lofl = g.get_absolute(lofl) 240 #print "lofl",lofl 241 #print "new_lofl",new_lofl 242 243 self.failUnless(type(new_lofl) == types.ListType, ' failed') 244 self.failUnless(type(new_lofl) == type(lofl), ' failed') 245 for point,new_point in map(None,lofl,new_lofl): 246 self.failUnless(point[0]+x==new_point[0], ' failed') 247 self.failUnless(point[1]+y==new_point[1], ' failed') 248 237 g = Geo_reference(56, x, y) 238 points = [[3.0,34.0], [64.0,6.0]] 239 new_points = g.get_absolute(points) 240 241 self.failUnless(type(new_points) == types.ListType, 'failed') 242 self.failUnless(type(new_points) == type(points), 'failed') 243 for point, new_point in map(None, points, new_points): 244 self.failUnless(point[0]+x == new_point[0], 'failed') 245 self.failUnless(point[1]+y == new_point[1], 'failed') 246 247 # test with no supplied offsets 248 g = Geo_reference() 249 points = [[3.0,34.0], [64.0,6.0]] 250 new_points = g.get_absolute(points) 251 252 self.failUnless(type(new_points) == types.ListType, 'failed') 253 self.failUnless(type(new_points) == type(points), 'failed') 254 for point, new_point in map(None, points, new_points): 255 self.failUnless(point[0] == new_point[0], 'failed') 256 self.failUnless(point[1] == new_point[1], 'failed') 249 257 258 # test that calling get_absolute twice does the right thing 259 # first call 260 dx = 10.0 261 dy = 10.0 262 g = Geo_reference(56, dx, dy) 263 points = [[3.0,34.0], [64.0,6.0]] 264 expected_new_points = [[3.0+dx,34.0+dy], [64.0+dx,6.0+dy]] 265 new_points = g.get_absolute(points) 266 267 self.failUnless(type(new_points) == types.ListType, 'failed') 268 self.failUnless(type(new_points) == type(points), 'failed') 269 for point, new_point in map(None, expected_new_points, new_points): 270 self.failUnless(point[0] == new_point[0], 'failed') 271 self.failUnless(point[1] == new_point[1], 'failed') 272 273 # and repeat from 'new_points = g.get_absolute(points)' above 274 # to see if second call with same input gives same results. 275 new_points = g.get_absolute(points) 276 277 self.failUnless(type(new_points) == types.ListType, 'failed') 278 self.failUnless(type(new_points) == type(points), 'failed') 279 for point, new_point in map(None, expected_new_points, new_points): 280 self.failUnless(point[0] == new_point[0], 'failed') 281 self.failUnless(point[1] == new_point[1], 'failed') 282 283 def test_get_absolute_array(self): 284 '''Same test as test_get_absolute_list(), but with numeric arrays.''' 285 286 # test with supplied offsets 287 x = 7.0 288 y = 3.0 289 290 g = Geo_reference(56, x, y) 291 points = num.array([[3.0,34.0], [64.0,6.0]]) 292 new_points = g.get_absolute(points) 293 294 self.failUnless(isinstance(new_points, num.ndarray), 'failed') 295 self.failUnless(type(new_points) == type(points), 'failed') 296 self.failUnless(num.alltrue(points == new_points), 'failed') 297 298 # test with no supplied offsets 250 299 g = Geo_reference() 251 lofl = [[3.0,34.0], [64.0,6.0]] 252 new_lofl = g.get_absolute(lofl) 253 #print "lofl",lofl 254 #print "new_lofl",new_lofl 255 256 self.failUnless(type(new_lofl) == types.ListType, ' failed') 257 self.failUnless(type(new_lofl) == type(lofl), ' failed') 258 for point,new_point in map(None,lofl,new_lofl): 259 self.failUnless(point[0]==new_point[0], ' failed') 260 self.failUnless(point[1]==new_point[1], ' failed') 261 300 points = num.array([[3.0,34.0], [64.0,6.0]]) 301 new_points = g.get_absolute(points) 302 303 self.failUnless(isinstance(new_points, num.ndarray), 'failed') 304 self.failUnless(type(new_points) == type(points), 'failed') 305 self.failUnless(num.alltrue(points == new_points), 'failed') 306 307 # test that calling get_absolute twice does the right thing 308 # first call 309 dx = 10.0 310 dy = 10.0 311 g = Geo_reference(56, dx, dy) 312 points = num.array([[3.0,34.0], [64.0,6.0]]) 313 expected_new_points = num.array([[3.0+dx,34.0+dy], [64.0+dx,6.0+dy]]) 314 new_points = g.get_absolute(points) 315 316 self.failUnless(isinstance(new_points, num.ndarray), 'failed') 317 self.failUnless(type(new_points) == type(points), 'failed') 318 msg = ('First call of .get_absolute() returned %s\nexpected %s' 319 % (str(new_points), str(expected_new_points))) 320 self.failUnless(num.alltrue(expected_new_points == new_points), msg) 321 322 # and repeat from 'new_points = g.get_absolute(points)' above 323 # to see if second call with same input gives same results. 324 new_points = g.get_absolute(points) 325 326 self.failUnless(isinstance(new_points, num.ndarray), 'failed') 327 self.failUnless(type(new_points) == type(points), 'failed') 328 msg = ('Second call of .get_absolute() returned %s\nexpected %s' 329 % (str(new_points), str(expected_new_points))) 330 self.failUnless(num.alltrue(expected_new_points == new_points), msg) 331 332 # and repeat again to see if *third* call with same input 333 # gives same results. 334 new_points = g.get_absolute(points) 335 336 self.failUnless(isinstance(new_points, num.ndarray), 'failed') 337 self.failUnless(type(new_points) == type(points), 'failed') 338 msg = ('Second call of .get_absolute() returned %s\nexpected %s' 339 % (str(new_points), str(expected_new_points))) 340 self.failUnless(num.alltrue(expected_new_points == new_points), msg) 341 262 342 def test_is_absolute(self): 263 343 … … 427 507 if __name__ == "__main__": 428 508 429 suite = unittest.makeSuite(geo_referenceTestCase,'test') 509 #suite = unittest.makeSuite(geo_referenceTestCase,'test') 510 suite = unittest.makeSuite(geo_referenceTestCase,'test_get_absolute') 430 511 runner = unittest.TextTestRunner() #verbosity=2) 431 512 runner.run(suite) -
branches/numpy/anuga/coordinate_transforms/test_lat_long_UTM_conversion.py
r6149 r6304 12 12 from anuga.utilities.anuga_exceptions import ANUGAError 13 13 14 import Numericas num14 import numpy as num 15 15 16 16 -
branches/numpy/anuga/coordinate_transforms/test_redfearn.py
r6149 r6304 11 11 from anuga.utilities.anuga_exceptions import ANUGAError 12 12 13 import Numericas num13 import numpy as num 14 14 15 15 -
branches/numpy/anuga/culvert_flows/Test_Culvert_Flat_Water_Lev.py
r6150 r6304 26 26 from math import pi,pow,sqrt 27 27 28 import Numericas num28 import numpy as num 29 29 30 30 -
branches/numpy/anuga/culvert_flows/culvert_class.py
r6150 r6304 14 14 from anuga.config import minimum_allowed_height, velocity_protection 15 15 16 import Numericas num16 import numpy as num 17 17 18 18 -
branches/numpy/anuga/culvert_flows/culvert_polygons.py
r6150 r6304 6 6 from anuga.utilities.polygon import inside_polygon, polygon_area 7 7 8 import Numericas num8 import numpy as num 9 9 10 10 -
branches/numpy/anuga/culvert_flows/test_culvert_class.py
r6150 r6304 21 21 from math import pi,pow,sqrt 22 22 23 import Numericas num23 import numpy as num 24 24 25 25 … … 470 470 ref_volume = domain.get_quantity('stage').get_integral() 471 471 for t in domain.evolve(yieldstep = 1, finaltime = 25): 472 472 473 #print domain.timestepping_statistics() 473 474 new_volume = domain.get_quantity('stage').get_integral() 474 475 475 476 msg = 'Total volume has changed' 476 477 assert num.allclose(new_volume, ref_volume), msg … … 564 565 #------------------------------------------------------------- 565 566 if __name__ == "__main__": 566 #suite = unittest.makeSuite(Test_Culvert, 'test_that_culvert_rating_limits_flow_in_shallow_inlet_condition')567 567 suite = unittest.makeSuite(Test_Culvert, 'test') 568 runner = unittest.TextTestRunner() 568 runner = unittest.TextTestRunner() #verbosity=2) 569 569 runner.run(suite) 570 570 -
branches/numpy/anuga/damage_modelling/inundation_damage.py
r6151 r6304 10 10 from types import StringType 11 11 12 import Numericas num12 import numpy as num 13 13 14 14 … … 17 17 except ImportError: 18 18 # Hand-built mockup of the things we need from the kinds package, since it 19 # was recently removed from the standard Numeric distro. Some users may19 # was recently removed from the standard numeric distro. Some users may 20 20 # not have it by default. 21 21 class _bunch: … … 314 314 315 315 # the data being created 316 struct_damage = num.zeros(self.structure_count, num. Float)317 contents_damage = num.zeros(self.structure_count, num. Float)316 struct_damage = num.zeros(self.structure_count, num.float) 317 contents_damage = num.zeros(self.structure_count, num.float) 318 318 self.struct_inundated = ['']* self.structure_count 319 319 -
branches/numpy/anuga/damage_modelling/test_inundation_damage.py
r6151 r6304 17 17 from anuga.shallow_water.data_manager import get_dataobject 18 18 19 import Numericas num19 import numpy as num 20 20 21 21 … … 83 83 #Initial condition - with jumps 84 84 bed = domain.quantities['elevation'].vertex_values 85 stage = num.zeros(bed.shape, num. Float)85 stage = num.zeros(bed.shape, num.float) 86 86 87 87 h = 0.3 … … 153 153 #Initial condition - with jumps 154 154 bed = domain.quantities['elevation'].vertex_values 155 stage = num.zeros(bed.shape, num. Float)155 stage = num.zeros(bed.shape, num.float) 156 156 157 157 h = 30. … … 476 476 edm = EventDamageModel([0.0]*17, [0.0]*17, [0.0]*17, 477 477 [0.0]*17, [0.0]*17) 478 edm.struct_damage = num.zeros(17,num. Float)479 edm.contents_damage = num.zeros(17,num. Float)478 edm.struct_damage = num.zeros(17,num.float) 479 edm.contents_damage = num.zeros(17,num.float) 480 480 collapse_probability = {0.4:[0], #0 481 481 0.6:[1], #1 … … 597 597 pass 598 598 suite = unittest.makeSuite(Test_inundation_damage,'test') 599 #suite = unittest.makeSuite(Test_inundation_damage,'test_inundation_damage_list_as_input')600 599 runner = unittest.TextTestRunner() 601 600 runner.run(suite) -
branches/numpy/anuga/fit_interpolate/fit.py
r6244 r6304 45 45 class VertsWithNoTrianglesError(exceptions.Exception): pass 46 46 47 import Numericas num47 import numpy as num 48 48 49 49 … … 66 66 67 67 vertex_coordinates: List of coordinate pairs [xi, eta] of 68 points constituting a mesh (or an m x 2 Numeric array or68 points constituting a mesh (or an m x 2 numeric array or 69 69 a geospatial object) 70 70 Points may appear multiple times 71 71 (e.g. if vertices have discontinuities) 72 72 73 triangles: List of 3-tuples (or a Numeric array) of73 triangles: List of 3-tuples (or a numeric array) of 74 74 integers representing indices of all vertices in the mesh. 75 75 … … 251 251 if len(z.shape) > 1: 252 252 att_num = z.shape[1] 253 self.Atz = num.zeros((m,att_num), num. Float)253 self.Atz = num.zeros((m,att_num), num.float) 254 254 else: 255 255 att_num = 1 256 self.Atz = num.zeros((m,), num. Float)256 self.Atz = num.zeros((m,), num.float) 257 257 assert z.shape[0] == point_coordinates.shape[0] 258 258 … … 336 336 point_coordinates: The co-ordinates of the data points. 337 337 List of coordinate pairs [x, y] of 338 data points or an nx2 Numeric array or a Geospatial_data object338 data points or an nx2 numeric array or a Geospatial_data object 339 339 or points file filename 340 340 z: Single 1d vector or array of data at the point_coordinates. … … 382 382 if point_coordinates is None: 383 383 if verbose: print 'Warning: no data points in fit' 384 assert self.AtA <> None, 'no interpolation matrix' 385 assert self.Atz <> None 384 #assert self.AtA != None, 'no interpolation matrix' 385 #assert self.Atz != None 386 assert not self.AtA is None, 'no interpolation matrix' 387 assert not self.Atz is None 386 388 387 389 # FIXME (DSG) - do a message … … 433 435 point_coordinates: The co-ordinates of the data points. 434 436 List of coordinate pairs [x, y] of 435 data points or an nx2 Numeric array or a Geospatial_data object437 data points or an nx2 numeric array or a Geospatial_data object 436 438 z: Single 1d vector or array of data at the point_coordinates. 437 439 attribute_name: Used to get the z values from the … … 448 450 absolute = True) 449 451 450 # Convert input to Numeric arrays452 # Convert input to numeric arrays 451 453 if z is not None: 452 z = ensure_numeric(z, num. Float)454 z = ensure_numeric(z, num.float) 453 455 else: 454 456 msg = 'z not specified' … … 456 458 z = point_coordinates.get_attributes(attribute_name) 457 459 458 point_coordinates = ensure_numeric(point_coordinates, num. Float)460 point_coordinates = ensure_numeric(point_coordinates, num.float) 459 461 self._build_matrix_AtA_Atz(point_coordinates, z, verbose) 460 462 … … 556 558 Inputs: 557 559 vertex_coordinates: List of coordinate pairs [xi, eta] of 558 points constituting a mesh (or an m x 2 Numeric array or560 points constituting a mesh (or an m x 2 numeric array or 559 561 a geospatial object) 560 562 Points may appear multiple times 561 563 (e.g. if vertices have discontinuities) 562 564 563 triangles: List of 3-tuples (or a Numeric array) of565 triangles: List of 3-tuples (or a numeric array) of 564 566 integers representing indices of all vertices in the mesh. 565 567 566 568 point_coordinates: List of coordinate pairs [x, y] of data points 567 (or an nx2 Numeric array). This can also be a .csv/.txt/.pts569 (or an nx2 numeric array). This can also be a .csv/.txt/.pts 568 570 file name. 569 571 … … 593 595 # are None 594 596 595 #Convert input to Numeric arrays596 triangles = ensure_numeric(triangles, num. Int)597 #Convert input to numeric arrays 598 triangles = ensure_numeric(triangles, num.int) 597 599 vertex_coordinates = ensure_absolute(vertex_coordinates, 598 600 geo_reference = mesh_origin) … … 662 664 vertex_coordinates = mesh_dict['vertices'] 663 665 triangles = mesh_dict['triangles'] 664 if type(mesh_dict['vertex_attributes']) == num.ArrayType:666 if isinstance(mesh_dict['vertex_attributes'], num.ndarray): 665 667 old_point_attributes = mesh_dict['vertex_attributes'].tolist() 666 668 else: 667 669 old_point_attributes = mesh_dict['vertex_attributes'] 668 670 669 if type(mesh_dict['vertex_attribute_titles']) == num.ArrayType:671 if isinstance(mesh_dict['vertex_attribute_titles'], num.ndarray): 670 672 old_title_list = mesh_dict['vertex_attribute_titles'].tolist() 671 673 else: -
branches/numpy/anuga/fit_interpolate/general_fit_interpolate.py
r6152 r6304 35 35 from anuga.fit_interpolate.search_functions import set_last_triangle 36 36 37 import Numericas num37 import numpy as num 38 38 39 39 … … 67 67 68 68 vertex_coordinates: List of coordinate pairs [xi, eta] of 69 points constituting a mesh (or an m x 2 Numeric array or69 points constituting a mesh (or an m x 2 numeric array or 70 70 a geospatial object) 71 71 Points may appear multiple times 72 72 (e.g. if vertices have discontinuities) 73 73 74 triangles: List of 3-tuples (or a Numeric array) of74 triangles: List of 3-tuples (or a numeric array) of 75 75 integers representing indices of all vertices in the mesh. 76 76 … … 96 96 # are None 97 97 98 #Convert input to Numeric arrays99 triangles = ensure_numeric(triangles, num. Int)98 #Convert input to numeric arrays 99 triangles = ensure_numeric(triangles, num.int) 100 100 vertex_coordinates = ensure_absolute(vertex_coordinates, 101 101 geo_reference = mesh_origin) -
branches/numpy/anuga/fit_interpolate/interpolate.py
r6223 r6304 41 41 42 42 43 import Numericas num43 import numpy as num 44 44 45 45 … … 77 77 vertex_coordinates: List of coordinate pairs [xi, eta] of 78 78 points constituting a mesh 79 (or an m x 2 Numeric array or79 (or an m x 2 numeric array or 80 80 a geospatial object) 81 81 Points may appear multiple times 82 82 (e.g. if vertices have discontinuities) 83 83 84 triangles: List of 3-tuples (or a Numeric array) of84 triangles: List of 3-tuples (or a numeric array) of 85 85 integers representing indices of all vertices 86 86 in the mesh. … … 92 92 interpolation_points: Interpolate mesh data to these positions. 93 93 List of coordinate pairs [x, y] of 94 data points or an nx2 Numeric array or a94 data points or an nx2 numeric array or a 95 95 Geospatial_data object 96 96 … … 132 132 133 133 # Create interpolation object with matrix 134 args = (ensure_numeric(vertex_coordinates, num. Float),134 args = (ensure_numeric(vertex_coordinates, num.float), 135 135 ensure_numeric(triangles)) 136 136 kwargs = {'mesh_origin': mesh_origin, … … 181 181 Inputs: 182 182 vertex_coordinates: List of coordinate pairs [xi, eta] of 183 points constituting a mesh (or an m x 2 Numeric array or183 points constituting a mesh (or an m x 2 numeric array or 184 184 a geospatial object) 185 185 Points may appear multiple times 186 186 (e.g. if vertices have discontinuities) 187 187 188 triangles: List of 3-tuples (or a Numeric array) of188 triangles: List of 3-tuples (or a numeric array) of 189 189 integers representing indices of all vertices in the mesh. 190 190 … … 243 243 point_coordinates: Interpolate mesh data to these positions. 244 244 List of coordinate pairs [x, y] of 245 data points or an nx2 Numeric array or a Geospatial_data object245 data points or an nx2 numeric array or a Geospatial_data object 246 246 247 247 If point_coordinates is absent, the points inputted last time … … 294 294 # creating a dummy array to concatenate to. 295 295 296 f = ensure_numeric(f, num. Float)296 f = ensure_numeric(f, num.float) 297 297 if len(f.shape) > 1: 298 z = num.zeros((0, f.shape[1]) )298 z = num.zeros((0, f.shape[1]), num.int) #array default# 299 299 else: 300 z = num.zeros((0,) )300 z = num.zeros((0,), num.int) #array default# 301 301 302 302 for end in range(start_blocking_len, … … 340 340 point_coordinates = point_coordinates.get_data_points(absolute=True) 341 341 342 # Convert lists to Numeric arrays if necessary343 point_coordinates = ensure_numeric(point_coordinates, num. Float)344 f = ensure_numeric(f, num. Float)342 # Convert lists to numeric arrays if necessary 343 point_coordinates = ensure_numeric(point_coordinates, num.float) 344 f = ensure_numeric(f, num.float) 345 345 346 346 from anuga.caching import myhash … … 447 447 if verbose: print 'Building interpolation matrix' 448 448 449 # Convert point_coordinates to Numeric arrays, in case it was a list.450 point_coordinates = ensure_numeric(point_coordinates, num. Float)449 # Convert point_coordinates to numeric arrays, in case it was a list. 450 point_coordinates = ensure_numeric(point_coordinates, num.float) 451 451 452 452 if verbose: print 'Getting indices inside mesh boundary' … … 526 526 points: Interpolate mesh data to these positions. 527 527 List of coordinate pairs [x, y] of 528 data points or an nx2 Numeric array or a Geospatial_data object528 data points or an nx2 numeric array or a Geospatial_data object 529 529 530 530 No test for this yet. … … 694 694 695 695 Mandatory input 696 time: px1 array of monotonously increasing times ( Float)697 quantities: Dictionary of arrays or 1 array ( Float)696 time: px1 array of monotonously increasing times (float) 697 quantities: Dictionary of arrays or 1 array (float) 698 698 The arrays must either have dimensions pxm or mx1. 699 699 The resulting function will be time dependent in … … 704 704 quantity_names: List of keys into the quantities dictionary for 705 705 imposing a particular order on the output vector. 706 vertex_coordinates: mx2 array of coordinates ( Float)706 vertex_coordinates: mx2 array of coordinates (float) 707 707 triangles: nx3 array of indices into vertex_coordinates (Int) 708 708 interpolation_points: Nx2 array of coordinates to be interpolated to … … 810 810 self.quantities_range = {} 811 811 for name in quantity_names: 812 q = quantities[name][:].flat 812 q = quantities[name][:].flatten() 813 813 self.quantities_range[name] = [min(q), max(q)] 814 814 … … 830 830 interpolation_points = ensure_numeric(interpolation_points) 831 831 except: 832 msg = 'Interpolation points must be an N x 2 Numeric array ' \832 msg = 'Interpolation points must be an N x 2 numeric array ' \ 833 833 'or a list of points\n' 834 834 msg += 'Got: %s.' %(str(self.interpolation_points)[:60] + '...') … … 913 913 914 914 for name in quantity_names: 915 self.precomputed_values[name] = num.zeros((p, m), num. Float)915 self.precomputed_values[name] = num.zeros((p, m), num.float) 916 916 917 917 if verbose is True: … … 1056 1056 1057 1057 # Compute interpolated values 1058 q = num.zeros(len(self.quantity_names), num. Float)1058 q = num.zeros(len(self.quantity_names), num.float) 1059 1059 for i, name in enumerate(self.quantity_names): 1060 1060 Q = self.precomputed_values[name] … … 1105 1105 res = [] 1106 1106 for col in q: 1107 res.append(col*num.ones(N, num. Float))1107 res.append(col*num.ones(N, num.float)) 1108 1108 1109 1109 return res … … 1145 1145 minq, maxq = self.quantities_range[name] 1146 1146 str += ' %s in [%f, %f]\n' %(name, minq, maxq) 1147 #q = quantities[name][:].flat 1147 #q = quantities[name][:].flatten() 1148 1148 #str += ' %s in [%f, %f]\n' %(name, min(q), max(q)) 1149 1149 … … 1158 1158 1159 1159 for name in quantity_names: 1160 q = precomputed_values[name][:].flat 1160 q = precomputed_values[name][:].flatten() 1161 1161 str += ' %s at interpolation points in [%f, %f]\n'\ 1162 1162 %(name, min(q), max(q)) … … 1190 1190 1191 1191 #Add the x and y together 1192 vertex_coordinates = num.concatenate((x[:,num. NewAxis], y[:,num.NewAxis]),axis=1)1192 vertex_coordinates = num.concatenate((x[:,num.newaxis], y[:,num.newaxis]),axis=1) 1193 1193 1194 1194 #Will return the quantity values at the specified times and locations … … 1262 1262 keys.remove("volumes") 1263 1263 keys.remove("time") 1264 #Turn NetCDF objects into Numeric arrays1264 #Turn NetCDF objects into numeric arrays 1265 1265 quantities = {} 1266 1266 for name in keys: -
branches/numpy/anuga/fit_interpolate/search_functions.py
r6174 r6304 11 11 from anuga.config import max_float 12 12 13 import Numericas num13 import numpy as num 14 14 15 15 … … 22 22 num.array([max_float,max_float]), 23 23 num.array([max_float,max_float])), 24 (num.array([1,1] , num.Int), #array default#25 num.array([0,0] , num.Int), #array default#24 (num.array([1,1]), 25 num.array([0,0]), 26 26 num.array([-1.1,-1.1]))]]] 27 27 -
branches/numpy/anuga/fit_interpolate/test_fit.py
r6174 r6304 21 21 from anuga.shallow_water import Domain 22 22 23 import Numericas num23 import numpy as num 24 24 25 25 … … 582 582 583 583 #Define f(x,y) = x 584 f = num.array([0,0,2] , num.Int) #Value at global vertex 2 #array default#584 f = num.array([0,0,2]) #Value at global vertex 2 585 585 586 586 #Check that int (df/dx)**2 + (df/dy)**2 dx dy = … … 589 589 590 590 #Define f(x,y) = y 591 f = num.array([0,2,0] , num.Int) #Value at global vertex 1 #array default#591 f = num.array([0,2,0]) #Value at global vertex 1 592 592 593 593 #Check that int (df/dx)**2 + (df/dy)**2 dx dy = … … 596 596 597 597 #Define f(x,y) = x+y 598 f = num.array([0,2,2] , num.Int) #Values at global vertex 1 and 2 #array default#598 f = num.array([0,2,2]) #Values at global vertex 1 and 2 599 599 600 600 #Check that int (df/dx)**2 + (df/dy)**2 dx dy = … … 623 623 624 624 #Define f(x,y) = x 625 f = num.array([0,0,2,0,2,4] , num.Int) #f evaluated at points a-f #array default#625 f = num.array([0,0,2,0,2,4]) #f evaluated at points a-f 626 626 627 627 #Check that int (df/dx)**2 + (df/dy)**2 dx dy = … … 630 630 631 631 #Define f(x,y) = y 632 f = num.array([0,2,0,4,2,0] , num.Int) #f evaluated at points a-f #array default#632 f = num.array([0,2,0,4,2,0]) #f evaluated at points a-f 633 633 634 634 #Check that int (df/dx)**2 + (df/dy)**2 dx dy = … … 637 637 638 638 #Define f(x,y) = x+y 639 f = num.array([0,2,2,4,4,4] , num.Int) #f evaluated at points a-f #array default#639 f = num.array([0,2,2,4,4,4]) #f evaluated at points a-f 640 640 641 641 #Check that int (df/dx)**2 + (df/dy)**2 dx dy = … … 1099 1099 if __name__ == "__main__": 1100 1100 suite = unittest.makeSuite(Test_Fit,'test') 1101 #suite = unittest.makeSuite(Test_Fit,'test_smooth_attributes_to_mesh_function') 1102 #suite = unittest.makeSuite(Test_Fit,'') 1103 runner = unittest.TextTestRunner(verbosity=1) 1101 runner = unittest.TextTestRunner() #verbosity=1) 1104 1102 runner.run(suite) 1105 1103 -
branches/numpy/anuga/fit_interpolate/test_interpolate.py
r6189 r6304 15 15 from Scientific.IO.NetCDF import NetCDFFile 16 16 17 import Numericas num17 import numpy as num 18 18 19 19 … … 67 67 68 68 bed = domain.quantities['elevation'].vertex_values 69 stage = num.zeros(bed.shape, num. Float)69 stage = num.zeros(bed.shape, num.float) 70 70 71 71 h = 0.3 … … 129 129 130 130 x, y, vertex_values, triangles = quantity.get_vertex_values(xy=True, smooth=False) 131 vertex_coordinates = num.concatenate( (x[:, num. NewAxis], y[:, num.NewAxis]), axis=1 )131 vertex_coordinates = num.concatenate( (x[:, num.newaxis], y[:, num.newaxis]), axis=1 ) 132 132 # FIXME: This concat should roll into get_vertex_values 133 133 … … 149 149 150 150 x, y, vertex_values, triangles = quantity.get_vertex_values(xy=True, smooth=False) 151 vertex_coordinates = num.concatenate( (x[:, num. NewAxis], y[:, num.NewAxis]), axis=1 )151 vertex_coordinates = num.concatenate( (x[:, num.newaxis], y[:, num.newaxis]), axis=1 ) 152 152 # FIXME: This concat should roll into get_vertex_values 153 153 … … 182 182 183 183 x, y, vertex_values, triangles = quantity.get_vertex_values(xy=True, smooth=False) 184 vertex_coordinates = num.concatenate( (x[:, num. NewAxis], y[:, num.NewAxis]), axis=1 )184 vertex_coordinates = num.concatenate( (x[:, num.newaxis], y[:, num.newaxis]), axis=1 ) 185 185 # FIXME: This concat should roll into get_vertex_values 186 186 … … 201 201 202 202 x, y, vertex_values, triangles = quantity.get_vertex_values(xy=True, smooth=False) 203 vertex_coordinates = num.concatenate( (x[:, num. NewAxis], y[:, num.NewAxis]), axis=1 )203 vertex_coordinates = num.concatenate( (x[:, num.newaxis], y[:, num.newaxis]), axis=1 ) 204 204 # FIXME: This concat should roll into get_vertex_values 205 205 … … 233 233 234 234 x, y, vertex_values, triangles = quantity.get_vertex_values(xy=True, smooth=False) 235 vertex_coordinates = num.concatenate( (x[:, num. NewAxis], y[:, num.NewAxis]), axis=1 )235 vertex_coordinates = num.concatenate( (x[:, num.newaxis], y[:, num.newaxis]), axis=1 ) 236 236 # FIXME: This concat should roll into get_vertex_values 237 237 … … 1078 1078 1079 1079 #One quantity 1080 Q = num.zeros( (3,6), num. Float )1080 Q = num.zeros( (3,6), num.float ) 1081 1081 1082 1082 #Linear in time and space … … 1225 1225 1226 1226 #One quantity 1227 Q = num.zeros( (3,6), num. Float )1227 Q = num.zeros( (3,6), num.float ) 1228 1228 1229 1229 #Linear in time and space … … 1285 1285 1286 1286 # One quantity 1287 Q = num.zeros((8,6), num. Float)1287 Q = num.zeros((8,6), num.float) 1288 1288 1289 1289 # Linear in time and space … … 1353 1353 1354 1354 #One quantity 1355 Q = num.zeros( (2,6), num. Float )1355 Q = num.zeros( (2,6), num.float ) 1356 1356 1357 1357 #Linear in time and space … … 1419 1419 1420 1420 # One quantity 1421 Q = num.zeros( (3,6), num. Float )1421 Q = num.zeros( (3,6), num.float ) 1422 1422 1423 1423 # Linear in time and space … … 1608 1608 1609 1609 #One quantity 1610 Q = num.zeros( (len(time),6), num. Float )1610 Q = num.zeros( (len(time),6), num.float ) 1611 1611 1612 1612 #Linear in time and space … … 1850 1850 if __name__ == "__main__": 1851 1851 suite = unittest.makeSuite(Test_Interpolate,'test') 1852 #suite = unittest.makeSuite(Test_Interpolate,'test_interpolate_one_point_many_triangles') 1853 runner = unittest.TextTestRunner(verbosity=1) 1852 runner = unittest.TextTestRunner() #verbosity=1) 1854 1853 runner.run(suite) 1855 1854 -
branches/numpy/anuga/fit_interpolate/test_search_functions.py
r6152 r6304 211 211 if __name__ == "__main__": 212 212 suite = unittest.makeSuite(Test_search_functions,'test') 213 #suite = unittest.makeSuite(Test_search_functions,'expanding_search') 214 runner = unittest.TextTestRunner(verbosity=1) 213 runner = unittest.TextTestRunner() #verbosity=1) 215 214 runner.run(suite) 216 215 -
branches/numpy/anuga/geospatial_data/geospatial_data.py
r6166 r6304 13 13 from Scientific.IO.NetCDF import NetCDFFile 14 14 15 import Numericas num15 import numpy as num 16 16 17 17 from anuga.coordinate_transforms.lat_long_UTM_conversion import UTMtoLL … … 23 23 from anuga.config import points_file_block_line_size as MAX_READ_LINES 24 24 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 25 from anuga.config import netcdf_float 25 26 26 27 DEFAULT_ATTRIBUTE = 'elevation' … … 56 57 load_file_now=True, 57 58 verbose=False): 58 """ 59 Create instance from data points and associated attributes 59 """Create instance from data points and associated attributes 60 60 61 61 data_points: x,y coordinates in meters. Type must be either a 62 sequence of 2-tuples or an Mx2 Numeric array of floats. A file name62 sequence of 2-tuples or an Mx2 numeric array of floats. A file name 63 63 with extension .txt, .cvs or .pts can also be passed in here. 64 64 … … 131 131 132 132 verbose: 133 134 133 """ 135 134 136 135 if isinstance(data_points, basestring): 137 # assume data pointis really a file name136 # assume data_points is really a file name 138 137 file_name = data_points 139 138 140 139 self.set_verbose(verbose) 141 self.geo_reference = None # create the attribute140 self.geo_reference = None # create the attribute 142 141 self.file_name = file_name 143 142 … … 157 156 data_points=data_points, 158 157 points_are_lats_longs=\ 159 158 points_are_lats_longs) 160 159 self.check_data_points(data_points) 161 160 self.set_attributes(attributes) … … 188 187 # This message was misleading. 189 188 # FIXME (Ole): Are we blocking here or not? 190 # print 'ASCII formats are not that great for '191 # print 'blockwise reading. Consider storing this'192 # print 'data as a pts NetCDF format'189 # print 'ASCII formats are not that great for ' 190 # print 'blockwise reading. Consider storing this' 191 # print 'data as a pts NetCDF format' 193 192 194 193 ## … … 203 202 204 203 ## 205 # @brief Save points data in instance.206 # @param data_points Points data to store in instance and check.204 # @brief Check data points. 205 # @param data_points Points data to check and store in instance. 207 206 # @note Throws ValueError exception if no data. 208 207 def check_data_points(self, data_points): 209 """Checks data points 210 """ 208 """Checks data points""" 211 209 212 210 if data_points is None: … … 217 215 else: 218 216 self.data_points = ensure_numeric(data_points) 217 return 218 219 print 'self.data_points=%s' % str(self.data_points) 220 print 'self.data_points.shape=%s' % str(self.data_points.shape) 219 221 if not (0,) == self.data_points.shape: 220 222 assert len(self.data_points.shape) == 2 … … 226 228 # @note Throws exception if unable to convert dict keys to numeric. 227 229 def set_attributes(self, attributes): 228 """Check and assign attributes dictionary 229 """ 230 """Check and assign attributes dictionary""" 230 231 231 232 if attributes is None: … … 234 235 235 236 if not isinstance(attributes, DictType): 236 # Convert single attribute into dictionary237 # Convert single attribute into dictionary 237 238 attributes = {DEFAULT_ATTRIBUTE: attributes} 238 239 239 # Check input attributes240 # Check input attributes 240 241 for key in attributes.keys(): 241 242 try: 242 243 attributes[key] = ensure_numeric(attributes[key]) 243 244 except: 244 msg = 'Attribute %s could not be converted' %key245 msg += 'to a numeric vector'246 raise msg245 msg = ("Attribute '%s' (%s) could not be converted to a" 246 "numeric vector" % (str(key), str(attributes[key]))) 247 raise Exception, msg 247 248 248 249 self.attributes = attributes 249 250 250 #def set_geo_reference(self, geo_reference):251 # # FIXME (Ole): Backwards compatibility - deprecate252 # self.setgeo_reference(geo_reference)253 254 251 ## 255 252 # @brief Set the georeference of geospatial data. 256 # @param geo_reference The georeference data 253 # @param geo_reference The georeference data to set. 257 254 # @note Will raise exception if param not instance of Geo_reference. 258 255 def set_geo_reference(self, geo_reference): … … 277 274 msg = 'Argument geo_reference must be a valid Geo_reference ' 278 275 msg += 'object or None.' 279 raise msg276 raise Expection, msg 280 277 281 278 # If a geo_reference already exists, change the point data according to … … 511 508 raise Exception, msg 512 509 else: 513 # other is None:510 # other is None: 514 511 new_points = self.get_data_points(absolute=True) 515 512 new_attributes = self.attributes … … 525 522 # @return The new geospatial object. 526 523 def __radd__(self, other): 527 """Handle cases like None + Geospatial_data(...) 528 """ 524 """Handle cases like None + Geospatial_data(...)""" 529 525 530 526 return self + other … … 542 538 def import_points_file(self, file_name, delimiter=None, verbose=False): 543 539 """ load an .txt, .csv or .pts file 540 544 541 Note: will throw an IOError/SyntaxError if it can't load the file. 545 542 Catch these! … … 571 568 except SyntaxError, e: 572 569 # This should only be if there is a format error 573 msg = ' Could not openfile %s. \n' %file_name570 msg = 'Problem with format of file %s. \n' %file_name 574 571 msg += Error_message['IOError'] 575 572 raise SyntaxError, msg … … 591 588 as_lat_long=False, isSouthHemisphere=True): 592 589 593 """ 594 write a points file, file_name, as a text (.csv) or binary (.pts) file 590 """write a points file as a text (.csv) or binary (.pts) file 591 595 592 file_name is the file name, including the extension 596 593 The point_dict is defined at the top of this file. … … 659 656 """ 660 657 661 # FIXME: add the geo_reference to this658 # FIXME: add the geo_reference to this 662 659 points = self.get_data_points() 663 660 sampled_points = num.take(points, indices) … … 679 676 # @note Points in each result object are selected randomly. 680 677 def split(self, factor=0.5, seed_num=None, verbose=False): 681 """Returns two 682 geospatial_data object, first is the size of the 'factor' 678 """Returns two geospatial_data object, first is the size of the 'factor' 683 679 smaller the original and the second is the remainder. The two 684 new object are disjoin setof each other.680 new objects are disjoint sets of each other. 685 681 686 682 Points of the two new object have selected RANDOMLY. … … 707 703 if verbose: print "make unique random number list and get indices" 708 704 709 total=num.array(range(self_size) , num.Int) #array default#705 total=num.array(range(self_size)) 710 706 total_list = total.tolist() 711 707 … … 731 727 random_num = random_num.tolist() 732 728 733 # need to sort and reverse so the pop() works correctly729 # need to sort and reverse so the pop() works correctly 734 730 random_num.sort() 735 731 random_num.reverse() … … 748 744 random_list.append(remainder_list.pop(i)) 749 745 j += 1 750 # prints progress746 # prints progress 751 747 if verbose and round(random_num_len/10*k) == j: 752 748 print '(%s/%s)' % (j, random_num_len) … … 779 775 """ 780 776 from Scientific.IO.NetCDF import NetCDFFile 781 # FIXME - what to do if the file isn't there777 # FIXME - what to do if the file isn't there 782 778 783 779 # FIXME (Ole): Shouldn't this go into the constructor? … … 941 937 data_points, 942 938 points_are_lats_longs): 943 """ 944 if the points has lat long info, assume it is in (lat, long) order. 945 """ 939 """If the points has lat long info, assume it is in (lat, long) order.""" 946 940 947 941 if geo_reference is not None: … … 1055 1049 header, 1056 1050 max_read_lines=1e30) 1057 # If the file is bigger that this, block..1051 # If the file is bigger that this, block.. 1058 1052 # FIXME (Ole) What's up here? 1059 1053 except ANUGAError: … … 1082 1076 """ 1083 1077 1084 line = file_pointer.readline() 1078 line = file_pointer.readline().strip() 1085 1079 header = clean_line(line, delimiter) 1086 1080 … … 1095 1089 # @param verbose True if this function is to be verbose. 1096 1090 # @note Will throw IndexError, SyntaxError exceptions. 1097 def _read_csv_file_blocking(file_pointer, header, 1091 def _read_csv_file_blocking(file_pointer, 1092 header, 1098 1093 delimiter=CSV_DELIMITER, 1099 1094 max_read_lines=MAX_READ_LINES, … … 1150 1145 raise StopIteration 1151 1146 1152 pointlist = num.array(points, num. Float)1147 pointlist = num.array(points, num.float) 1153 1148 for key in att_dict.keys(): 1154 att_dict[key] = num.array(att_dict[key], num. Float)1149 att_dict[key] = num.array(att_dict[key], num.float) 1155 1150 1156 1151 # Do stuff here so the info is in lat's and longs … … 1183 1178 # @note Will throw IOError and AttributeError exceptions. 1184 1179 def _read_pts_file_header(fid, verbose=False): 1185 """Read the geo_reference and number_of_points from a .pts file 1186 """ 1180 """Read the geo_reference and number_of_points from a .pts file""" 1187 1181 1188 1182 keys = fid.variables.keys() … … 1212 1206 # @return Tuple of (pointlist, attributes). 1213 1207 def _read_pts_file_blocking(fid, start_row, fin_row, keys): 1214 """Read the body of a .csv file. 1215 """ 1208 """Read the body of a .csv file.""" 1216 1209 1217 1210 pointlist = num.array(fid.variables['points'][start_row:fin_row]) … … 1239 1232 1240 1233 WARNING: This function mangles the point_atts data structure 1241 # F??ME: (DSG)This format has issues.1234 # F??ME: (DSG)This format has issues. 1242 1235 # There can't be an attribute called points 1243 1236 # consider format change … … 1264 1257 shape = write_data_points.shape[0] 1265 1258 outfile.createDimension('number_of_points', shape) 1266 outfile.createDimension('number_of_dimensions', 2) # This is 2d data1259 outfile.createDimension('number_of_dimensions', 2) # This is 2d data 1267 1260 1268 1261 # Variable definition 1269 outfile.createVariable('points', n um.Float, ('number_of_points',1270 'number_of_dimensions'))1271 1272 # create variables1273 outfile.variables['points'][:] = write_data_points #.astype(Float32)1262 outfile.createVariable('points', netcdf_float, ('number_of_points', 1263 'number_of_dimensions')) 1264 1265 # create variables 1266 outfile.variables['points'][:] = write_data_points 1274 1267 1275 1268 if write_attributes is not None: 1276 1269 for key in write_attributes.keys(): 1277 outfile.createVariable(key, n um.Float, ('number_of_points',))1278 outfile.variables[key][:] = write_attributes[key] #.astype(Float32)1270 outfile.createVariable(key, netcdf_float, ('number_of_points',)) 1271 outfile.variables[key][:] = write_attributes[key] 1279 1272 1280 1273 if write_geo_reference is not None: … … 1296 1289 as_lat_long=False, 1297 1290 delimiter=','): 1298 """Write a .csv file. 1299 """ 1291 """Write a .csv file.""" 1300 1292 1301 1293 points = write_data_points … … 1361 1353 # @return ?? 1362 1354 def _point_atts2array(point_atts): 1363 point_atts['pointlist'] = num.array(point_atts['pointlist'], num. Float)1355 point_atts['pointlist'] = num.array(point_atts['pointlist'], num.float) 1364 1356 1365 1357 for key in point_atts['attributelist'].keys(): 1366 1358 point_atts['attributelist'][key] = \ 1367 num.array(point_atts['attributelist'][key], num. Float)1359 num.array(point_atts['attributelist'][key], num.float) 1368 1360 1369 1361 return point_atts … … 1375 1367 # @return A points dictionary. 1376 1368 def geospatial_data2points_dictionary(geospatial_data): 1377 """Convert geospatial data to points_dictionary 1378 """ 1369 """Convert geospatial data to points_dictionary""" 1379 1370 1380 1371 points_dictionary = {} … … 1396 1387 # @param points_dictionary A points dictionary to convert. 1397 1388 def points_dictionary2geospatial_data(points_dictionary): 1398 """Convert points_dictionary to geospatial data object 1399 """ 1389 """Convert points_dictionary to geospatial data object""" 1400 1390 1401 1391 msg = 'Points dictionary must have key pointlist' … … 1417 1407 ## 1418 1408 # @brief Split a string into 'clean' fields. 1419 # @param lineThe string to process.1409 # @param str The string to process. 1420 1410 # @param delimiter The delimiter string to split 'line' with. 1421 1411 # @return A list of 'cleaned' field strings. 1422 1412 # @note Any fields that were initially zero length will be removed. 1423 def clean_line(line,delimiter): 1424 """Remove whitespace 1425 """ 1426 1427 line = line.strip() # probably unnecessary RW 1428 numbers = line.split(delimiter) 1429 1430 i = len(numbers) - 1 1431 while i >= 0: 1432 if numbers[i] == '': 1433 numbers.pop(i) 1434 else: 1435 numbers[i] = numbers[i].strip() 1436 i += -1 1437 1438 return numbers 1413 # @note If a field contains '\n' it isn't zero length. 1414 def clean_line(str, delimiter): 1415 """Split string on given delimiter, remove whitespace from each field.""" 1416 1417 return [x.strip() for x in str.split(delimiter) if x != ''] 1439 1418 1440 1419 … … 1462 1441 # Input check 1463 1442 if isinstance(points, basestring): 1464 # It's a string - assume it is a point file1443 # It's a string - assume it is a point file 1465 1444 points = Geospatial_data(file_name=points) 1466 1445 … … 1470 1449 assert geo_reference == None, msg 1471 1450 else: 1472 points = ensure_numeric(points, num. Float)1451 points = ensure_numeric(points, num.float) 1473 1452 1474 1453 # Sort of geo_reference and convert points 1475 1454 if geo_reference is None: 1476 geo = None # Geo_reference()1455 geo = None # Geo_reference() 1477 1456 else: 1478 1457 if isinstance(geo_reference, Geo_reference): … … 1493 1472 # @return A geospatial object. 1494 1473 def ensure_geospatial(points, geo_reference=None): 1495 """ 1496 This function inputs several formats and 1497 outputs one format. - a geospatial_data instance. 1474 """Convert various data formats to a geospatial_data instance. 1498 1475 1499 1476 Inputed formats are; … … 1514 1491 else: 1515 1492 # List or numeric array of absolute points 1516 points = ensure_numeric(points, num. Float)1493 points = ensure_numeric(points, num.float) 1517 1494 1518 1495 # Sort out geo reference … … 1563 1540 cache=False, 1564 1541 verbose=False): 1565 """ 1566 Removes a small random sample of points from 'data_file'. Then creates 1567 models with different alpha values from 'alpha_list' and cross validates 1568 the predicted value to the previously removed point data. Returns the 1569 alpha value which has the smallest covariance. 1542 """Removes a small random sample of points from 'data_file'. 1543 Then creates models with different alpha values from 'alpha_list' and 1544 cross validates the predicted value to the previously removed point data. 1545 Returns the alpha value which has the smallest covariance. 1570 1546 1571 1547 data_file: must not contain points outside the boundaries defined … … 1628 1604 if no_boundary is True: 1629 1605 msg = 'All boundaries must be defined' 1630 raise msg1606 raise Expection, msg 1631 1607 1632 1608 poly_topo = [[east_boundary,south_boundary], … … 1645 1621 1646 1622 else: # if mesh file provided 1647 # test mesh file exists?1623 # test mesh file exists? 1648 1624 if verbose: "reading from file: %s" % mesh_file 1649 1625 if access(mesh_file,F_OK) == 0: … … 1651 1627 raise IOError, msg 1652 1628 1653 # split topo data1629 # split topo data 1654 1630 if verbose: print 'Reading elevation file: %s' % data_file 1655 1631 G = Geospatial_data(file_name = data_file) … … 1668 1644 alphas = alpha_list 1669 1645 1670 # creates array with columns 1 and 2 are x, y. column 3 is elevation1671 # 4 onwards is the elevation_predicted using the alpha, which will1672 # be compared later against the real removed data1673 data = num.array([], typecode=num.Float)1646 # creates array with columns 1 and 2 are x, y. column 3 is elevation 1647 # 4 onwards is the elevation_predicted using the alpha, which will 1648 # be compared later against the real removed data 1649 data = num.array([], dtype=num.float) 1674 1650 1675 1651 data=num.resize(data, (len(points), 3+len(alphas))) 1676 1652 1677 # gets relative point from sample1653 # gets relative point from sample 1678 1654 data[:,0] = points[:,0] 1679 1655 data[:,1] = points[:,1] … … 1681 1657 data[:,2] = elevation_sample 1682 1658 1683 normal_cov=num.array(num.zeros([len(alphas), 2]), typecode=num.Float)1659 normal_cov=num.array(num.zeros([len(alphas), 2]), dtype=num.float) 1684 1660 1685 1661 if verbose: print 'Setup computational domains with different alphas' 1686 1662 1687 1663 for i, alpha in enumerate(alphas): 1688 # add G_other data to domains with different alphas1664 # add G_other data to domains with different alphas 1689 1665 if verbose: 1690 1666 print '\n Calculating domain and mesh for Alpha = ', alpha, '\n' … … 1700 1676 points_geo = Geospatial_data(points, domain.geo_reference) 1701 1677 1702 # returns the predicted elevation of the points that were "split" out1703 # of the original data set for one particular alpha1678 # returns the predicted elevation of the points that were "split" out 1679 # of the original data set for one particular alpha 1704 1680 if verbose: print 'Get predicted elevation for location to be compared' 1705 1681 elevation_predicted = \ … … 1707 1683 get_values(interpolation_points=points_geo) 1708 1684 1709 # add predicted elevation to array that starts with x, y, z...1685 # add predicted elevation to array that starts with x, y, z... 1710 1686 data[:,i+3] = elevation_predicted 1711 1687 … … 1834 1810 if no_boundary is True: 1835 1811 msg = 'All boundaries must be defined' 1836 raise msg1812 raise Expection, msg 1837 1813 1838 1814 poly_topo = [[east_boundary,south_boundary], … … 1851 1827 1852 1828 else: # if mesh file provided 1853 # test mesh file exists?1829 # test mesh file exists? 1854 1830 if access(mesh_file,F_OK) == 0: 1855 1831 msg = "file %s doesn't exist!" % mesh_file 1856 1832 raise IOError, msg 1857 1833 1858 # split topo data1834 # split topo data 1859 1835 G = Geospatial_data(file_name=data_file) 1860 1836 if verbose: print 'start split' … … 1863 1839 points = G_small.get_data_points() 1864 1840 1865 # FIXME: Remove points outside boundary polygon1841 # FIXME: Remove points outside boundary polygon 1866 1842 # print 'new point',len(points) 1867 1843 # 1868 1844 # new_points=[] 1869 # new_points=array([], typecode=Float)1845 # new_points=array([],dtype=float) 1870 1846 # new_points=resize(new_points,(len(points),2)) 1871 1847 # print "BOUNDARY", boundary_poly … … 1890 1866 1891 1867 for alpha in alphas: 1892 # add G_other data to domains with different alphas1868 # add G_other data to domains with different alphas 1893 1869 if verbose: 1894 1870 print '\n Calculating domain and mesh for Alpha = ', alpha, '\n' … … 1902 1878 domains[alpha] = domain 1903 1879 1904 # creates array with columns 1 and 2 are x, y. column 3 is elevation1905 # 4 onwards is the elevation_predicted using the alpha, which will1906 # be compared later against the real removed data1907 data = num.array([], typecode=num.Float)1880 # creates array with columns 1 and 2 are x, y. column 3 is elevation 1881 # 4 onwards is the elevation_predicted using the alpha, which will 1882 # be compared later against the real removed data 1883 data = num.array([], dtype=num.float) 1908 1884 1909 1885 data = num.resize(data, (len(points), 3+len(alphas))) 1910 1886 1911 # gets relative point from sample1887 # gets relative point from sample 1912 1888 data[:,0] = points[:,0] 1913 1889 data[:,1] = points[:,1] … … 1915 1891 data[:,2] = elevation_sample 1916 1892 1917 normal_cov = num.array(num.zeros([len(alphas), 2]), typecode=num.Float)1893 normal_cov = num.array(num.zeros([len(alphas), 2]), dtype=num.float) 1918 1894 1919 1895 if verbose: … … 1923 1899 1924 1900 points_geo = domains[alpha].geo_reference.change_points_geo_ref(points) 1925 # returns the predicted elevation of the points that were "split" out1926 # of the original data set for one particular alpha1901 # returns the predicted elevation of the points that were "split" out 1902 # of the original data set for one particular alpha 1927 1903 elevation_predicted = \ 1928 1904 domains[alpha].quantities[attribute_smoothed].\ 1929 1905 get_values(interpolation_points=points_geo) 1930 1906 1931 # add predicted elevation to array that starts with x, y, z...1907 # add predicted elevation to array that starts with x, y, z... 1932 1908 data[:,i+3] = elevation_predicted 1933 1909 -
branches/numpy/anuga/geospatial_data/test_geospatial_data.py
r6153 r6304 1 1 #!/usr/bin/env python 2 3 2 4 3 import unittest 5 4 import os 5 import tempfile 6 6 from math import sqrt, pi 7 import tempfile8 7 from sets import ImmutableSet 9 8 10 import Numericas num9 import numpy as num 11 10 12 11 from anuga.geospatial_data.geospatial_data import * … … 16 15 from anuga.utilities.system_tools import get_host_name 17 16 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 17 from anuga.config import netcdf_float 18 18 19 19 20 class Test_Geospatial_data(unittest.TestCase): … … 24 25 pass 25 26 26 27 27 def test_0(self): 28 28 #Basic points 29 29 from anuga.coordinate_transforms.geo_reference import Geo_reference 30 30 31 31 points = [[1.0, 2.1], [3.0, 5.3]] 32 32 G = Geospatial_data(points) 33 34 33 assert num.allclose(G.data_points, [[1.0, 2.1], [3.0, 5.3]]) 35 34 … … 38 37 rep = `G` 39 38 ref = '[[ 1. 2.1]\n [ 3. 5.3]]' 40 41 msg = 'Representation %s is not equal to %s' %(rep, ref) 39 msg = 'Representation %s is not equal to %s' % (rep, ref) 42 40 assert rep == ref, msg 43 41 44 42 #Check getter 45 43 assert num.allclose(G.get_data_points(), [[1.0, 2.1], [3.0, 5.3]]) 46 44 47 45 #Check defaults 48 46 assert G.attributes is None 49 50 47 assert G.geo_reference.zone == Geo_reference().zone 51 48 assert G.geo_reference.xllcorner == Geo_reference().xllcorner 52 49 assert G.geo_reference.yllcorner == Geo_reference().yllcorner 53 54 50 55 51 def test_1(self): 56 52 points = [[1.0, 2.1], [3.0, 5.3]] 57 53 attributes = [2, 4] 58 G = Geospatial_data(points, attributes) 54 G = Geospatial_data(points, attributes) 59 55 assert G.attributes.keys()[0] == DEFAULT_ATTRIBUTE 60 56 assert num.allclose(G.attributes.values()[0], [2, 4]) 61 62 57 63 58 def test_2(self): 64 59 from anuga.coordinate_transforms.geo_reference import Geo_reference 60 65 61 points = [[1.0, 2.1], [3.0, 5.3]] 66 62 attributes = [2, 4] … … 72 68 assert G.geo_reference.yllcorner == 200 73 69 74 75 70 def test_get_attributes_1(self): 76 71 from anuga.coordinate_transforms.geo_reference import Geo_reference 72 77 73 points = [[1.0, 2.1], [3.0, 5.3]] 78 74 attributes = [2, 4] … … 80 76 geo_reference=Geo_reference(56, 100, 200)) 81 77 82 83 78 P = G.get_data_points(absolute=False) 84 assert num.allclose(P, [[1.0, 2.1], [3.0, 5.3]]) 79 assert num.allclose(P, [[1.0, 2.1], [3.0, 5.3]]) 85 80 86 81 P = G.get_data_points(absolute=True) 87 assert num.allclose(P, [[101.0, 202.1], [103.0, 205.3]]) 82 assert num.allclose(P, [[101.0, 202.1], [103.0, 205.3]]) 88 83 89 84 V = G.get_attributes() #Simply get them … … 95 90 def test_get_attributes_2(self): 96 91 #Multiple attributes 97 98 99 92 from anuga.coordinate_transforms.geo_reference import Geo_reference 93 100 94 points = [[1.0, 2.1], [3.0, 5.3]] 101 95 attributes = {'a0': [0, 0], 'a1': [2, 4], 'a2': [79.4, -7]} … … 104 98 default_attribute_name='a1') 105 99 106 107 100 P = G.get_data_points(absolute=False) 108 assert num.allclose(P, [[1.0, 2.1], [3.0, 5.3]]) 109 101 assert num.allclose(P, [[1.0, 2.1], [3.0, 5.3]]) 102 110 103 V = G.get_attributes() #Get default attribute 111 104 assert num.allclose(V, [2, 4]) … … 125 118 pass 126 119 else: 127 raise 'Should have raised exception'120 raise Exception, 'Should have raised exception' 128 121 129 122 def test_get_data_points(self): 130 points_ab = [[12.5, 34.7],[-4.5,-60.0]]123 points_ab = [[12.5, 34.7], [-4.5, -60.0]] 131 124 x_p = -10 132 125 y_p = -40 133 126 geo_ref = Geo_reference(56, x_p, y_p) 134 127 points_rel = geo_ref.change_points_geo_ref(points_ab) 135 128 136 129 spatial = Geospatial_data(points_rel, geo_reference=geo_ref) 137 138 130 results = spatial.get_data_points(absolute=False) 139 140 131 assert num.allclose(results, points_rel) 141 132 142 133 x_p = -1770 143 134 y_p = 4.01 144 135 geo_ref = Geo_reference(56, x_p, y_p) 145 136 points_rel = geo_ref.change_points_geo_ref(points_ab) 146 results = spatial.get_data_points \ 147 ( geo_reference=geo_ref) 148 137 results = spatial.get_data_points(geo_reference=geo_ref) 138 149 139 assert num.allclose(results, points_rel) 150 140 151 152 141 def test_get_data_points_lat_long(self): 153 # lat long [-30.],[130] 154 #Zone: 52 155 #Easting: 596450.153 Northing: 6680793.777 156 # lat long [-32.],[131] 157 #Zone: 52 158 #Easting: 688927.638 Northing: 6457816.509 159 160 points_Lat_long = [[-30.,130], [-32,131]] 161 162 spatial = Geospatial_data(latitudes=[-30, -32.], 163 longitudes=[130, 131]) 164 142 # lat long [-30.], [130] 143 # Zone: 52 144 # Easting: 596450.153 Northing: 6680793.777 145 # lat long [-32.], [131] 146 # Zone: 52 147 # Easting: 688927.638 Northing: 6457816.509 148 149 points_Lat_long = [[-30., 130], [-32, 131]] 150 151 spatial = Geospatial_data(latitudes=[-30, -32.], longitudes=[130, 131]) 165 152 results = spatial.get_data_points(as_lat_long=True) 166 #print "test_get_data_points_lat_long - results", results167 #print "points_Lat_long",points_Lat_long168 153 assert num.allclose(results, points_Lat_long) 169 154 170 155 def test_get_data_points_lat_longII(self): 171 156 # x,y North,east long,lat 172 157 boundary_polygon = [[ 250000, 7630000]] 173 158 zone = 50 174 159 175 160 geo_reference = Geo_reference(zone=zone) 176 geo = Geospatial_data(boundary_polygon ,geo_reference=geo_reference)161 geo = Geospatial_data(boundary_polygon ,geo_reference=geo_reference) 177 162 seg_lat_long = geo.get_data_points(as_lat_long=True) 178 lat_result = degminsec2decimal_degrees(-21,24,54) 179 long_result = degminsec2decimal_degrees(114,35,17.89) 180 #print "seg_lat_long", seg_lat_long [0][0] 181 #print "lat_result",lat_result 163 lat_result = degminsec2decimal_degrees(-21, 24, 54) 164 long_result = degminsec2decimal_degrees(114, 35, 17.89) 165 assert num.allclose(seg_lat_long[0][0], lat_result) #lat 166 assert num.allclose(seg_lat_long[0][1], long_result) #long 167 168 def test_get_data_points_lat_longIII(self): 169 # x,y North,east long,lat 170 # for northern hemisphere 171 boundary_polygon = [[419944.8, 918642.4]] 172 zone = 47 173 174 geo_reference = Geo_reference(zone=zone) 175 geo = Geospatial_data(boundary_polygon, geo_reference=geo_reference) 176 seg_lat_long = geo.get_data_points(as_lat_long=True, 177 isSouthHemisphere=False) 178 lat_result = degminsec2decimal_degrees(8.31, 0, 0) 179 long_result = degminsec2decimal_degrees(98.273, 0, 0) 182 180 assert num.allclose(seg_lat_long[0][0], lat_result)#lat 183 181 assert num.allclose(seg_lat_long[0][1], long_result)#long 184 182 185 186 def test_get_data_points_lat_longIII(self):187 # x,y North,east long,lat188 #for northern hemisphere189 boundary_polygon = [[419944.8, 918642.4]]190 zone = 47191 192 geo_reference = Geo_reference(zone=zone)193 geo = Geospatial_data(boundary_polygon,194 geo_reference=geo_reference)195 196 seg_lat_long = geo.get_data_points(as_lat_long=True,197 isSouthHemisphere=False)198 199 lat_result = degminsec2decimal_degrees(8.31,0,0)200 long_result = degminsec2decimal_degrees(98.273,0,0)201 #print "seg_lat_long", seg_lat_long [0]202 #print "lat_result",lat_result203 assert num.allclose(seg_lat_long[0][0], lat_result)#lat204 assert num.allclose(seg_lat_long[0][1], long_result)#long205 206 207 208 183 def test_set_geo_reference(self): 209 """test_set_georeference210 211 Test that georeference can be changed without changing the 184 '''test_set_georeference 185 186 Test that georeference can be changed without changing the 212 187 absolute values. 213 """214 215 points_ab = [[12.5, 34.7],[-4.5,-60.0]]188 ''' 189 190 points_ab = [[12.5, 34.7], [-4.5, -60.0]] 216 191 x_p = -10 217 192 y_p = -40 218 193 geo_ref = Geo_reference(56, x_p, y_p) 219 194 points_rel = geo_ref.change_points_geo_ref(points_ab) 220 195 221 196 # Create without geo_ref properly set 222 G = Geospatial_data(points_rel) 197 G = Geospatial_data(points_rel) 223 198 assert not num.allclose(points_ab, G.get_data_points(absolute=True)) 224 199 225 200 # Create the way it should be 226 201 G = Geospatial_data(points_rel, geo_reference=geo_ref) 227 202 assert num.allclose(points_ab, G.get_data_points(absolute=True)) 228 203 229 204 # Change georeference and check that absolute values are unchanged. 230 205 x_p = 10 … … 232 207 new_geo_ref = Geo_reference(56, x_p, y_p) 233 208 G.set_geo_reference(new_geo_ref) 234 assert num.allclose(points_ab, G.get_data_points(absolute=True)) 235 236 237 238 209 msg = ('points_ab=%s, but\nG.get_data_points(absolute=True)=%s' 210 % (str(points_ab), str(G.get_data_points(absolute=True)))) 211 assert num.allclose(points_ab, G.get_data_points(absolute=True)), msg 212 239 213 def test_conversions_to_points_dict(self): 240 214 #test conversions to points_dict 241 242 243 215 from anuga.coordinate_transforms.geo_reference import Geo_reference 216 244 217 points = [[1.0, 2.1], [3.0, 5.3]] 245 218 attributes = {'a0': [0, 0], 'a1': [2, 4], 'a2': [79.4, -7]} … … 248 221 default_attribute_name='a1') 249 222 250 251 223 points_dict = geospatial_data2points_dictionary(G) 252 224 253 225 assert points_dict.has_key('pointlist') 254 assert points_dict.has_key('attributelist') 226 assert points_dict.has_key('attributelist') 255 227 assert points_dict.has_key('geo_reference') 256 228 … … 260 232 assert A.has_key('a0') 261 233 assert A.has_key('a1') 262 assert A.has_key('a2') 234 assert A.has_key('a2') 263 235 264 236 assert num.allclose( A['a0'], [0, 0] ) 265 assert num.allclose( A['a1'], [2, 4] ) 237 assert num.allclose( A['a1'], [2, 4] ) 266 238 assert num.allclose( A['a2'], [79.4, -7] ) 267 268 239 269 240 geo = points_dict['geo_reference'] 270 241 assert geo is G.geo_reference 271 242 272 273 243 def test_conversions_from_points_dict(self): 274 """test conversions from points_dict 275 """ 244 '''test conversions from points_dict''' 276 245 277 246 from anuga.coordinate_transforms.geo_reference import Geo_reference 278 247 279 248 points = [[1.0, 2.1], [3.0, 5.3]] 280 249 attributes = {'a0': [0, 0], 'a1': [2, 4], 'a2': [79.4, -7]} … … 284 253 points_dict['attributelist'] = attributes 285 254 points_dict['geo_reference'] = Geo_reference(56, 100, 200) 286 287 255 288 256 G = points_dictionary2geospatial_data(points_dict) 289 290 257 P = G.get_data_points(absolute=False) 291 assert num.allclose(P, [[1.0, 2.1], [3.0, 5.3]]) 292 293 #V = G.get_attribute_values() #Get default attribute 294 #assert allclose(V, [2, 4]) 258 assert num.allclose(P, [[1.0, 2.1], [3.0, 5.3]]) 295 259 296 260 V = G.get_attributes('a0') #Get by name … … 304 268 305 269 def test_add(self): 306 """ test the addition of two geospatical objects 307 no geo_reference see next test 308 """ 270 '''test the addition of two geospatical objects 271 no geo_reference see next test 272 ''' 273 309 274 points = [[1.0, 2.1], [3.0, 5.3]] 310 attributes = {'depth':[2, 4], 'elevation':[6.1, 5]} 311 attributes1 = {'depth':[2, 4], 'elevation':[2.5, 1]} 312 G1 = Geospatial_data(points, attributes) 313 G2 = Geospatial_data(points, attributes1) 314 315 # g3 = geospatial_data2points_dictionary(G1) 316 # print 'g3=', g3 317 275 attributes = {'depth': [2, 4], 'elevation': [6.1, 5]} 276 attributes1 = {'depth': [2, 4], 'elevation': [2.5, 1]} 277 G1 = Geospatial_data(points, attributes) 278 G2 = Geospatial_data(points, attributes1) 279 318 280 G = G1 + G2 319 281 … … 326 288 327 289 def test_addII(self): 328 """ test the addition of two geospatical objects 329 no geo_reference see next test 330 """ 290 '''test the addition of two geospatical objects 291 no geo_reference see next test 292 ''' 293 331 294 points = [[1.0, 2.1], [3.0, 5.3]] 332 attributes = {'depth': [2, 4]}333 G1 = Geospatial_data(points, attributes) 334 295 attributes = {'depth': [2, 4]} 296 G1 = Geospatial_data(points, attributes) 297 335 298 points = [[5.0, 2.1], [3.0, 50.3]] 336 attributes = {'depth': [200, 400]}299 attributes = {'depth': [200, 400]} 337 300 G2 = Geospatial_data(points, attributes) 338 339 # g3 = geospatial_data2points_dictionary(G1) 340 # print 'g3=', g3 341 301 342 302 G = G1 + G2 343 303 344 assert G.attributes.has_key('depth') 304 assert G.attributes.has_key('depth') 345 305 assert G.attributes.keys(), ['depth'] 346 306 assert num.allclose(G.attributes['depth'], [2, 4, 200, 400]) 347 307 assert num.allclose(G.get_data_points(), [[1.0, 2.1], [3.0, 5.3], 348 308 [5.0, 2.1], [3.0, 50.3]]) 309 349 310 def test_add_with_geo (self): 350 """ 351 Difference in Geo_reference resolved 352 """ 311 '''Difference in Geo_reference resolved''' 312 353 313 points1 = [[1.0, 2.1], [3.0, 5.3]] 354 314 points2 = [[5.0, 6.1], [6.0, 3.3]] … … 362 322 projection='UTM', 363 323 units='m') 364 324 365 325 G1 = Geospatial_data(points1, attributes1, geo_ref1) 366 326 G2 = Geospatial_data(points2, attributes2, geo_ref2) … … 371 331 372 332 P2 = G2.get_data_points(absolute=True) 373 assert num.allclose(P2, [[5.1, 9.1], [6.1, 6.3]]) 374 333 assert num.allclose(P2, [[5.1, 9.1], [6.1, 6.3]]) 334 375 335 G = G1 + G2 376 336 … … 381 341 P = G.get_data_points(absolute=True) 382 342 383 #P_relative = G.get_data_points(absolute=False)384 #385 #assert allclose(P_relative, P - [0.1, 2.0])386 387 343 assert num.allclose(P, num.concatenate( (P1,P2) )) 344 msg = 'P=%s' % str(P) 388 345 assert num.allclose(P, [[2.0, 4.1], [4.0, 7.3], 389 [5.1, 9.1], [6.1, 6.3]]) 390 391 392 393 346 [5.1, 9.1], [6.1, 6.3]]), msg 394 347 395 348 def test_add_with_geo_absolute (self): 396 """ 397 Difference in Geo_reference resolved 398 """ 349 '''Difference in Geo_reference resolved''' 350 399 351 points1 = num.array([[2.0, 4.1], [4.0, 7.3]]) 400 points2 = num.array([[5.1, 9.1], [6.1, 6.3]]) 352 points2 = num.array([[5.1, 9.1], [6.1, 6.3]]) 401 353 attributes1 = [2, 4] 402 354 attributes2 = [5, 76] … … 404 356 geo_ref2 = Geo_reference(55, 2.0, 3.0) 405 357 406 407 408 G1 = Geospatial_data(points1 - [geo_ref1.get_xllcorner(), geo_ref1.get_yllcorner()], 358 G1 = Geospatial_data(points1 - [geo_ref1.get_xllcorner(), 359 geo_ref1.get_yllcorner()], 409 360 attributes1, geo_ref1) 410 411 G2 = Geospatial_data(points2 - [geo_ref2.get_xllcorner(), geo_ref2.get_yllcorner()], 361 362 G2 = Geospatial_data(points2 - [geo_ref2.get_xllcorner(), 363 geo_ref2.get_yllcorner()], 412 364 attributes2, geo_ref2) 413 365 … … 417 369 418 370 P1 = G1.get_data_points(absolute=False) 419 assert num.allclose(P1, points1 - [geo_ref1.get_xllcorner(), geo_ref1.get_yllcorner()]) 371 msg = ('P1=%s, but\npoints1 - <...>=%s' 372 % (str(P1), 373 str(points1 - [geo_ref1.get_xllcorner(), 374 geo_ref1.get_yllcorner()]))) 375 assert num.allclose(P1, points1 - [geo_ref1.get_xllcorner(), 376 geo_ref1.get_yllcorner()]), msg 420 377 421 378 P2 = G2.get_data_points(absolute=True) … … 423 380 424 381 P2 = G2.get_data_points(absolute=False) 425 assert num.allclose(P2, points2 - [geo_ref2.get_xllcorner(), geo_ref2.get_yllcorner()]) 426 382 assert num.allclose(P2, points2 - [geo_ref2.get_xllcorner(), 383 geo_ref2.get_yllcorner()]) 384 427 385 G = G1 + G2 428 429 #assert allclose(G.get_geo_reference().get_xllcorner(), 1.0)430 #assert allclose(G.get_geo_reference().get_yllcorner(), 2.0)431 432 386 P = G.get_data_points(absolute=True) 433 387 434 #P_relative = G.get_data_points(absolute=False) 435 # 436 #assert allclose(P_relative, [[1.0, 2.1], [3.0, 5.3], [4.1, 7.1], [5.1, 4.3]]) 437 438 assert num.allclose(P, num.concatenate( (points1,points2) )) 439 388 assert num.allclose(P, num.concatenate((points1, points2))) 440 389 441 390 def test_add_with_None(self): 442 """ test that None can be added to a geospatical objects 443 """ 444 391 '''test that None can be added to a geospatical objects''' 392 445 393 points1 = num.array([[2.0, 4.1], [4.0, 7.3]]) 446 points2 = num.array([[5.1, 9.1], [6.1, 6.3]]) 394 points2 = num.array([[5.1, 9.1], [6.1, 6.3]]) 447 395 448 396 geo_ref1= Geo_reference(55, 1.0, 2.0) … … 453 401 projection='UTM', 454 402 units='m') 455 456 457 attributes1 = {'depth':[2, 4.7], 'elevation':[6.1, 5]} 458 attributes2 = {'depth':[-2.3, 4], 'elevation':[2.5, 1]} 459 403 404 attributes1 = {'depth': [2, 4.7], 'elevation': [6.1, 5]} 405 attributes2 = {'depth': [-2.3, 4], 'elevation': [2.5, 1]} 460 406 461 407 G1 = Geospatial_data(points1, attributes1, geo_ref1) … … 465 411 assert G1.attributes.has_key('elevation') 466 412 assert num.allclose(G1.attributes['depth'], [2, 4.7]) 467 assert num.allclose(G1.attributes['elevation'], [6.1, 5]) 468 413 assert num.allclose(G1.attributes['elevation'], [6.1, 5]) 414 469 415 G2 = Geospatial_data(points2, attributes2, geo_ref2) 470 416 assert num.allclose(G2.get_geo_reference().get_xllcorner(), 0.1) … … 473 419 assert G2.attributes.has_key('elevation') 474 420 assert num.allclose(G2.attributes['depth'], [-2.3, 4]) 475 assert num.allclose(G2.attributes['elevation'], [2.5, 1]) 421 assert num.allclose(G2.attributes['elevation'], [2.5, 1]) 476 422 477 423 #Check that absolute values are as expected … … 480 426 481 427 P2 = G2.get_data_points(absolute=True) 482 assert num.allclose(P2, [[5.2, 12.1], [6.2, 9.3]]) 428 assert num.allclose(P2, [[5.2, 12.1], [6.2, 9.3]]) 483 429 484 430 # Normal add 485 431 G = G1 + None 486 487 432 assert G.attributes.has_key('depth') 488 433 assert G.attributes.has_key('elevation') 489 434 assert num.allclose(G.attributes['depth'], [2, 4.7]) 490 assert num.allclose(G.attributes['elevation'], [6.1, 5]) 435 assert num.allclose(G.attributes['elevation'], [6.1, 5]) 491 436 492 437 # Points are now absolute. 493 438 assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0) 494 439 assert num.allclose(G.get_geo_reference().get_yllcorner(), 0.0) 495 P = G.get_data_points(absolute=True) 496 assert num.allclose(P, [[3.0, 6.1], [5.0, 9.3]])497 440 P = G.get_data_points(absolute=True) 441 msg = 'P=%s' % str(P) 442 assert num.allclose(P, [[3.0, 6.1], [5.0, 9.3]]), msg 498 443 499 444 G = G2 + None … … 501 446 assert G.attributes.has_key('elevation') 502 447 assert num.allclose(G.attributes['depth'], [-2.3, 4]) 503 assert num.allclose(G.attributes['elevation'], [2.5, 1]) 504 448 assert num.allclose(G.attributes['elevation'], [2.5, 1]) 505 449 assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0) 506 450 assert num.allclose(G.get_geo_reference().get_yllcorner(), 0.0) 507 P = G.get_data_points(absolute=True) 451 452 P = G.get_data_points(absolute=True) 508 453 assert num.allclose(P, [[5.2, 12.1], [6.2, 9.3]]) 509 510 511 454 512 455 # Reverse add 513 456 G = None + G1 514 515 457 assert G.attributes.has_key('depth') 516 458 assert G.attributes.has_key('elevation') 517 459 assert num.allclose(G.attributes['depth'], [2, 4.7]) 518 assert num.allclose(G.attributes['elevation'], [6.1, 5]) 460 assert num.allclose(G.attributes['elevation'], [6.1, 5]) 519 461 520 462 # Points are now absolute. 521 463 assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0) 522 464 assert num.allclose(G.get_geo_reference().get_yllcorner(), 0.0) 523 P = G.get_data_points(absolute=True) 524 assert num.allclose(P, [[3.0, 6.1], [5.0, 9.3]])525 465 466 P = G.get_data_points(absolute=True) 467 assert num.allclose(P, [[3.0, 6.1], [5.0, 9.3]]) 526 468 527 469 G = None + G2 … … 529 471 assert G.attributes.has_key('elevation') 530 472 assert num.allclose(G.attributes['depth'], [-2.3, 4]) 531 assert num.allclose(G.attributes['elevation'], [2.5, 1]) 473 assert num.allclose(G.attributes['elevation'], [2.5, 1]) 532 474 533 475 assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0) 534 476 assert num.allclose(G.get_geo_reference().get_yllcorner(), 0.0) 535 P = G.get_data_points(absolute=True) 477 478 P = G.get_data_points(absolute=True) 536 479 assert num.allclose(P, [[5.2, 12.1], [6.2, 9.3]]) 537 480 538 539 540 541 542 543 481 def test_clip0(self): 544 """test_clip0(self):545 482 '''test_clip0(self): 483 546 484 Test that point sets can be clipped by a polygon 547 """548 485 ''' 486 549 487 from anuga.coordinate_transforms.geo_reference import Geo_reference 550 488 551 489 points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3], 552 490 [0, 0], [2.4, 3.3]] 553 491 G = Geospatial_data(points) 554 492 555 # First try the unit square 556 U = [[0,0], [1,0], [1,1], [0,1]] 557 assert num.allclose(G.clip(U).get_data_points(), [[0.2, 0.5], [0.4, 0.3], [0, 0]]) 493 # First try the unit square 494 U = [[0,0], [1,0], [1,1], [0,1]] 495 assert num.allclose(G.clip(U).get_data_points(), 496 [[0.2, 0.5], [0.4, 0.3], [0, 0]]) 558 497 559 498 # Then a more complex polygon 560 499 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 561 points = [ [0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 500 points = [[0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], 501 [0.5, 1.5], [0.5, -0.5]] 562 502 G = Geospatial_data(points) 563 503 564 504 assert num.allclose(G.clip(polygon).get_data_points(), 565 [[0.5, 0.5], [1, -0.5], [1.5, 0]])505 [[0.5, 0.5], [1, -0.5], [1.5, 0]]) 566 506 567 507 def test_clip0_with_attributes(self): 568 """test_clip0_with_attributes(self):569 508 '''test_clip0_with_attributes(self): 509 570 510 Test that point sets with attributes can be clipped by a polygon 571 """572 511 ''' 512 573 513 from anuga.coordinate_transforms.geo_reference import Geo_reference 574 514 575 515 points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3], 576 516 [0, 0], [2.4, 3.3]] … … 579 519 att_dict = {'att1': attributes, 580 520 'att2': num.array(attributes)+1} 581 521 582 522 G = Geospatial_data(points, att_dict) 583 523 584 # First try the unit square 585 U = [[0,0], [1,0], [1,1], [0,1]] 586 assert num.allclose(G.clip(U).get_data_points(), [[0.2, 0.5], [0.4, 0.3], [0, 0]]) 524 # First try the unit square 525 U = [[0,0], [1,0], [1,1], [0,1]] 526 assert num.allclose(G.clip(U).get_data_points(), 527 [[0.2, 0.5], [0.4, 0.3], [0, 0]]) 587 528 assert num.allclose(G.clip(U).get_attributes('att1'), [-4, 76, 0.1]) 588 assert num.allclose(G.clip(U).get_attributes('att2'), [-3, 77, 1.1]) 529 assert num.allclose(G.clip(U).get_attributes('att2'), [-3, 77, 1.1]) 589 530 590 531 # Then a more complex polygon 591 532 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 592 points = [ [0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 533 points = [[0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], 534 [0.5, 1.5], [0.5, -0.5]] 593 535 594 536 # This time just one attribute 595 537 attributes = [2, -4, 5, 76, -2, 0.1] 596 538 G = Geospatial_data(points, attributes) 597 598 539 assert num.allclose(G.clip(polygon).get_data_points(), 599 [[0.5, 0.5], [1, -0.5], [1.5, 0]])540 [[0.5, 0.5], [1, -0.5], [1.5, 0]]) 600 541 assert num.allclose(G.clip(polygon).get_attributes(), [-4, 5, 76]) 601 602 542 603 543 def test_clip1(self): 604 """test_clip1(self):605 544 '''test_clip1(self): 545 606 546 Test that point sets can be clipped by a polygon given as 607 547 another Geospatial dataset 608 """609 548 ''' 549 610 550 from anuga.coordinate_transforms.geo_reference import Geo_reference 611 551 612 552 points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3], 613 553 [0, 0], [2.4, 3.3]] … … 616 556 'att2': num.array(attributes)+1} 617 557 G = Geospatial_data(points, att_dict) 618 619 # First try the unit square 620 U = Geospatial_data([[0,0], [1,0], [1,1], [0,1]]) 558 559 # First try the unit square 560 U = Geospatial_data([[0,0], [1,0], [1,1], [0,1]]) 621 561 assert num.allclose(G.clip(U).get_data_points(), 622 [[0.2, 0.5], [0.4, 0.3], [0, 0]]) 623 562 [[0.2, 0.5], [0.4, 0.3], [0, 0]]) 624 563 assert num.allclose(G.clip(U).get_attributes('att1'), [-4, 76, 0.1]) 625 assert num.allclose(G.clip(U).get_attributes('att2'), [-3, 77, 1.1]) 626 564 assert num.allclose(G.clip(U).get_attributes('att2'), [-3, 77, 1.1]) 565 627 566 # Then a more complex polygon 628 points = [ [0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 629 attributes = [2, -4, 5, 76, -2, 0.1] 567 points = [[0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], 568 [0.5, 1.5], [0.5, -0.5]] 569 attributes = [2, -4, 5, 76, -2, 0.1] 630 570 G = Geospatial_data(points, attributes) 631 polygon = Geospatial_data([[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]])632 571 polygon = Geospatial_data([[0,0], [1,0], [0.5,-1], [2, -1], 572 [2,1], [0,1]]) 633 573 634 574 assert num.allclose(G.clip(polygon).get_data_points(), 635 575 [[0.5, 0.5], [1, -0.5], [1.5, 0]]) 636 576 assert num.allclose(G.clip(polygon).get_attributes(), [-4, 5, 76]) 637 638 577 639 578 def test_clip0_outside(self): 640 """test_clip0_outside(self):641 579 '''test_clip0_outside(self): 580 642 581 Test that point sets can be clipped outside of a polygon 643 """644 582 ''' 583 645 584 from anuga.coordinate_transforms.geo_reference import Geo_reference 646 585 647 586 points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3], 648 587 [0, 0], [2.4, 3.3]] 649 attributes = [2, -4, 5, 76, -2, 0.1, 3] 588 attributes = [2, -4, 5, 76, -2, 0.1, 3] 650 589 G = Geospatial_data(points, attributes) 651 590 652 # First try the unit square 591 # First try the unit square 653 592 U = [[0,0], [1,0], [1,1], [0,1]] 654 593 assert num.allclose(G.clip_outside(U).get_data_points(), 655 594 [[-1, 4], [1.0, 2.1], [3.0, 5.3], [2.4, 3.3]]) 656 #print G.clip_outside(U).get_attributes() 657 assert num.allclose(G.clip_outside(U).get_attributes(), [2, 5, -2, 3]) 658 595 assert num.allclose(G.clip_outside(U).get_attributes(), [2, 5, -2, 3]) 659 596 660 597 # Then a more complex polygon 661 598 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 662 points = [ [0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 663 attributes = [2, -4, 5, 76, -2, 0.1] 599 points = [[0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], 600 [0.5, 1.5], [0.5, -0.5]] 601 attributes = [2, -4, 5, 76, -2, 0.1] 664 602 G = Geospatial_data(points, attributes) 665 666 603 assert num.allclose(G.clip_outside(polygon).get_data_points(), 667 604 [[0.5, 1.4], [0.5, 1.5], [0.5, -0.5]]) 668 assert num.allclose(G.clip_outside(polygon).get_attributes(), [2, -2, 0.1])669 605 assert num.allclose(G.clip_outside(polygon).get_attributes(), 606 [2, -2, 0.1]) 670 607 671 608 def test_clip1_outside(self): 672 """test_clip1_outside(self):673 609 '''test_clip1_outside(self): 610 674 611 Test that point sets can be clipped outside of a polygon given as 675 612 another Geospatial dataset 676 """677 613 ''' 614 678 615 from anuga.coordinate_transforms.geo_reference import Geo_reference 679 616 680 617 points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3], 681 618 [0, 0], [2.4, 3.3]] 682 attributes = [2, -4, 5, 76, -2, 0.1, 3] 683 G = Geospatial_data(points, attributes) 684 685 # First try the unit square 686 U = Geospatial_data([[0,0], [1,0], [1,1], [0,1]]) 619 attributes = [2, -4, 5, 76, -2, 0.1, 3] 620 G = Geospatial_data(points, attributes) 621 622 # First try the unit square 623 U = Geospatial_data([[0,0], [1,0], [1,1], [0,1]]) 687 624 assert num.allclose(G.clip_outside(U).get_data_points(), 688 625 [[-1, 4], [1.0, 2.1], [3.0, 5.3], [2.4, 3.3]]) 689 assert num.allclose(G.clip(U).get_attributes(), [-4, 76, 0.1]) 626 assert num.allclose(G.clip(U).get_attributes(), [-4, 76, 0.1]) 690 627 691 628 # Then a more complex polygon 692 points = [ [0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 693 attributes = [2, -4, 5, 76, -2, 0.1] 629 points = [[0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], 630 [0.5, 1.5], [0.5, -0.5]] 631 attributes = [2, -4, 5, 76, -2, 0.1] 694 632 G = Geospatial_data(points, attributes) 695 696 polygon = Geospatial_data([[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]]) 697 698 633 polygon = Geospatial_data([[0, 0], [1, 0], [0.5, -1], [2, -1], 634 [2, 1], [0, 1]]) 699 635 assert num.allclose(G.clip_outside(polygon).get_data_points(), 700 636 [[0.5, 1.4], [0.5, 1.5], [0.5, -0.5]]) 701 assert num.allclose(G.clip_outside(polygon).get_attributes(), [2, -2, 0.1]) 702 703 637 assert num.allclose(G.clip_outside(polygon).get_attributes(), 638 [2, -2, 0.1]) 704 639 705 640 def test_clip1_inside_outside(self): 706 """test_clip1_inside_outside(self):707 641 '''test_clip1_inside_outside(self): 642 708 643 Test that point sets can be clipped outside of a polygon given as 709 644 another Geospatial dataset 710 """711 645 ''' 646 712 647 from anuga.coordinate_transforms.geo_reference import Geo_reference 713 648 714 649 points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3], 715 650 [0, 0], [2.4, 3.3]] 716 attributes = [2, -4, 5, 76, -2, 0.1, 3] 651 attributes = [2, -4, 5, 76, -2, 0.1, 3] 717 652 G = Geospatial_data(points, attributes) 718 653 719 # First try the unit square 720 U = Geospatial_data([[0,0], [1,0], [1,1], [0,1]]) 654 # First try the unit square 655 U = Geospatial_data([[0,0], [1,0], [1,1], [0,1]]) 721 656 G1 = G.clip(U) 722 assert num.allclose(G1.get_data_points(),[[0.2, 0.5], [0.4, 0.3], [0, 0]]) 657 assert num.allclose(G1.get_data_points(), 658 [[0.2, 0.5], [0.4, 0.3], [0, 0]]) 723 659 assert num.allclose(G.clip(U).get_attributes(), [-4, 76, 0.1]) 724 725 660 G2 = G.clip_outside(U) 726 661 assert num.allclose(G2.get_data_points(),[[-1, 4], [1.0, 2.1], 727 662 [3.0, 5.3], [2.4, 3.3]]) 728 assert num.allclose(G.clip_outside(U).get_attributes(), [2, 5, -2, 3]) 729 730 663 assert num.allclose(G.clip_outside(U).get_attributes(), [2, 5, -2, 3]) 664 731 665 # New ordering 732 new_points = [[0.2, 0.5], [0.4, 0.3], [0, 0]] +\ 733 [[-1, 4], [1.0, 2.1], [3.0, 5.3], [2.4, 3.3]] 734 735 new_attributes = [-4, 76, 0.1, 2, 5, -2, 3] 736 666 new_points = [[0.2, 0.5], [0.4, 0.3], [0, 0], [-1, 4], 667 [1.0, 2.1], [3.0, 5.3], [2.4, 3.3]] 668 new_attributes = [-4, 76, 0.1, 2, 5, -2, 3] 669 737 670 assert num.allclose((G1+G2).get_data_points(), new_points) 738 671 assert num.allclose((G1+G2).get_attributes(), new_attributes) … … 742 675 G.export_points_file(FN) 743 676 744 745 677 # Read it back in 746 678 G3 = Geospatial_data(FN) 747 679 748 749 680 # Check result 750 assert num.allclose(G3.get_data_points(), new_points) 751 assert num.allclose(G3.get_attributes(), new_attributes) 752 681 assert num.allclose(G3.get_data_points(), new_points) 682 assert num.allclose(G3.get_attributes(), new_attributes) 683 753 684 os.remove(FN) 754 685 755 756 686 def test_load_csv(self): 757 758 import os 759 import tempfile 760 761 fileName = tempfile.mktemp(".csv") 762 file = open(fileName,"w") 763 file.write("x,y,elevation speed \n\ 687 fileName = tempfile.mktemp('.csv') 688 file = open(fileName,'w') 689 file.write('x,y,elevation speed \n\ 764 690 1.0 0.0 10.0 0.0\n\ 765 691 0.0 1.0 0.0 10.0\n\ 766 1.0 0.0 10.4 40.0\n ")692 1.0 0.0 10.4 40.0\n') 767 693 file.close() 768 #print fileName 694 769 695 results = Geospatial_data(fileName) 770 696 os.remove(fileName) 771 # print 'data', results.get_data_points() 772 assert num.allclose(results.get_data_points(), [[1.0, 0.0],[0.0, 1.0], 773 [1.0, 0.0]]) 697 assert num.allclose(results.get_data_points(), 698 [[1.0, 0.0],[0.0, 1.0], [1.0, 0.0]]) 774 699 assert num.allclose(results.get_attributes(attribute_name='elevation'), 775 700 [10.0, 0.0, 10.4]) … … 777 702 [0.0, 10.0, 40.0]) 778 703 779 780 ###################### .CSV ############################## 704 ################################################################################ 705 # Test CSV files 706 ################################################################################ 781 707 782 708 def test_load_csv_lat_long_bad_blocking(self): 783 """ 784 test_load_csv_lat_long_bad_blocking(self): 709 '''test_load_csv_lat_long_bad_blocking(self): 785 710 Different zones in Geo references 786 """ 787 fileName = tempfile.mktemp(".csv") 788 file = open(fileName,"w") 789 file.write("Lati,LONG,z \n\ 711 ''' 712 713 fileName = tempfile.mktemp('.csv') 714 file = open(fileName, 'w') 715 file.write('Lati,LONG,z \n\ 790 716 -25.0,180.0,452.688000\n\ 791 -34,150.0,459.126000\n ")717 -34,150.0,459.126000\n') 792 718 file.close() 793 719 794 720 results = Geospatial_data(fileName, max_read_lines=1, 795 721 load_file_now=False) 796 797 #for i in results: 798 # pass 722 799 723 try: 800 724 for i in results: … … 804 728 else: 805 729 msg = 'Different zones in Geo references not caught.' 806 raise msg807 808 os.remove(fileName) 809 730 raise Exception, msg 731 732 os.remove(fileName) 733 810 734 def test_load_csv(self): 811 812 fileName = tempfile.mktemp(".txt") 813 file = open(fileName,"w") 814 file.write(" x,y, elevation , speed \n\ 815 1.0, 0.0, 10.0, 0.0\n\ 816 0.0, 1.0, 0.0, 10.0\n\ 817 1.0, 0.0 ,10.4, 40.0\n") 735 fileName = tempfile.mktemp('.txt') 736 file = open(fileName, 'w') 737 file.write(' x,y, elevation , speed \n\ 738 1.0, 0.0, 10.0, 0.0\n\ 739 0.0, 1.0, 0.0, 10.0\n\ 740 1.0, 0.0 ,10.4, 40.0\n') 818 741 file.close() 819 742 820 743 results = Geospatial_data(fileName, max_read_lines=2) 821 744 822 823 assert num.allclose(results.get_data_points(), [[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]]) 824 assert num.allclose(results.get_attributes(attribute_name='elevation'), [10.0, 0.0, 10.4]) 825 assert num.allclose(results.get_attributes(attribute_name='speed'), [0.0, 10.0, 40.0]) 745 assert num.allclose(results.get_data_points(), 746 [[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]]) 747 assert num.allclose(results.get_attributes(attribute_name='elevation'), 748 [10.0, 0.0, 10.4]) 749 assert num.allclose(results.get_attributes(attribute_name='speed'), 750 [0.0, 10.0, 40.0]) 826 751 827 752 # Blocking … … 829 754 for i in results: 830 755 geo_list.append(i) 831 756 832 757 assert num.allclose(geo_list[0].get_data_points(), 833 758 [[1.0, 0.0],[0.0, 1.0]]) 834 835 759 assert num.allclose(geo_list[0].get_attributes(attribute_name='elevation'), 836 760 [10.0, 0.0]) 837 761 assert num.allclose(geo_list[1].get_data_points(), 838 [[1.0, 0.0]]) 762 [[1.0, 0.0]]) 839 763 assert num.allclose(geo_list[1].get_attributes(attribute_name='elevation'), 840 764 [10.4]) 841 842 os.remove(fileName) 843 765 766 os.remove(fileName) 767 844 768 def test_load_csv_bad(self): 845 """test_load_csv_bad(self):769 '''test_load_csv_bad(self): 846 770 header column, body column missmatch 847 771 (Format error) 848 """ 849 import os 850 851 fileName = tempfile.mktemp(".txt") 852 file = open(fileName,"w") 853 file.write(" elevation , speed \n\ 854 1.0, 0.0, 10.0, 0.0\n\ 855 0.0, 1.0, 0.0, 10.0\n\ 856 1.0, 0.0 ,10.4, 40.0\n") 772 ''' 773 774 fileName = tempfile.mktemp('.txt') 775 file = open(fileName, 'w') 776 file.write(' elevation , speed \n\ 777 1.0, 0.0, 10.0, 0.0\n\ 778 0.0, 1.0, 0.0, 10.0\n\ 779 1.0, 0.0 ,10.4, 40.0\n') 857 780 file.close() 858 781 … … 862 785 # Blocking 863 786 geo_list = [] 864 #for i in results:865 # geo_list.append(i)866 787 try: 867 788 for i in results: … … 870 791 pass 871 792 else: 872 msg = ' bad file did not raise error!'873 raise msg793 msg = 'Bad file did not raise error!' 794 raise Exception, msg 874 795 os.remove(fileName) 875 796 876 797 def test_load_csv_badII(self): 877 """test_load_csv_bad(self):798 '''test_load_csv_bad(self): 878 799 header column, body column missmatch 879 800 (Format error) 880 """ 881 import os 882 883 fileName = tempfile.mktemp(".txt") 884 file = open(fileName,"w") 885 file.write(" x,y,elevation , speed \n\ 801 ''' 802 803 fileName = tempfile.mktemp('.txt') 804 file = open(fileName, 'w') 805 file.write(' x,y,elevation , speed \n\ 886 806 1.0, 0.0, 10.0, 0.0\n\ 887 807 0.0, 1.0, 0.0, 10\n\ 888 1.0, 0.0 ,10.4 yeah\n ")808 1.0, 0.0 ,10.4 yeah\n') 889 809 file.close() 890 810 … … 894 814 # Blocking 895 815 geo_list = [] 896 #for i in results:897 # geo_list.append(i)898 816 try: 899 817 for i in results: … … 902 820 pass 903 821 else: 904 msg = ' bad file did not raise error!'905 raise msg822 msg = 'Bad file did not raise error!' 823 raise Exception, msg 906 824 os.remove(fileName) 907 825 908 826 def test_load_csv_badIII(self): 909 """test_load_csv_bad(self):827 '''test_load_csv_bad(self): 910 828 space delimited 911 """ 912 import os 913 914 fileName = tempfile.mktemp(".txt") 915 file = open(fileName,"w") 916 file.write(" x y elevation speed \n\ 829 ''' 830 831 fileName = tempfile.mktemp('.txt') 832 file = open(fileName, 'w') 833 file.write(' x y elevation speed \n\ 917 834 1. 0.0 10.0 0.0\n\ 918 835 0.0 1.0 0.0 10.0\n\ 919 1.0 0.0 10.4 40.0\n ")836 1.0 0.0 10.4 40.0\n') 920 837 file.close() 921 838 … … 926 843 pass 927 844 else: 928 msg = ' bad file did not raise error!'929 raise msg930 os.remove(fileName) 931 845 msg = 'Bad file did not raise error!' 846 raise Exception, msg 847 os.remove(fileName) 848 932 849 def test_load_csv_badIV(self): 933 """test_load_csv_bad(self):850 ''' test_load_csv_bad(self): 934 851 header column, body column missmatch 935 852 (Format error) 936 """ 937 import os 938 939 fileName = tempfile.mktemp(".txt") 940 file = open(fileName,"w") 941 file.write(" x,y,elevation , speed \n\ 853 ''' 854 855 fileName = tempfile.mktemp('.txt') 856 file = open(fileName, 'w') 857 file.write(' x,y,elevation , speed \n\ 942 858 1.0, 0.0, 10.0, wow\n\ 943 859 0.0, 1.0, 0.0, ha\n\ 944 1.0, 0.0 ,10.4, yeah\n ")860 1.0, 0.0 ,10.4, yeah\n') 945 861 file.close() 946 862 … … 950 866 # Blocking 951 867 geo_list = [] 952 #for i in results:953 # geo_list.append(i)954 868 try: 955 869 for i in results: … … 958 872 pass 959 873 else: 960 msg = ' bad file did not raise error!'961 raise msg874 msg = 'Bad file did not raise error!' 875 raise Exception, msg 962 876 os.remove(fileName) 963 877 964 878 def test_load_pts_blocking(self): 965 879 #This is pts! 966 967 import os 968 969 fileName = tempfile.mktemp(".txt") 970 file = open(fileName,"w") 971 file.write(" x,y, elevation , speed \n\ 972 1.0, 0.0, 10.0, 0.0\n\ 973 0.0, 1.0, 0.0, 10.0\n\ 974 1.0, 0.0 ,10.4, 40.0\n") 880 fileName = tempfile.mktemp('.txt') 881 file = open(fileName, 'w') 882 file.write(' x,y, elevation , speed \n\ 883 1.0, 0.0, 10.0, 0.0\n\ 884 0.0, 1.0, 0.0, 10.0\n\ 885 1.0, 0.0 ,10.4, 40.0\n') 975 886 file.close() 976 887 977 pts_file = tempfile.mktemp( ".pts")978 888 pts_file = tempfile.mktemp('.pts') 889 979 890 convert = Geospatial_data(fileName) 980 891 convert.export_points_file(pts_file) 981 892 results = Geospatial_data(pts_file, max_read_lines=2) 982 893 983 assert num.allclose(results.get_data_points(), [[1.0, 0.0],[0.0, 1.0],984 894 assert num.allclose(results.get_data_points(), 895 [[1.0, 0.0],[0.0, 1.0], [1.0, 0.0]]) 985 896 assert num.allclose(results.get_attributes(attribute_name='elevation'), 986 897 [10.0, 0.0, 10.4]) … … 991 902 geo_list = [] 992 903 for i in results: 993 geo_list.append(i) 904 geo_list.append(i) 994 905 assert num.allclose(geo_list[0].get_data_points(), 995 906 [[1.0, 0.0],[0.0, 1.0]]) … … 997 908 [10.0, 0.0]) 998 909 assert num.allclose(geo_list[1].get_data_points(), 999 [[1.0, 0.0]]) 910 [[1.0, 0.0]]) 1000 911 assert num.allclose(geo_list[1].get_attributes(attribute_name='elevation'), 1001 912 [10.4]) 1002 1003 os.remove(fileName) 1004 os.remove(pts_file) 913 914 os.remove(fileName) 915 os.remove(pts_file) 1005 916 1006 917 def verbose_test_load_pts_blocking(self): 1007 1008 import os 1009 1010 fileName = tempfile.mktemp(".txt") 1011 file = open(fileName,"w") 1012 file.write(" x,y, elevation , speed \n\ 1013 1.0, 0.0, 10.0, 0.0\n\ 1014 0.0, 1.0, 0.0, 10.0\n\ 1015 1.0, 0.0, 10.0, 0.0\n\ 1016 0.0, 1.0, 0.0, 10.0\n\ 1017 1.0, 0.0, 10.0, 0.0\n\ 1018 0.0, 1.0, 0.0, 10.0\n\ 1019 1.0, 0.0, 10.0, 0.0\n\ 1020 0.0, 1.0, 0.0, 10.0\n\ 1021 1.0, 0.0, 10.0, 0.0\n\ 1022 0.0, 1.0, 0.0, 10.0\n\ 1023 1.0, 0.0, 10.0, 0.0\n\ 1024 0.0, 1.0, 0.0, 10.0\n\ 1025 1.0, 0.0, 10.0, 0.0\n\ 1026 0.0, 1.0, 0.0, 10.0\n\ 1027 1.0, 0.0, 10.0, 0.0\n\ 1028 0.0, 1.0, 0.0, 10.0\n\ 1029 1.0, 0.0, 10.0, 0.0\n\ 1030 0.0, 1.0, 0.0, 10.0\n\ 1031 1.0, 0.0, 10.0, 0.0\n\ 1032 0.0, 1.0, 0.0, 10.0\n\ 1033 1.0, 0.0, 10.0, 0.0\n\ 1034 0.0, 1.0, 0.0, 10.0\n\ 1035 1.0, 0.0, 10.0, 0.0\n\ 1036 0.0, 1.0, 0.0, 10.0\n\ 1037 1.0, 0.0, 10.0, 0.0\n\ 1038 0.0, 1.0, 0.0, 10.0\n\ 1039 1.0, 0.0, 10.0, 0.0\n\ 1040 0.0, 1.0, 0.0, 10.0\n\ 1041 1.0, 0.0, 10.0, 0.0\n\ 1042 0.0, 1.0, 0.0, 10.0\n\ 1043 1.0, 0.0, 10.0, 0.0\n\ 1044 0.0, 1.0, 0.0, 10.0\n\ 1045 1.0, 0.0, 10.0, 0.0\n\ 1046 0.0, 1.0, 0.0, 10.0\n\ 1047 1.0, 0.0, 10.0, 0.0\n\ 1048 0.0, 1.0, 0.0, 10.0\n\ 1049 1.0, 0.0, 10.0, 0.0\n\ 1050 0.0, 1.0, 0.0, 10.0\n\ 1051 1.0, 0.0, 10.0, 0.0\n\ 1052 0.0, 1.0, 0.0, 10.0\n\ 1053 1.0, 0.0, 10.0, 0.0\n\ 1054 0.0, 1.0, 0.0, 10.0\n\ 1055 1.0, 0.0, 10.0, 0.0\n\ 1056 0.0, 1.0, 0.0, 10.0\n\ 1057 1.0, 0.0, 10.0, 0.0\n\ 1058 0.0, 1.0, 0.0, 10.0\n\ 1059 1.0, 0.0 ,10.4, 40.0\n") 918 fileName = tempfile.mktemp('.txt') 919 file = open(fileName, 'w') 920 file.write(' x,y, elevation , speed \n\ 921 1.0, 0.0, 10.0, 0.0\n\ 922 0.0, 1.0, 0.0, 10.0\n\ 923 1.0, 0.0, 10.0, 0.0\n\ 924 0.0, 1.0, 0.0, 10.0\n\ 925 1.0, 0.0, 10.0, 0.0\n\ 926 0.0, 1.0, 0.0, 10.0\n\ 927 1.0, 0.0, 10.0, 0.0\n\ 928 0.0, 1.0, 0.0, 10.0\n\ 929 1.0, 0.0, 10.0, 0.0\n\ 930 0.0, 1.0, 0.0, 10.0\n\ 931 1.0, 0.0, 10.0, 0.0\n\ 932 0.0, 1.0, 0.0, 10.0\n\ 933 1.0, 0.0, 10.0, 0.0\n\ 934 0.0, 1.0, 0.0, 10.0\n\ 935 1.0, 0.0, 10.0, 0.0\n\ 936 0.0, 1.0, 0.0, 10.0\n\ 937 1.0, 0.0, 10.0, 0.0\n\ 938 0.0, 1.0, 0.0, 10.0\n\ 939 1.0, 0.0, 10.0, 0.0\n\ 940 0.0, 1.0, 0.0, 10.0\n\ 941 1.0, 0.0, 10.0, 0.0\n\ 942 0.0, 1.0, 0.0, 10.0\n\ 943 1.0, 0.0, 10.0, 0.0\n\ 944 0.0, 1.0, 0.0, 10.0\n\ 945 1.0, 0.0, 10.0, 0.0\n\ 946 0.0, 1.0, 0.0, 10.0\n\ 947 1.0, 0.0, 10.0, 0.0\n\ 948 0.0, 1.0, 0.0, 10.0\n\ 949 1.0, 0.0, 10.0, 0.0\n\ 950 0.0, 1.0, 0.0, 10.0\n\ 951 1.0, 0.0, 10.0, 0.0\n\ 952 0.0, 1.0, 0.0, 10.0\n\ 953 1.0, 0.0, 10.0, 0.0\n\ 954 0.0, 1.0, 0.0, 10.0\n\ 955 1.0, 0.0, 10.0, 0.0\n\ 956 0.0, 1.0, 0.0, 10.0\n\ 957 1.0, 0.0, 10.0, 0.0\n\ 958 0.0, 1.0, 0.0, 10.0\n\ 959 1.0, 0.0, 10.0, 0.0\n\ 960 0.0, 1.0, 0.0, 10.0\n\ 961 1.0, 0.0, 10.0, 0.0\n\ 962 0.0, 1.0, 0.0, 10.0\n\ 963 1.0, 0.0, 10.0, 0.0\n\ 964 0.0, 1.0, 0.0, 10.0\n\ 965 1.0, 0.0, 10.0, 0.0\n\ 966 0.0, 1.0, 0.0, 10.0\n\ 967 1.0, 0.0 ,10.4, 40.0\n') 1060 968 file.close() 1061 969 1062 pts_file = tempfile.mktemp(".pts") 1063 970 pts_file = tempfile.mktemp('.pts') 1064 971 convert = Geospatial_data(fileName) 1065 972 convert.export_points_file(pts_file) … … 1069 976 geo_list = [] 1070 977 for i in results: 1071 geo_list.append(i) 978 geo_list.append(i) 1072 979 assert num.allclose(geo_list[0].get_data_points(), 1073 [[1.0, 0.0], [0.0, 1.0]])980 [[1.0, 0.0], [0.0, 1.0]]) 1074 981 assert num.allclose(geo_list[0].get_attributes(attribute_name='elevation'), 1075 982 [10.0, 0.0]) 1076 983 assert num.allclose(geo_list[1].get_data_points(), 1077 [[1.0, 0.0],[0.0, 1.0] ]) 984 [[1.0, 0.0],[0.0, 1.0] ]) 1078 985 assert num.allclose(geo_list[1].get_attributes(attribute_name='elevation'), 1079 986 [10.0, 0.0]) 1080 1081 os.remove(fileName) 987 988 os.remove(fileName) 1082 989 os.remove(pts_file) 1083 1084 1085 990 1086 991 def test_new_export_pts_file(self): … … 1089 994 att_dict['elevation'] = num.array([10.1, 0.0, 10.4]) 1090 995 att_dict['brightness'] = num.array([10.0, 1.0, 10.4]) 1091 1092 fileName = tempfile.mktemp(".pts") 1093 996 997 fileName = tempfile.mktemp('.pts') 1094 998 G = Geospatial_data(pointlist, att_dict) 1095 1096 999 G.export_points_file(fileName) 1097 1098 1000 results = Geospatial_data(file_name = fileName) 1099 1100 os.remove(fileName) 1101 1102 assert num.allclose(results.get_data_points(),[[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]]) 1103 assert num.allclose(results.get_attributes(attribute_name='elevation'), [10.1, 0.0, 10.4]) 1001 os.remove(fileName) 1002 1003 assert num.allclose(results.get_data_points(), 1004 [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1005 assert num.allclose(results.get_attributes(attribute_name='elevation'), 1006 [10.1, 0.0, 10.4]) 1104 1007 answer = [10.0, 1.0, 10.4] 1105 assert num.allclose(results.get_attributes(attribute_name='brightness'), answer) 1008 assert num.allclose(results.get_attributes(attribute_name='brightness'), 1009 answer) 1106 1010 1107 1011 def test_new_export_absolute_pts_file(self): 1108 1012 att_dict = {} 1109 pointlist = num.array([[1.0, 0.0], [0.0, 1.0],[1.0, 0.0]])1013 pointlist = num.array([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1110 1014 att_dict['elevation'] = num.array([10.1, 0.0, 10.4]) 1111 1015 att_dict['brightness'] = num.array([10.0, 1.0, 10.4]) 1112 1016 geo_ref = Geo_reference(50, 25, 55) 1113 1114 fileName = tempfile.mktemp(".pts") 1115 1017 1018 fileName = tempfile.mktemp('.pts') 1116 1019 G = Geospatial_data(pointlist, att_dict, geo_ref) 1117 1118 1020 G.export_points_file(fileName, absolute=True) 1119 1120 1021 results = Geospatial_data(file_name = fileName) 1121 1122 os.remove(fileName) 1123 1124 assert num.allclose(results.get_data_points(), G.get_data_points(True)) 1125 assert num.allclose(results.get_attributes(attribute_name='elevation'), [10.1, 0.0, 10.4]) 1022 os.remove(fileName) 1023 1024 msg = ('results.get_data_points()=%s, but\nG.get_data_points(True)=%s' 1025 % (str(results.get_data_points()), str(G.get_data_points(True)))) 1026 assert num.allclose(results.get_data_points(), 1027 G.get_data_points(True)), msg 1028 msg = ("results.get_attributes(attribute_name='elevation')=%s" 1029 % str(results.get_attributes(attribute_name='elevation'))) 1030 assert num.allclose(results.get_attributes(attribute_name='elevation'), 1031 [10.1, 0.0, 10.4]), msg 1126 1032 answer = [10.0, 1.0, 10.4] 1127 assert num.allclose(results.get_attributes(attribute_name='brightness'), answer) 1033 msg = ("results.get_attributes(attribute_name='brightness')=%s, " 1034 'answer=%s' % 1035 (str(results.get_attributes(attribute_name='brightness')), 1036 str(answer))) 1037 assert num.allclose(results.get_attributes(attribute_name='brightness'), 1038 answer), msg 1128 1039 1129 1040 def test_loadpts(self): 1130 1131 1041 from Scientific.IO.NetCDF import NetCDFFile 1132 1042 1133 fileName = tempfile.mktemp( ".pts")1043 fileName = tempfile.mktemp('.pts') 1134 1044 # NetCDF file definition 1135 1045 outfile = NetCDFFile(fileName, netcdf_mode_w) 1136 1046 1137 1047 # dimension definitions 1138 outfile.createDimension('number_of_points', 3) 1139 outfile.createDimension('number_of_dimensions', 2) # This is 2d data1140 1048 outfile.createDimension('number_of_points', 3) 1049 outfile.createDimension('number_of_dimensions', 2) # This is 2d data 1050 1141 1051 # variable definitions 1142 outfile.createVariable('points', n um.Float, ('number_of_points',1143 'number_of_dimensions'))1144 outfile.createVariable('elevation', n um.Float, ('number_of_points',))1145 1052 outfile.createVariable('points', netcdf_float, ('number_of_points', 1053 'number_of_dimensions')) 1054 outfile.createVariable('elevation', netcdf_float, ('number_of_points',)) 1055 1146 1056 # Get handles to the variables 1147 1057 points = outfile.variables['points'] 1148 1058 elevation = outfile.variables['elevation'] 1149 1059 1150 1060 points[0, :] = [1.0,0.0] 1151 elevation[0] = 10.0 1061 elevation[0] = 10.0 1152 1062 points[1, :] = [0.0,1.0] 1153 elevation[1] = 0.0 1063 elevation[1] = 0.0 1154 1064 points[2, :] = [1.0,0.0] 1155 elevation[2] = 10.4 1065 elevation[2] = 10.4 1156 1066 1157 1067 outfile.close() 1158 1068 1159 1069 results = Geospatial_data(file_name = fileName) 1160 1070 os.remove(fileName) 1161 answer = [[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]] 1162 assert num.allclose(results.get_data_points(), [[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]]) 1163 assert num.allclose(results.get_attributes(attribute_name='elevation'), [10.0, 0.0, 10.4]) 1164 1071 1072 answer = [[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]] 1073 assert num.allclose(results.get_data_points(), 1074 [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1075 assert num.allclose(results.get_attributes(attribute_name='elevation'), 1076 [10.0, 0.0, 10.4]) 1077 1165 1078 def test_writepts(self): 1166 #test_writepts: Test that storage of x,y,attributes works1167 1079 '''Test that storage of x,y,attributes works''' 1080 1168 1081 att_dict = {} 1169 pointlist = num.array([[1.0, 0.0], [0.0, 1.0],[1.0, 0.0]])1082 pointlist = num.array([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1170 1083 att_dict['elevation'] = num.array([10.0, 0.0, 10.4]) 1171 1084 att_dict['brightness'] = num.array([10.0, 0.0, 10.4]) 1172 geo_reference=Geo_reference(56, 1.9,1.9)1085 geo_reference=Geo_reference(56, 1.9, 1.9) 1173 1086 1174 1087 # Test pts format 1175 fileName = tempfile.mktemp( ".pts")1088 fileName = tempfile.mktemp('.pts') 1176 1089 G = Geospatial_data(pointlist, att_dict, geo_reference) 1177 1090 G.export_points_file(fileName, False) … … 1179 1092 os.remove(fileName) 1180 1093 1181 assert num.allclose(results.get_data_points(False),[[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]]) 1182 assert num.allclose(results.get_attributes('elevation'), [10.0, 0.0, 10.4]) 1094 assert num.allclose(results.get_data_points(False), 1095 [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1096 assert num.allclose(results.get_attributes('elevation'), 1097 [10.0, 0.0, 10.4]) 1183 1098 answer = [10.0, 0.0, 10.4] 1184 1099 assert num.allclose(results.get_attributes('brightness'), answer) 1185 1100 self.failUnless(geo_reference == geo_reference, 1186 1101 'test_writepts failed. Test geo_reference') 1187 1102 1188 1103 def test_write_csv_attributes(self): 1189 #test_write : Test that storage of x,y,attributes works1190 1104 '''Test that storage of x,y,attributes works''' 1105 1191 1106 att_dict = {} 1192 pointlist = num.array([[1.0, 0.0], [0.0, 1.0],[1.0, 0.0]])1107 pointlist = num.array([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1193 1108 att_dict['elevation'] = num.array([10.0, 0.0, 10.4]) 1194 1109 att_dict['brightness'] = num.array([10.0, 0.0, 10.4]) 1195 geo_reference=Geo_reference(56,0,0) 1110 geo_reference=Geo_reference(56, 0, 0) 1111 1196 1112 # Test txt format 1197 fileName = tempfile.mktemp( ".txt")1113 fileName = tempfile.mktemp('.txt') 1198 1114 G = Geospatial_data(pointlist, att_dict, geo_reference) 1199 1115 G.export_points_file(fileName) 1200 #print "fileName", fileName1201 1116 results = Geospatial_data(file_name=fileName) 1202 1117 os.remove(fileName) 1203 assert num.allclose(results.get_data_points(False),[[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]]) 1204 assert num.allclose(results.get_attributes('elevation'), [10.0, 0.0, 10.4]) 1118 1119 assert num.allclose(results.get_data_points(False), 1120 [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1121 assert num.allclose(results.get_attributes('elevation'), 1122 [10.0, 0.0, 10.4]) 1205 1123 answer = [10.0, 0.0, 10.4] 1206 1124 assert num.allclose(results.get_attributes('brightness'), answer) 1207 1208 1125 1209 1126 def test_write_csv_attributes_lat_long(self): 1210 #test_write : Test that storage of x,y,attributes works1211 1127 '''Test that storage of x,y,attributes works''' 1128 1212 1129 att_dict = {} 1213 pointlist = num.array([[-21.5, 114.5],[-21.6,114.5],[-21.7,114.5]])1130 pointlist = num.array([[-21.5, 114.5], [-21.6, 114.5], [-21.7, 114.5]]) 1214 1131 att_dict['elevation'] = num.array([10.0, 0.0, 10.4]) 1215 1132 att_dict['brightness'] = num.array([10.0, 0.0, 10.4]) 1133 1216 1134 # Test txt format 1217 fileName = tempfile.mktemp( ".txt")1135 fileName = tempfile.mktemp('.txt') 1218 1136 G = Geospatial_data(pointlist, att_dict, points_are_lats_longs=True) 1219 1137 G.export_points_file(fileName, as_lat_long=True) 1220 #print "fileName", fileName1221 1138 results = Geospatial_data(file_name=fileName) 1222 1139 os.remove(fileName) 1140 1223 1141 assert num.allclose(results.get_data_points(False, as_lat_long=True), 1224 pointlist) 1225 assert num.allclose(results.get_attributes('elevation'), [10.0, 0.0, 10.4]) 1142 pointlist) 1143 assert num.allclose(results.get_attributes('elevation'), 1144 [10.0, 0.0, 10.4]) 1226 1145 answer = [10.0, 0.0, 10.4] 1227 1146 assert num.allclose(results.get_attributes('brightness'), answer) 1228 1147 1229 1148 def test_writepts_no_attributes(self): 1230 1231 #test_writepts_no_attributes: Test that storage of x,y alone works 1232 1149 '''Test that storage of x,y alone works''' 1150 1233 1151 att_dict = {} 1234 pointlist = num.array([[1.0, 0.0], [0.0, 1.0],[1.0, 0.0]])1235 geo_reference=Geo_reference(56, 1.9,1.9)1152 pointlist = num.array([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1153 geo_reference=Geo_reference(56, 1.9, 1.9) 1236 1154 1237 1155 # Test pts format 1238 fileName = tempfile.mktemp( ".pts")1156 fileName = tempfile.mktemp('.pts') 1239 1157 G = Geospatial_data(pointlist, None, geo_reference) 1240 1158 G.export_points_file(fileName, False) … … 1242 1160 os.remove(fileName) 1243 1161 1244 assert num.allclose(results.get_data_points(False),[[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]]) 1162 assert num.allclose(results.get_data_points(False), 1163 [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1245 1164 self.failUnless(geo_reference == geo_reference, 1246 'test_writepts failed. Test geo_reference') 1247 1248 1165 'test_writepts failed. Test geo_reference') 1166 1249 1167 def test_write_csv_no_attributes(self): 1250 #test_write txt _no_attributes: Test that storage of x,y alone works1251 1168 '''Test that storage of x,y alone works''' 1169 1252 1170 att_dict = {} 1253 pointlist = num.array([[1.0, 0.0], [0.0, 1.0],[1.0, 0.0]])1171 pointlist = num.array([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1254 1172 geo_reference=Geo_reference(56,0,0) 1173 1255 1174 # Test format 1256 fileName = tempfile.mktemp( ".txt")1175 fileName = tempfile.mktemp('.txt') 1257 1176 G = Geospatial_data(pointlist, None, geo_reference) 1258 1177 G.export_points_file(fileName) 1259 1178 results = Geospatial_data(file_name=fileName) 1260 1179 os.remove(fileName) 1261 assert num.allclose(results.get_data_points(False),[[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]]) 1262 1263 1264 1265 ########################## BAD .PTS ########################## 1180 1181 assert num.allclose(results.get_data_points(False), 1182 [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1183 1184 ################################################################################ 1185 # Check bad PTS files. 1186 ################################################################################ 1266 1187 1267 1188 def test_load_bad_no_file_pts(self): 1268 import os 1269 import tempfile 1270 1271 fileName = tempfile.mktemp(".pts") 1272 #print fileName 1189 fileName = tempfile.mktemp('.pts') 1273 1190 try: 1274 results = Geospatial_data(file_name = fileName) 1275 # dict = import_points_file(fileName) 1191 results = Geospatial_data(file_name=fileName) 1276 1192 except IOError: 1277 1193 pass 1278 1194 else: 1279 1195 msg = 'imaginary file did not raise error!' 1280 raise msg 1281 # self.failUnless(0 == 1, 1282 # 'imaginary file did not raise error!') 1283 1196 raise Exception, msg 1284 1197 1285 1198 def test_create_from_pts_file(self): 1286 1287 1199 from Scientific.IO.NetCDF import NetCDFFile 1288 1200 1289 # fileName = tempfile.mktemp(".pts") 1201 # NetCDF file definition 1290 1202 FN = 'test_points.pts' 1291 # NetCDF file definition1292 1203 outfile = NetCDFFile(FN, netcdf_mode_w) 1293 1204 1294 1205 # dimension definitions 1295 outfile.createDimension('number_of_points', 3) 1296 outfile.createDimension('number_of_dimensions', 2) # This is 2d data1297 1206 outfile.createDimension('number_of_points', 3) 1207 outfile.createDimension('number_of_dimensions', 2) # This is 2d data 1208 1298 1209 # variable definitions 1299 outfile.createVariable('points', n um.Float, ('number_of_points',1300 'number_of_dimensions'))1301 outfile.createVariable('elevation', n um.Float, ('number_of_points',))1302 1210 outfile.createVariable('points', netcdf_float, ('number_of_points', 1211 'number_of_dimensions')) 1212 outfile.createVariable('elevation', netcdf_float, ('number_of_points',)) 1213 1303 1214 # Get handles to the variables 1304 1215 points = outfile.variables['points'] 1305 1216 elevation = outfile.variables['elevation'] 1306 1217 1307 1218 points[0, :] = [1.0,0.0] 1308 elevation[0] = 10.0 1219 elevation[0] = 10.0 1309 1220 points[1, :] = [0.0,1.0] 1310 elevation[1] = 0.0 1221 elevation[1] = 0.0 1311 1222 points[2, :] = [1.0,0.0] 1312 elevation[2] = 10.4 1223 elevation[2] = 10.4 1313 1224 1314 1225 outfile.close() … … 1318 1229 assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0) 1319 1230 assert num.allclose(G.get_geo_reference().get_yllcorner(), 0.0) 1320 1321 assert num.allclose(G.get_data_points(), [[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]])1231 assert num.allclose(G.get_data_points(), 1232 [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1322 1233 assert num.allclose(G.get_attributes(), [10.0, 0.0, 10.4]) 1323 1234 os.remove(FN) 1324 1235 1325 1236 def test_create_from_pts_file_with_geo(self): 1326 """This test reveals if Geospatial data is correctly instantiated from a pts file. 1327 """ 1328 1237 '''Test if Geospatial data is correctly instantiated from a pts file.''' 1238 1329 1239 from Scientific.IO.NetCDF import NetCDFFile 1330 1240 1241 # NetCDF file definition 1331 1242 FN = 'test_points.pts' 1332 # NetCDF file definition1333 1243 outfile = NetCDFFile(FN, netcdf_mode_w) 1334 1244 … … 1340 1250 1341 1251 # dimension definitions 1342 outfile.createDimension('number_of_points', 3) 1343 outfile.createDimension('number_of_dimensions', 2) # This is 2d data1344 1252 outfile.createDimension('number_of_points', 3) 1253 outfile.createDimension('number_of_dimensions', 2) # This is 2d data 1254 1345 1255 # variable definitions 1346 outfile.createVariable('points', n um.Float, ('number_of_points',1347 'number_of_dimensions'))1348 outfile.createVariable('elevation', n um.Float, ('number_of_points',))1349 1256 outfile.createVariable('points', netcdf_float, ('number_of_points', 1257 'number_of_dimensions')) 1258 outfile.createVariable('elevation', netcdf_float, ('number_of_points',)) 1259 1350 1260 # Get handles to the variables 1351 1261 points = outfile.variables['points'] … … 1353 1263 1354 1264 points[0, :] = [1.0,0.0] 1355 elevation[0] = 10.0 1265 elevation[0] = 10.0 1356 1266 points[1, :] = [0.0,1.0] 1357 elevation[1] = 0.0 1267 elevation[1] = 0.0 1358 1268 points[2, :] = [1.0,0.0] 1359 elevation[2] = 10.4 1269 elevation[2] = 10.4 1360 1270 1361 1271 outfile.close() … … 1365 1275 assert num.allclose(G.get_geo_reference().get_xllcorner(), xll) 1366 1276 assert num.allclose(G.get_geo_reference().get_yllcorner(), yll) 1367 1368 1277 assert num.allclose(G.get_data_points(), [[1.0+xll, 0.0+yll], 1369 1278 [0.0+xll, 1.0+yll], 1370 1279 [1.0+xll, 0.0+yll]]) 1371 1372 1280 assert num.allclose(G.get_attributes(), [10.0, 0.0, 10.4]) 1281 1373 1282 os.remove(FN) 1374 1283 1375 1376 1284 def test_add_(self): 1377 1285 '''test_add_(self): 1378 1286 adds an txt and pts files, reads the files and adds them 1379 1287 checking results are correct 1380 1288 ''' 1289 1381 1290 # create files 1382 1291 att_dict1 = {} 1383 pointlist1 = num.array([[1.0, 0.0], [0.0, 1.0],[1.0, 0.0]])1292 pointlist1 = num.array([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1384 1293 att_dict1['elevation'] = num.array([-10.0, 0.0, 10.4]) 1385 1294 att_dict1['brightness'] = num.array([10.0, 0.0, 10.4]) 1386 1295 geo_reference1 = Geo_reference(56, 2.0, 1.0) 1387 1296 1388 1297 att_dict2 = {} 1389 pointlist2 = num.array([[2.0, 1.0], [1.0, 2.0],[2.0, 1.0]])1298 pointlist2 = num.array([[2.0, 1.0], [1.0, 2.0], [2.0, 1.0]]) 1390 1299 att_dict2['elevation'] = num.array([1.0, 15.0, 1.4]) 1391 1300 att_dict2['brightness'] = num.array([14.0, 1.0, -12.4]) 1392 geo_reference2 = Geo_reference(56, 1.0, 2.0) 1301 geo_reference2 = Geo_reference(56, 1.0, 2.0) 1393 1302 1394 1303 G1 = Geospatial_data(pointlist1, att_dict1, geo_reference1) 1395 1304 G2 = Geospatial_data(pointlist2, att_dict2, geo_reference2) 1396 1397 fileName1 = tempfile.mktemp( ".txt")1398 fileName2 = tempfile.mktemp( ".pts")1399 1400 # makes files1305 1306 fileName1 = tempfile.mktemp('.txt') 1307 fileName2 = tempfile.mktemp('.pts') 1308 1309 # makes files 1401 1310 G1.export_points_file(fileName1) 1402 1311 G2.export_points_file(fileName2) 1403 1312 1404 1313 # add files 1405 1406 G3 = Geospatial_data(file_name = fileName1) 1407 G4 = Geospatial_data(file_name = fileName2) 1408 1314 G3 = Geospatial_data(file_name=fileName1) 1315 G4 = Geospatial_data(file_name=fileName2) 1409 1316 G = G3 + G4 1410 1317 1411 1412 1318 #read results 1413 # print'res', G.get_data_points()1414 # print'res1', G.get_data_points(False)1415 1319 assert num.allclose(G.get_data_points(), 1416 1320 [[ 3.0, 1.0], [ 2.0, 2.0], 1417 1321 [ 3.0, 1.0], [ 3.0, 3.0], 1418 1322 [ 2.0, 4.0], [ 3.0, 3.0]]) 1419 1420 1323 assert num.allclose(G.get_attributes(attribute_name='elevation'), 1421 1324 [-10.0, 0.0, 10.4, 1.0, 15.0, 1.4]) 1422 1423 1325 answer = [10.0, 0.0, 10.4, 14.0, 1.0, -12.4] 1424 assert num.allclose(G.get_attributes(attribute_name='brightness'), answer)1425 1326 assert num.allclose(G.get_attributes(attribute_name='brightness'), 1327 answer) 1426 1328 self.failUnless(G.get_geo_reference() == geo_reference1, 1427 1428 1329 'test_writepts failed. Test geo_reference') 1330 1429 1331 os.remove(fileName1) 1430 1332 os.remove(fileName2) 1431 1333 1432 1334 def test_ensure_absolute(self): 1433 points = [[2.0, 0.0], [1.0, 1.0],1434 [2.0, 0.0],[2.0, 2.0],1435 [1.0, 3.0],[2.0, 2.0]]1335 points = [[2.0, 0.0], [1.0, 1.0], 1336 [2.0, 0.0], [2.0, 2.0], 1337 [1.0, 3.0], [2.0, 2.0]] 1436 1338 new_points = ensure_absolute(points) 1437 1339 1438 1340 assert num.allclose(new_points, points) 1439 1341 1440 points = num.array([[2.0, 0.0], [1.0, 1.0],1441 [2.0, 0.0], [2.0, 2.0],1442 [1.0, 3.0], [2.0, 2.0]])1342 points = num.array([[2.0, 0.0], [1.0, 1.0], 1343 [2.0, 0.0], [2.0, 2.0], 1344 [1.0, 3.0], [2.0, 2.0]]) 1443 1345 new_points = ensure_absolute(points) 1444 1346 1445 1347 assert num.allclose(new_points, points) 1446 1447 ab_points = num.array([[2.0, 0.0], [1.0, 1.0],1448 [2.0, 0.0], [2.0, 2.0],1449 [1.0, 3.0], [2.0, 2.0]])1450 1451 mesh_origin = (56, 290000, 618000) # zone, easting, northing1452 1453 data_points = num.zeros((ab_points.shape), num.Float) 1348 1349 ab_points = num.array([[2.0, 0.0], [1.0, 1.0], 1350 [2.0, 0.0], [2.0, 2.0], 1351 [1.0, 3.0], [2.0, 2.0]]) 1352 1353 mesh_origin = (56, 290000, 618000) # zone, easting, northing 1354 data_points = num.zeros((ab_points.shape), num.float) 1355 1454 1356 #Shift datapoints according to new origins 1455 1357 for k in range(len(ab_points)): 1456 1358 data_points[k][0] = ab_points[k][0] - mesh_origin[1] 1457 1359 data_points[k][1] = ab_points[k][1] - mesh_origin[2] 1458 #print "data_points",data_points 1459 new_points = ensure_absolute(data_points, 1460 geo_reference=mesh_origin) 1461 #print "new_points",new_points 1462 #print "ab_points",ab_points 1463 1360 new_points = ensure_absolute(data_points, geo_reference=mesh_origin) 1361 1464 1362 assert num.allclose(new_points, ab_points) 1465 1363 1466 1364 geo = Geo_reference(56,67,-56) 1467 1468 data_points = geo.change_points_geo_ref(ab_points) 1469 new_points = ensure_absolute(data_points, 1470 geo_reference=geo) 1471 #print "new_points",new_points 1472 #print "ab_points",ab_points 1473 1365 data_points = geo.change_points_geo_ref(ab_points) 1366 new_points = ensure_absolute(data_points, geo_reference=geo) 1367 1474 1368 assert num.allclose(new_points, ab_points) 1475 1476 1369 1477 1370 geo_reference = Geo_reference(56, 100, 200) … … 1479 1372 points = geo_reference.change_points_geo_ref(ab_points) 1480 1373 attributes = [2, 4] 1481 #print "geo in points", points 1482 G = Geospatial_data(points, attributes, 1483 geo_reference=geo_reference) 1484 1374 G = Geospatial_data(points, attributes, geo_reference=geo_reference) 1485 1375 new_points = ensure_absolute(G) 1486 #print "new_points",new_points 1487 #print "ab_points",ab_points 1488 1376 1489 1377 assert num.allclose(new_points, ab_points) 1490 1378 1491 1492 1493 1379 def test_ensure_geospatial(self): 1494 points = [[2.0, 0.0], [1.0, 1.0],1495 [2.0, 0.0],[2.0, 2.0],1496 [1.0, 3.0],[2.0, 2.0]]1380 points = [[2.0, 0.0], [1.0, 1.0], 1381 [2.0, 0.0], [2.0, 2.0], 1382 [1.0, 3.0], [2.0, 2.0]] 1497 1383 new_points = ensure_geospatial(points) 1498 1499 assert num.allclose(new_points.get_data_points(absolute = True), points) 1500 1501 points = num.array([[2.0, 0.0],[1.0, 1.0], 1502 [2.0, 0.0],[2.0, 2.0], 1503 [1.0, 3.0],[2.0, 2.0]]) 1384 assert num.allclose(new_points.get_data_points(absolute=True), points) 1385 1386 points = num.array([[2.0, 0.0], [1.0, 1.0], 1387 [2.0, 0.0], [2.0, 2.0], 1388 [1.0, 3.0], [2.0, 2.0]]) 1504 1389 new_points = ensure_geospatial(points) 1505 1506 assert num.allclose(new_points.get_data_points(absolute = True), points) 1507 1390 assert num.allclose(new_points.get_data_points(absolute=True), points) 1391 1508 1392 ab_points = num.array([[2.0, 0.0],[1.0, 1.0], 1509 1393 [2.0, 0.0],[2.0, 2.0], 1510 1394 [1.0, 3.0],[2.0, 2.0]]) 1511 1512 mesh_origin = (56, 290000, 618000) #zone, easting, northing 1513 1514 data_points = num.zeros((ab_points.shape), num.Float) 1395 mesh_origin = (56, 290000, 618000) # zone, easting, northing 1396 data_points = num.zeros((ab_points.shape), num.float) 1397 1515 1398 #Shift datapoints according to new origins 1516 1399 for k in range(len(ab_points)): 1517 1400 data_points[k][0] = ab_points[k][0] - mesh_origin[1] 1518 1401 data_points[k][1] = ab_points[k][1] - mesh_origin[2] 1519 #print "data_points",data_points1520 1402 new_geospatial = ensure_geospatial(data_points, 1521 1403 geo_reference=mesh_origin) 1522 1404 new_points = new_geospatial.get_data_points(absolute=True) 1523 #print "new_points",new_points1524 #print "ab_points",ab_points1525 1526 1405 assert num.allclose(new_points, ab_points) 1527 1406 1528 geo = Geo_reference(56,67,-56) 1529 1530 data_points = geo.change_points_geo_ref(ab_points) 1531 new_geospatial = ensure_geospatial(data_points, 1532 geo_reference=geo) 1407 geo = Geo_reference(56, 67, -56) 1408 data_points = geo.change_points_geo_ref(ab_points) 1409 new_geospatial = ensure_geospatial(data_points, geo_reference=geo) 1533 1410 new_points = new_geospatial.get_data_points(absolute=True) 1534 #print "new_points",new_points1535 #print "ab_points",ab_points1536 1537 1411 assert num.allclose(new_points, ab_points) 1538 1539 1412 1540 1413 geo_reference = Geo_reference(56, 100, 200) … … 1542 1415 points = geo_reference.change_points_geo_ref(ab_points) 1543 1416 attributes = [2, 4] 1544 #print "geo in points", points 1545 G = Geospatial_data(points, attributes, 1546 geo_reference=geo_reference) 1547 1548 new_geospatial = ensure_geospatial(G) 1417 G = Geospatial_data(points, attributes, geo_reference=geo_reference) 1418 new_geospatial = ensure_geospatial(G) 1549 1419 new_points = new_geospatial.get_data_points(absolute=True) 1550 #print "new_points",new_points1551 #print "ab_points",ab_points1552 1553 1420 assert num.allclose(new_points, ab_points) 1554 1421 1555 1422 def test_isinstance(self): 1556 1557 import os 1558 1559 fileName = tempfile.mktemp(".csv") 1560 file = open(fileName,"w") 1561 file.write("x,y, elevation , speed \n\ 1562 1.0, 0.0, 10.0, 0.0\n\ 1563 0.0, 1.0, 0.0, 10.0\n\ 1564 1.0, 0.0, 10.4, 40.0\n") 1423 fileName = tempfile.mktemp('.csv') 1424 file = open(fileName, 'w') 1425 file.write('x,y, elevation , speed \n\ 1426 1.0, 0.0, 10.0, 0.0\n\ 1427 0.0, 1.0, 0.0, 10.0\n\ 1428 1.0, 0.0, 10.4, 40.0\n') 1565 1429 file.close() 1566 1430 1567 1431 results = Geospatial_data(fileName) 1568 1432 assert num.allclose(results.get_data_points(absolute=True), 1569 [[1.0, 0.0], [0.0, 1.0],[1.0, 0.0]])1433 [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]]) 1570 1434 assert num.allclose(results.get_attributes(attribute_name='elevation'), 1571 1435 [10.0, 0.0, 10.4]) … … 1574 1438 1575 1439 os.remove(fileName) 1576 1577 1440 1578 1441 def test_no_constructors(self): 1579 1580 1442 try: 1581 1443 G = Geospatial_data() 1582 # results = Geospatial_data(file_name = fileName)1583 # dict = import_points_file(fileName)1584 1444 except ValueError: 1585 1445 pass 1586 1446 else: 1587 1447 msg = 'Instance must have a filename or data points' 1588 raise msg1448 raise Exception, msg 1589 1449 1590 1450 def test_load_csv_lat_long(self): 1591 """ 1592 comma delimited 1593 1594 """ 1595 fileName = tempfile.mktemp(".csv") 1596 file = open(fileName,"w") 1597 file.write("long,lat, elevation, yeah \n\ 1451 '''comma delimited''' 1452 1453 fileName = tempfile.mktemp('.csv') 1454 file = open(fileName, 'w') 1455 file.write('long,lat, elevation, yeah \n\ 1598 1456 150.916666667,-34.50,452.688000, 10\n\ 1599 150.0,-34,459.126000, 10\n ")1457 150.0,-34,459.126000, 10\n') 1600 1458 file.close() 1459 1601 1460 results = Geospatial_data(fileName) 1602 1461 os.remove(fileName) 1603 1462 points = results.get_data_points() 1604 1463 1605 1464 assert num.allclose(points[0][0], 308728.009) 1606 1465 assert num.allclose(points[0][1], 6180432.601) 1607 1466 assert num.allclose(points[1][0], 222908.705) 1608 1467 assert num.allclose(points[1][1], 6233785.284) 1609 1610 1468 1611 1469 def test_load_csv_lat_longII(self): 1612 """ 1613 comma delimited 1614 1615 """ 1616 fileName = tempfile.mktemp(".csv") 1617 file = open(fileName,"w") 1618 file.write("Lati,LONG,z \n\ 1470 '''comma delimited''' 1471 1472 fileName = tempfile.mktemp('.csv') 1473 file = open(fileName, 'w') 1474 file.write('Lati,LONG,z \n\ 1619 1475 -34.50,150.916666667,452.688000\n\ 1620 -34,150.0,459.126000\n ")1476 -34,150.0,459.126000\n') 1621 1477 file.close() 1478 1622 1479 results = Geospatial_data(fileName) 1623 1480 os.remove(fileName) 1624 1481 points = results.get_data_points() 1625 1482 1626 1483 assert num.allclose(points[0][0], 308728.009) 1627 1484 assert num.allclose(points[0][1], 6180432.601) 1628 assert num.allclose(points[1][0], 1485 assert num.allclose(points[1][0], 222908.705) 1629 1486 assert num.allclose(points[1][1], 6233785.284) 1630 1487 1631 1632 1488 def test_load_csv_lat_long_bad(self): 1633 """ 1634 comma delimited 1635 1636 """ 1637 fileName = tempfile.mktemp(".csv") 1638 file = open(fileName,"w") 1639 file.write("Lati,LONG,z \n\ 1489 '''comma delimited''' 1490 1491 fileName = tempfile.mktemp('.csv') 1492 file = open(fileName, 'w') 1493 file.write('Lati,LONG,z \n\ 1640 1494 -25.0,180.0,452.688000\n\ 1641 -34,150.0,459.126000\n ")1495 -34,150.0,459.126000\n') 1642 1496 file.close() 1497 1643 1498 try: 1644 1499 results = Geospatial_data(fileName) … … 1647 1502 else: 1648 1503 msg = 'Different zones in Geo references not caught.' 1649 raise msg1650 1651 os.remove(fileName) 1652 1504 raise Exception, msg 1505 1506 os.remove(fileName) 1507 1653 1508 def test_lat_long(self): 1654 lat_gong = degminsec2decimal_degrees(-34, 30,0.)1655 lon_gong = degminsec2decimal_degrees(150, 55,0.)1656 1657 lat_2 = degminsec2decimal_degrees(-34, 00,0.)1658 lon_2 = degminsec2decimal_degrees(150, 00,0.)1659 1509 lat_gong = degminsec2decimal_degrees(-34, 30, 0.) 1510 lon_gong = degminsec2decimal_degrees(150, 55, 0.) 1511 1512 lat_2 = degminsec2decimal_degrees(-34, 00, 0.) 1513 lon_2 = degminsec2decimal_degrees(150, 00, 0.) 1514 1660 1515 lats = [lat_gong, lat_2] 1661 1516 longs = [lon_gong, lon_2] … … 1663 1518 1664 1519 points = gsd.get_data_points(absolute=True) 1665 1520 1666 1521 assert num.allclose(points[0][0], 308728.009) 1667 1522 assert num.allclose(points[0][1], 6180432.601) 1668 assert num.allclose(points[1][0], 1523 assert num.allclose(points[1][0], 222908.705) 1669 1524 assert num.allclose(points[1][1], 6233785.284) 1670 1525 self.failUnless(gsd.get_geo_reference().get_zone() == 56, 1671 1526 'Bad zone error!') 1672 1527 1673 1528 try: 1674 1529 results = Geospatial_data(latitudes=lats) … … 1676 1531 pass 1677 1532 else: 1678 self.fail Unless(0 ==1,'Error not thrown error!')1533 self.fail('Error not thrown error!') 1679 1534 try: 1680 1535 results = Geospatial_data(latitudes=lats) … … 1682 1537 pass 1683 1538 else: 1684 self.fail Unless(0 ==1,'Error not thrown error!')1539 self.fail('Error not thrown error!') 1685 1540 try: 1686 1541 results = Geospatial_data(longitudes=lats) … … 1688 1543 pass 1689 1544 else: 1690 self.fail Unless(0 ==1,'Error not thrown error!')1545 self.fail('Error not thrown error!') 1691 1546 try: 1692 1547 results = Geospatial_data(latitudes=lats, longitudes=longs, … … 1695 1550 pass 1696 1551 else: 1697 self.fail Unless(0 ==1,'Error not thrown error!')1698 1552 self.fail('Error not thrown error!') 1553 1699 1554 try: 1700 1555 results = Geospatial_data(latitudes=lats, longitudes=longs, … … 1703 1558 pass 1704 1559 else: 1705 self.fail Unless(0 ==1,'Error not thrown error!')1560 self.fail('Error not thrown error!') 1706 1561 1707 1562 def test_lat_long2(self): 1708 lat_gong = degminsec2decimal_degrees(-34, 30,0.)1709 lon_gong = degminsec2decimal_degrees(150, 55,0.)1710 1711 lat_2 = degminsec2decimal_degrees(-34, 00,0.)1712 lon_2 = degminsec2decimal_degrees(150, 00,0.)1713 1563 lat_gong = degminsec2decimal_degrees(-34, 30, 0.) 1564 lon_gong = degminsec2decimal_degrees(150, 55, 0.) 1565 1566 lat_2 = degminsec2decimal_degrees(-34, 00, 0.) 1567 lon_2 = degminsec2decimal_degrees(150, 00, 0.) 1568 1714 1569 points = [[lat_gong, lon_gong], [lat_2, lon_2]] 1715 1570 gsd = Geospatial_data(data_points=points, points_are_lats_longs=True) 1716 1571 1717 1572 points = gsd.get_data_points(absolute=True) 1718 1573 1719 1574 assert num.allclose(points[0][0], 308728.009) 1720 1575 assert num.allclose(points[0][1], 6180432.601) 1721 assert num.allclose(points[1][0], 1576 assert num.allclose(points[1][0], 222908.705) 1722 1577 assert num.allclose(points[1][1], 6233785.284) 1723 1578 self.failUnless(gsd.get_geo_reference().get_zone() == 56, … … 1729 1584 pass 1730 1585 else: 1731 self.failUnless(0 ==1, 'Error not thrown error!') 1732 1586 self.fail('Error not thrown error!') 1733 1587 1734 1588 def test_write_urs_file(self): 1735 lat_gong = degminsec2decimal_degrees(-34, 00,0)1736 lon_gong = degminsec2decimal_degrees(150, 30,0.)1737 1738 lat_2 = degminsec2decimal_degrees(-34, 00,1)1739 lon_2 = degminsec2decimal_degrees(150, 00,0.)1589 lat_gong = degminsec2decimal_degrees(-34, 00, 0) 1590 lon_gong = degminsec2decimal_degrees(150, 30, 0.) 1591 1592 lat_2 = degminsec2decimal_degrees(-34, 00, 1) 1593 lon_2 = degminsec2decimal_degrees(150, 00, 0.) 1740 1594 p1 = (lat_gong, lon_gong) 1741 1595 p2 = (lat_2, lon_2) … … 1743 1597 gsd = Geospatial_data(data_points=list(points), 1744 1598 points_are_lats_longs=True) 1745 1746 fn = tempfile.mktemp( ".urs")1599 1600 fn = tempfile.mktemp('.urs') 1747 1601 gsd.export_points_file(fn) 1748 #print "fn", fn1749 1602 handle = open(fn) 1750 1603 lines = handle.readlines() 1751 assert lines[0], '2'1752 assert lines[1], '-34.0002778 150.0 0'1753 assert lines[2], '-34.0 150.5 1'1604 assert lines[0], '2' 1605 assert lines[1], '-34.0002778 150.0 0' 1606 assert lines[2], '-34.0 150.5 1' 1754 1607 handle.close() 1755 1608 os.remove(fn) 1756 1609 1757 1610 def test_lat_long_set(self): 1758 lat_gong = degminsec2decimal_degrees(-34, 30,0.)1759 lon_gong = degminsec2decimal_degrees(150, 55,0.)1760 1761 lat_2 = degminsec2decimal_degrees(-34, 00,0.)1762 lon_2 = degminsec2decimal_degrees(150, 00,0.)1611 lat_gong = degminsec2decimal_degrees(-34, 30, 0.) 1612 lon_gong = degminsec2decimal_degrees(150, 55, 0.) 1613 1614 lat_2 = degminsec2decimal_degrees(-34, 00, 0.) 1615 lon_2 = degminsec2decimal_degrees(150, 00, 0.) 1763 1616 p1 = (lat_gong, lon_gong) 1764 1617 p2 = (lat_2, lon_2) … … 1768 1621 1769 1622 points = gsd.get_data_points(absolute=True) 1770 #print "points[0][0]", points[0][0]1771 1623 #Note the order is unknown, due to using sets 1772 1624 # and it changes from windows to linux … … 1774 1626 assert num.allclose(points[1][0], 308728.009) 1775 1627 assert num.allclose(points[1][1], 6180432.601) 1776 assert num.allclose(points[0][0], 1628 assert num.allclose(points[0][0], 222908.705) 1777 1629 assert num.allclose(points[0][1], 6233785.284) 1778 1630 except AssertionError: 1779 1631 assert num.allclose(points[0][0], 308728.009) 1780 1632 assert num.allclose(points[0][1], 6180432.601) 1781 assert num.allclose(points[1][0], 1633 assert num.allclose(points[1][0], 222908.705) 1782 1634 assert num.allclose(points[1][1], 6233785.284) 1783 1635 1784 1636 self.failUnless(gsd.get_geo_reference().get_zone() == 56, 1785 1637 'Bad zone error!') 1786 1638 points = gsd.get_data_points(as_lat_long=True) 1787 #print "test_lat_long_set points", points1788 1639 try: 1789 1640 assert num.allclose(points[0][0], -34) … … 1794 1645 1795 1646 def test_len(self): 1796 1797 1647 points = [[1.0, 2.1], [3.0, 5.3]] 1798 1648 G = Geospatial_data(points) 1799 self.failUnless(2 == len(G),'Len error!')1800 1649 self.failUnless(2 == len(G), 'Len error!') 1650 1801 1651 points = [[1.0, 2.1]] 1802 1652 G = Geospatial_data(points) 1803 self.failUnless(1 == len(G),'Len error!')1653 self.failUnless(1 == len(G), 'Len error!') 1804 1654 1805 1655 points = [[1.0, 2.1], [3.0, 5.3], [3.0, 5.3], [3.0, 5.3]] 1806 1656 G = Geospatial_data(points) 1807 self.failUnless(4 == len(G),'Len error!')1808 1657 self.failUnless(4 == len(G), 'Len error!') 1658 1809 1659 def test_split(self): 1810 1660 """test if the results from spilt are disjoin sets""" 1811 1812 #below is a work around until the randint works on cyclones compute nodes 1813 if get_host_name()[8:9]!='0': 1814 1815 1661 1662 # below is a workaround until randint works on cyclones compute nodes 1663 if get_host_name()[8:9] != '0': 1816 1664 points = [[1.0, 1.0], [1.0, 2.0],[1.0, 3.0], [1.0, 4.0], [1.0, 5.0], 1817 1665 [2.0, 1.0], [2.0, 2.0],[2.0, 3.0], [2.0, 4.0], [2.0, 5.0], … … 1819 1667 [4.0, 1.0], [4.0, 2.0],[4.0, 3.0], [4.0, 4.0], [4.0, 5.0], 1820 1668 [5.0, 1.0], [5.0, 2.0],[5.0, 3.0], [5.0, 4.0], [5.0, 5.0]] 1821 attributes = {'depth':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1822 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25], 1823 'speed':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1824 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]} 1669 attributes = {'depth': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1670 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1671 21, 22, 23, 24, 25], 1672 'speed': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1673 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1674 21, 22, 23, 24, 25]} 1825 1675 G = Geospatial_data(points, attributes) 1826 1676 1827 1677 factor = 0.21 1828 1829 #will return G1 with 10% of points and G2 with 90% 1830 G1, G2 = G.split(factor,100) 1831 1678 1679 # will return G1 with 10% of points and G2 with 90% 1680 G1, G2 = G.split(factor, 100) 1832 1681 assert num.allclose(len(G), len(G1)+len(G2)) 1833 1682 assert num.allclose(round(len(G)*factor), len(G1)) 1834 1683 1835 1684 P = G1.get_data_points(absolute=False) 1836 assert num.allclose(P, [[5.0,4.0],[4.0,3.0],[4.0,2.0],[3.0,1.0],[2.0,3.0]]) 1837 1685 expected = [[5.0, 4.0], [4.0, 3.0], [4.0, 2.0], 1686 [3.0, 1.0], [2.0, 3.0]] 1687 msg = 'Expected %s, but\nP=%s' % (str(expected), str(P)) 1688 assert num.allclose(P, expected), msg 1689 1838 1690 A = G1.get_attributes() 1839 assert num.allclose(A,[24, 18, 17, 11, 8]) 1840 1691 expected = [24, 18, 17, 11, 8] 1692 msg = 'expected=%s, but A=%s' % (str(expected), str(A)) 1693 assert num.allclose(A, expected), msg 1694 1841 1695 def test_split1(self): 1842 """test if the results from sp ilt are disjoinsets"""1843 #below is a work around until the randint works on cyclones compute nodes 1844 if get_host_name()[8:9]!='0':1845 1696 """test if the results from split are disjoint sets""" 1697 1698 # below is a workaround until randint works on cyclones compute nodes 1699 if get_host_name()[8:9] != '0': 1846 1700 from RandomArray import randint,seed 1701 1847 1702 seed(100,100) 1848 a_points = randint(0, 999999,(10,2))1703 a_points = randint(0, 999999, (10,2)) 1849 1704 points = a_points.tolist() 1850 # print points 1851 1705 1852 1706 G = Geospatial_data(points) 1853 1707 1854 1708 factor = 0.1 1855 1856 #will return G1 with 10% of points and G2 with 90% 1857 G1, G2 = G.split(factor,100) 1858 1859 # print 'G1',G1 1709 1710 # will return G1 with 10% of points and G2 with 90% 1711 G1, G2 = G.split(factor, 100) 1860 1712 assert num.allclose(len(G), len(G1)+len(G2)) 1861 1713 assert num.allclose(round(len(G)*factor), len(G1)) 1862 1714 1863 1715 P = G1.get_data_points(absolute=False) 1864 assert num.allclose(P, [[982420.,28233.]]) 1865 1866 1716 expected = [[982420., 28233.]] 1717 msg = 'expected=%s, but\nP=%s' % (str(expected), str(P)) 1718 assert num.allclose(P, expected), msg 1719 1867 1720 def test_find_optimal_smoothing_parameter(self): 1868 1721 """ 1869 Creates a elevation file repres ting hill (sort of) and runs1722 Creates a elevation file representing a hill (sort of) and runs 1870 1723 find_optimal_smoothing_parameter for 3 different alphas, 1871 1724 1872 1725 NOTE the random number seed is provided to control the results 1873 1726 """ 1727 1874 1728 from cmath import cos 1875 1729 1876 # below is a work around until therandint works on cyclones compute nodes1730 # below is a workaround until randint works on cyclones compute nodes 1877 1731 if get_host_name()[8:9]!='0': 1878 1879 filename = tempfile.mktemp(".csv") 1880 file = open(filename,"w") 1881 file.write("x,y,elevation \n") 1882 1883 for i in range(-5,6): 1884 for j in range(-5,6): 1885 #this equation made surface like a circle ripple 1732 filename = tempfile.mktemp('.csv') 1733 file = open(filename, 'w') 1734 file.write('x,y,elevation \n') 1735 1736 for i in range(-5, 6): 1737 for j in range(-5, 6): 1738 # this equation makes a surface like a circle ripple 1886 1739 z = abs(cos(((i*i) + (j*j))*.1)*2) 1887 # print 'x,y,f',i,j,z 1888 file.write("%s, %s, %s\n" %(i, j, z)) 1889 1740 file.write("%s, %s, %s\n" % (i, j, z)) 1741 1890 1742 file.close() 1891 1892 value, alpha = find_optimal_smoothing_parameter(data_file=filename, 1743 1744 value, alpha = find_optimal_smoothing_parameter(data_file=filename, 1893 1745 alpha_list=[0.0001, 0.01, 1], 1894 1746 mesh_file=None, … … 1901 1753 seed_num=100000, 1902 1754 verbose=False) 1903 1755 1904 1756 os.remove(filename) 1905 1757 1906 1758 # print value, alpha 1907 assert (alpha==0.01)1759 assert(alpha == 0.01) 1908 1760 1909 1761 def test_find_optimal_smoothing_parameter1(self): 1910 1762 """ 1911 Creates a elevation file repres tinghill (sort of) and1763 Creates a elevation file representing a hill (sort of) and 1912 1764 Then creates a mesh file and passes the mesh file and the elevation 1913 1765 file to find_optimal_smoothing_parameter for 3 different alphas, 1914 1766 1915 1767 NOTE the random number seed is provided to control the results 1916 1768 """ 1917 #below is a work around until the randint works on cyclones compute nodes 1769 1770 # below is a workaround until randint works on cyclones compute nodes 1918 1771 if get_host_name()[8:9]!='0': 1919 1920 1772 from cmath import cos 1921 1773 from anuga.pmesh.mesh_interface import create_mesh_from_regions 1922 1923 filename = tempfile.mktemp( ".csv")1924 file = open(filename, "w")1925 file.write( "x,y,elevation \n")1926 1927 for i in range(-5 ,6):1928 for j in range(-5, 6):1929 # this equation madesurface like a circle ripple1774 1775 filename = tempfile.mktemp('.csv') 1776 file = open(filename, 'w') 1777 file.write('x,y,elevation \n') 1778 1779 for i in range(-5 ,6): 1780 for j in range(-5, 6): 1781 # this equation makes a surface like a circle ripple 1930 1782 z = abs(cos(((i*i) + (j*j))*.1)*2) 1931 # print 'x,y,f',i,j,z 1932 file.write("%s, %s, %s\n" %(i, j, z)) 1933 1783 file.write('%s, %s, %s\n' % (i, j, z)) 1784 1934 1785 file.close() 1935 poly=[[5,5],[5,-5],[-5,-5],[-5,5]] 1936 internal_poly=[[[[1,1],[1,-1],[-1,-1],[-1,1]],.5]] 1937 mesh_filename= tempfile.mktemp(".msh") 1938 1786 1787 poly=[[5,5], [5,-5], [-5,-5], [-5,5]] 1788 internal_poly=[[[[1,1], [1,-1], [-1,-1], [-1,1]], .5]] 1789 mesh_filename= tempfile.mktemp('.msh') 1790 1939 1791 create_mesh_from_regions(poly, 1940 boundary_tags={'back': [2],1941 'side': [1,3],1942 'ocean': [0]},1943 maximum_triangle_area=3,1944 interior_regions=internal_poly,1945 filename=mesh_filename,1946 use_cache=False,1947 verbose=False)1948 1949 value, alpha = find_optimal_smoothing_parameter(data_file=filename, 1792 boundary_tags={'back': [2], 1793 'side': [1,3], 1794 'ocean': [0]}, 1795 maximum_triangle_area=3, 1796 interior_regions=internal_poly, 1797 filename=mesh_filename, 1798 use_cache=False, 1799 verbose=False) 1800 1801 value, alpha = find_optimal_smoothing_parameter(data_file=filename, 1950 1802 alpha_list=[0.0001, 0.01, 1], 1951 1803 mesh_file=mesh_filename, … … 1953 1805 seed_num=174, 1954 1806 verbose=False) 1955 1807 1956 1808 os.remove(filename) 1957 1809 os.remove(mesh_filename) 1958 1959 # print value, alpha 1960 assert (alpha==0.01) 1810 1811 assert(alpha == 0.01) 1961 1812 1962 1813 def test_find_optimal_smoothing_parameter2(self): 1963 """ 1964 Tests requirement that mesh file must exist or IOError is thrown 1965 1814 '''Tests requirement that mesh file must exist or IOError is thrown 1815 1966 1816 NOTE the random number seed is provided to control the results 1967 """ 1817 ''' 1818 1968 1819 from cmath import cos 1969 1820 from anuga.pmesh.mesh_interface import create_mesh_from_regions 1970 1971 filename = tempfile.mktemp( ".csv")1972 mesh_filename= tempfile.mktemp( ".msh")1973 1821 1822 filename = tempfile.mktemp('.csv') 1823 mesh_filename= tempfile.mktemp('.msh') 1824 1974 1825 try: 1975 value, alpha = find_optimal_smoothing_parameter(data_file=filename, 1826 value, alpha = find_optimal_smoothing_parameter(data_file=filename, 1976 1827 alpha_list=[0.0001, 0.01, 1], 1977 1828 mesh_file=mesh_filename, … … 1982 1833 pass 1983 1834 else: 1984 self.failUnless(0 ==1, 'Error not thrown error!') 1985 1986 1835 self.fail('Error not thrown error!') 1836 1837 ################################################################################ 1838 # Test the clean_line() utility function. 1839 ################################################################################ 1840 1841 # helper routine to test clean_line() 1842 def clean_line_test(self, instr, delim, expected): 1843 result = clean_line(instr, delim) 1844 self.failUnless(result == expected, 1845 "clean_line('%s', '%s'), expected %s, got %s" 1846 % (str(instr), str(delim), str(expected), str(result))) 1847 1848 def test_clean_line_01(self): 1849 self.clean_line_test('abc, ,,xyz,123', ',', ['abc', '', 'xyz', '123']) 1850 1851 def test_clean_line_02(self): 1852 self.clean_line_test(' abc , ,, xyz , 123 ', ',', 1853 ['abc', '', 'xyz', '123']) 1854 1855 def test_clean_line_03(self): 1856 self.clean_line_test('1||||2', '|', ['1', '2']) 1857 1858 def test_clean_line_04(self): 1859 self.clean_line_test('abc, ,,xyz,123, ', ',', 1860 ['abc', '', 'xyz', '123', '']) 1861 1862 def test_clean_line_05(self): 1863 self.clean_line_test('abc, ,,xyz,123, , ', ',', 1864 ['abc', '', 'xyz', '123', '', '']) 1865 1866 def test_clean_line_06(self): 1867 self.clean_line_test(',,abc, ,,xyz,123, , ', ',', 1868 ['abc', '', 'xyz', '123', '', '']) 1869 1870 def test_clean_line_07(self): 1871 self.clean_line_test('|1||||2', '|', ['1', '2']) 1872 1873 def test_clean_line_08(self): 1874 self.clean_line_test(' ,a,, , ,b,c , ,, , ', ',', 1875 ['', 'a', '', '', 'b', 'c', '', '', '']) 1876 1877 def test_clean_line_09(self): 1878 self.clean_line_test('a:b:c', ':', ['a', 'b', 'c']) 1879 1880 def test_clean_line_10(self): 1881 self.clean_line_test('a:b:c:', ':', ['a', 'b', 'c']) 1882 1883 # new version of function should leave last field if contains '\n'. 1884 # cf. test_clean_line_10() above. 1885 def test_clean_line_11(self): 1886 self.clean_line_test('a:b:c:\n', ':', ['a', 'b', 'c', '']) 1887 1987 1888 if __name__ == "__main__": 1988 1989 #suite = unittest.makeSuite(Test_Geospatial_data, 'test_write_csv_attributes_lat_long')1990 #suite = unittest.makeSuite(Test_Geospatial_data, 'test_find_optimal_smoothing_parameter')1991 #suite = unittest.makeSuite(Test_Geospatial_data, 'test_split1')1992 1889 suite = unittest.makeSuite(Test_Geospatial_data, 'test') 1993 1890 runner = unittest.TextTestRunner() #verbosity=2) 1994 1891 runner.run(suite) 1995 1892 1996 1893 -
branches/numpy/anuga/load_mesh/loadASCII.py
r6166 r6304 58 58 59 59 from string import find, rfind 60 import Numericas num60 import numpy as num 61 61 from os.path import splitext 62 62 … … 66 66 from Scientific.IO.NetCDF import NetCDFFile 67 67 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 68 68 from anuga.config import netcdf_float, netcdf_char, netcdf_int 69 69 70 70 import exceptions 71 72 71 73 class TitleAmountError(exceptions.Exception): pass 72 74 … … 82 84 # @note This is used by pmesh. 83 85 def import_mesh_file(ofile): 84 """ 85 read a mesh file, either .tsh or .msh 86 """Read a mesh file, either .tsh or .msh 86 87 87 88 Note: will throw an IOError if it can't load the file. 88 89 Catch these! 89 90 """ 90 try: 91 if ofile[-4:]== ".tsh": 91 92 try: 93 if ofile[-4:] == ".tsh": 92 94 dict = _read_tsh_file(ofile) 93 elif ofile[-4:] == ".msh":95 elif ofile[-4:] == ".msh": 94 96 dict = _read_msh_file(ofile) 95 97 else: … … 98 100 #FIXME No test for ValueError 99 101 except (TitleError, SyntaxError, IndexError, ValueError): 100 101 102 msg = 'File could not be opened' 103 raise IOError, msg 102 104 return dict 103 105 … … 109 111 # @note Raises IOError if file extension is unrecognized. 110 112 def export_mesh_file(ofile, mesh_dict): 111 """ 112 write a file, ofile, with the format 113 """Write a mesh file given a dictionary. 113 114 114 115 First line: <# of vertices> <# of attributes> … … 137 138 # hand-off to appropriate function 138 139 if (ofile[-4:] == ".tsh"): 139 _write_tsh_file(ofile, mesh_dict)140 _write_tsh_file(ofile, mesh_dict) 140 141 elif (ofile[-4:] == ".msh"): 141 142 _write_msh_file(ofile, mesh_dict) 142 143 else: 143 msg = 'Unknown file type %s ' % ofile144 msg = 'Unknown file type %s ' % ofile 144 145 raise IOError, msg 145 146 146 147 147 148 ## 148 # @brief Read .tsh file into a dictionary.149 # @brief Read a mesh file into a dictionary. 149 150 # @param ofile Path of the file to read. 150 # @return Data dictionary from the .tshfile.151 # @return Data dictionary from the mesh (.tsh) file. 151 152 def _read_tsh_file(ofile): 152 """ 153 Read the text file format for meshes 154 """ 153 """Read the text file format for meshes""" 155 154 156 155 fd = open(ofile, 'r') … … 169 168 # @return A dictionary ... 170 169 def _read_triangulation(fd): 171 """ 172 Read the generated triangulation, NOT the outline. 173 """ 170 """Read the generated triangulation, NOT the outline.""" 174 171 175 172 delimiter = " " … … 178 175 line = fd.readline() 179 176 fragments = line.split() 180 if fragments == []:177 if fragments == []: 181 178 NumOfVertices = 0 182 179 NumOfVertAttributes = 0 … … 188 185 for index in range(int(NumOfVertices)): 189 186 fragments = fd.readline().split() 190 fragments.pop(0) #pop off the index191 192 # pop the x y off so we're left with a list of attributes187 fragments.pop(0) # pop off the index 188 189 # pop the x & y off so we're left with a list of attributes 193 190 vert = [float(fragments.pop(0)), float(fragments.pop(0))] 194 191 points.append(vert) … … 215 212 for index in range(int(NumOfTriangles)): 216 213 line = fd.readline() 217 line.strip() # so we can get the region string214 line.strip() # so we can get the region string 218 215 fragments = line.split() 219 fragments.pop(0) #pop off the index216 fragments.pop(0) # pop off the index 220 217 221 218 tri = [int(fragments[0]), int(fragments[1]), int(fragments[2])] … … 223 220 neighbors = [int(fragments[3]), int(fragments[4]), int(fragments[5])] 224 221 triangleneighbors.append(neighbors) 225 for x in range(7): # remove index [<vertex #>] [<neigbouring tri #>]226 line = line[find(line, delimiter):] # remove index222 for x in range(7): # remove index [<vertex #>] [<neigbouring tri #>] 223 line = line[find(line, delimiter):] # remove index 227 224 line = line.lstrip() 228 225 stringtag = line.strip() … … 237 234 for index in range(int(NumOfSegments)): 238 235 line = fd.readline() 239 line.strip() # to get the segment string236 line.strip() # to get the segment string 240 237 fragments = line.split() 241 fragments.pop(0) #pop off the index238 fragments.pop(0) #pop off the index 242 239 seg = [int(fragments[0]), int(fragments[1])] 243 240 segments.append(seg) … … 272 269 # @note If file has no mesh info, an empty dict will be returned. 273 270 def _read_outline(fd): 271 """Read a mesh file outline. 272 273 Note, if a file has no mesh info, it can still be read - 274 the meshdic returned will be 'empty'. 274 275 """ 275 Note, if a file has no mesh info, it can still be read - the meshdic 276 returned will be 'empty'. 277 """ 278 279 delimiter = " " # warning: split() calls are using default whitespace 276 277 delimiter = " " # warning: split() calls are using default whitespace 280 278 281 279 # loading the point info 282 280 line = fd.readline() 283 281 fragments = line.split() 284 if fragments == []:282 if fragments == []: 285 283 NumOfVertices = 0 286 284 NumOfVertAttributes = 0 … … 292 290 for index in range(int(NumOfVertices)): 293 291 fragments = fd.readline().split() 294 fragments.pop(0) #pop off the index295 # pop the x y off so we're left with a list of attributes292 fragments.pop(0) # pop off the index 293 # pop the x & y off so we're left with a list of attributes 296 294 vert = [float(fragments.pop(0)), float(fragments.pop(0))] 297 295 points.append(vert) … … 304 302 line = fd.readline() 305 303 fragments = line.split() 306 if fragments == []:304 if fragments == []: 307 305 NumOfSegments = 0 308 306 else: … … 313 311 line = fd.readline() 314 312 fragments = line.split() 315 fragments.pop(0) #pop off the index313 fragments.pop(0) # pop off the index 316 314 seg = [int(fragments[0]), int(fragments[1])] 317 315 segments.append(seg) … … 350 348 line = fd.readline() 351 349 fragments = line.split() 352 fragments.pop(0) #pop off the index350 fragments.pop(0) # pop off the index 353 351 region = [float(fragments[0]), float(fragments[1])] 354 352 regions.append(region) … … 364 362 regionmaxareas = [] 365 363 line = fd.readline() 366 for index in range(int(numOfRegions)): # Read in the Max area info364 for index in range(int(numOfRegions)): # Read in the Max area info 367 365 line = fd.readline() 368 366 fragments = line.split() 369 367 # The try is here for format compatibility 370 368 try: 371 fragments.pop(0) #pop off the index372 if len(fragments) == 0: #no max area369 fragments.pop(0) # pop off the index 370 if len(fragments) == 0: # no max area 373 371 regionmaxareas.append(None) 374 372 else: … … 404 402 # @note Will also remove any field that was originally ''. 405 403 def clean_line(line, delimiter): 406 """Remove whitespace 407 """ 404 """Clean up a line - return fields with end space removed.""" 408 405 409 406 line = line.strip() … … 447 444 # Don't understand why we have to do vertices_attributes[0] is None, 448 445 # but it doesn't work otherwise... 449 if vertices_attributes == None \450 or (numVert == "0") \451 or len(vertices_attributes) == 0:446 if (vertices_attributes == None or 447 numVert == "0" or 448 len(vertices_attributes) == 0): 452 449 numVertAttrib = "0" 453 450 else: … … 478 475 fd.write(title + "\n") 479 476 480 # <# of triangles>477 # <# of triangles> 481 478 n = len(triangles) 482 479 fd.write(str(n) … … 501 498 else: 502 499 neighbors += "-1 " 503 # Warning even though a list is past, only the first value504 # is written. There's an assumption that the list only500 # Warning even though a list is passed, only the first value 501 # is written. There's an assumption that the list only 505 502 # contains one item. This assumption is made since the 506 # dict that's being passed around is also be used to communicate503 # dict that's being passed around is also be used to communicate 507 504 # with triangle, and it seems to have the option of returning 508 505 # more than one value for triangle attributex 509 if triangles_attributes == None \510 or triangles_attributes == [] \511 or triangles_attributes[index] == ['']:506 if (triangles_attributes == None or 507 triangles_attributes == [] or 508 triangles_attributes[index] == ['']): 512 509 att = "" 513 510 else: … … 520 517 + att + "\n") 521 518 522 # One line: <# of segments>519 # One line: <# of segments> 523 520 fd.write(str(len(segments)) + 524 521 " # <# of segments>, next lines <segment #> <vertex #> " 525 522 "<vertex #> [boundary tag] ...Triangulation Segments...\n") 526 523 527 # Following lines: <segment #> <vertex #> <vertex #> [boundary tag]524 # Following lines: <segment #> <vertex #> <vertex #> [boundary tag] 528 525 for i in range(len(segments)): 529 526 seg = segments[i] … … 560 557 561 558 num_points = str(len(points)) 562 if (num_points == "0"):563 num_point_atts = "0"559 if (num_points == '0'): 560 num_point_atts = '0' 564 561 else: 565 562 num_point_atts = str(len(point_attributes[0])) 566 563 567 fd.write(num_points + " "+ num_point_atts +568 " # <# of verts> <# of vert attributes>, next lines <vertex #> "569 "<x> <y> [attributes] ...Mesh Vertices...\n")564 fd.write(num_points + ' ' + num_point_atts + 565 ' # <# of verts> <# of vert attributes>, next lines <vertex #> ' 566 '<x> <y> [attributes] ...Mesh Vertices...\n') 570 567 571 568 # <x> <y> [attributes] 572 for i, point in enumerate(points):573 attlist = ""569 for i, point in enumerate(points): 570 attlist = '' 574 571 for att in point_attributes[i]: 575 attlist = attlist + str(att) + " "572 attlist = attlist + str(att) + ' ' 576 573 attlist.strip() 577 fd.write(str(i) + " " 578 + str(point[0]) + " " 579 + str(point[1]) + " " 580 + attlist + "\n") 581 582 #One line: <# of segments> 574 fd.write(str(i) + ' ' + str(point[0]) + ' ' + str(point[1]) + ' ' + 575 attlist + '\n') 576 577 # One line: <# of segments> 583 578 fd.write(str(len(segments)) + 584 " # <# of segments>, next lines <segment #> <vertex #> "585 "<vertex #> [boundary tag] ...Mesh Segments...\n")586 587 # Following lines: <vertex #> <vertex #> [boundary tag]579 ' # <# of segments>, next lines <segment #> <vertex #> ' 580 '<vertex #> [boundary tag] ...Mesh Segments...\n') 581 582 # Following lines: <vertex #> <vertex #> [boundary tag] 588 583 for i,seg in enumerate(segments): 589 fd.write(str(i) + " " 590 + str(seg[0]) + " " 591 + str(seg[1]) + " " 592 + str(segment_tags[i]) + "\n") 593 594 #One line: <# of holes> 584 fd.write(str(i) + ' ' + str(seg[0]) + ' ' + str(seg[1]) + ' ' + 585 str(segment_tags[i]) + '\n') 586 587 # One line: <# of holes> 595 588 fd.write(str(len(holes)) + 596 " # <# of holes>, next lines <Hole #> <x> <y> ...Mesh Holes...\n")589 ' # <# of holes>, next lines <Hole #> <x> <y> ...Mesh Holes...\n') 597 590 # <x> <y> 598 591 for i,h in enumerate(holes): 599 fd.write(str(i) + " " 600 + str(h[0]) + " " 601 + str(h[1]) + "\n") 602 603 #One line: <# of regions> 592 fd.write(str(i) + ' ' + str(h[0]) + ' ' + str(h[1]) + '\n') 593 594 # One line: <# of regions> 604 595 fd.write(str(len(regions)) + 605 " # <# of regions>, next lines <Region #> <x> <y> <tag>"606 "...Mesh Regions...\n")596 ' # <# of regions>, next lines <Region #> <x> <y> <tag>' 597 '...Mesh Regions...\n') 607 598 608 599 # <index> <x> <y> <tag> 609 600 for i,r in enumerate(regions): 610 fd.write(str(i) + " " 611 + str(r[0]) + " " 612 + str(r[1])+ " " 613 + str(region_tags[i]) + "\n") 614 615 # <index> [<MaxArea>|""] 616 617 #One line: <# of regions> 601 fd.write(str(i) + ' ' + str(r[0]) + ' ' + str(r[1])+ ' ' + 602 str(region_tags[i]) + '\n') 603 604 # <index> [<MaxArea>|''] 605 606 # One line: <# of regions> 618 607 fd.write(str(len(regions)) + 619 " # <# of regions>, next lines <Region #> [Max Area] "620 "...Mesh Regions...\n")608 ' # <# of regions>, next lines <Region #> [Max Area] ' 609 '...Mesh Regions...\n') 621 610 for i,r in enumerate(regions): 622 611 area = str(region_max_areas[i]) 623 612 624 fd.write(str(i) + " " + area + "\n")613 fd.write(str(i) + ' ' + area + '\n') 625 614 626 615 # geo_reference info … … 649 638 # in more detail. 650 639 651 IntType = num. Int32640 IntType = num.int32 652 641 #IntType = Int 653 642 654 643 #the triangulation 655 mesh['vertices'] = num.array(mesh['vertices'], num. Float)644 mesh['vertices'] = num.array(mesh['vertices'], num.float) 656 645 if mesh['vertex_attributes'] != None: 657 646 mesh['vertex_attributes'] = \ 658 num.array(mesh['vertex_attributes'], num. Float)647 num.array(mesh['vertex_attributes'], num.float) 659 648 mesh['vertex_attribute_titles'] = \ 660 num.array(mesh['vertex_attribute_titles'], num. Character)649 num.array(mesh['vertex_attribute_titles'], num.character) 661 650 mesh['segments'] = num.array(mesh['segments'], IntType) 662 mesh['segment_tags'] = num.array(mesh['segment_tags'], num. Character)651 mesh['segment_tags'] = num.array(mesh['segment_tags'], num.character) 663 652 mesh['triangles'] = num.array(mesh['triangles'], IntType) 664 mesh['triangle_tags'] = num.array(mesh['triangle_tags']) #.astype(Character)653 mesh['triangle_tags'] = num.array(mesh['triangle_tags']) 665 654 mesh['triangle_neighbors'] = \ 666 655 num.array(mesh['triangle_neighbors'], IntType) 667 656 668 657 #the outline 669 mesh['points'] = num.array(mesh['points'], num. Float)670 mesh['point_attributes'] = num.array(mesh['point_attributes'], num. Float)658 mesh['points'] = num.array(mesh['points'], num.float) 659 mesh['point_attributes'] = num.array(mesh['point_attributes'], num.float) 671 660 mesh['outline_segments'] = num.array(mesh['outline_segments'], IntType) 672 661 mesh['outline_segment_tags'] = \ 673 num.array(mesh['outline_segment_tags'], num.Character) 674 mesh['holes'] = num.array(mesh['holes'], num.Float) 675 mesh['regions'] = num.array(mesh['regions'], num.Float) 676 mesh['region_tags'] = num.array(mesh['region_tags'], num.Character) 677 mesh['region_max_areas'] = num.array(mesh['region_max_areas'], num.Float) 678 679 #mesh = mesh_dict2array(mesh) 680 #print "new_mesh",new_mesh 681 #print "mesh",mesh 662 num.array(mesh['outline_segment_tags'], num.character) 663 mesh['holes'] = num.array(mesh['holes'], num.float) 664 mesh['regions'] = num.array(mesh['regions'], num.float) 665 mesh['region_tags'] = num.array(mesh['region_tags'], num.character) 666 mesh['region_max_areas'] = num.array(mesh['region_max_areas'], num.float) 682 667 683 668 # NetCDF file definition … … 686 671 except IOError: 687 672 msg = 'File %s could not be created' % file_name 688 raise msg673 raise Exception, msg 689 674 690 675 #Create new file 691 676 outfile.institution = 'Geoscience Australia' 692 outfile.description = 'NetCDF format for compact and portable storage ' + \677 outfile.description = 'NetCDF format for compact and portable storage ' + \ 693 678 'of spatial point data' 694 679 695 680 # dimension definitions - fixed 696 outfile.createDimension('num_of_dimensions', 2) #This is 2d data697 outfile.createDimension('num_of_segment_ends', 2) #Segs have two points681 outfile.createDimension('num_of_dimensions', 2) # This is 2d data 682 outfile.createDimension('num_of_segment_ends', 2) # Segs have two points 698 683 outfile.createDimension('num_of_triangle_vertices', 3) 699 684 outfile.createDimension('num_of_triangle_faces', 3) … … 706 691 if (mesh['vertices'].shape[0] > 0): 707 692 outfile.createDimension('num_of_vertices', mesh['vertices'].shape[0]) 708 outfile.createVariable('vertices', n um.Float, ('num_of_vertices',709 'num_of_dimensions'))693 outfile.createVariable('vertices', netcdf_float, ('num_of_vertices', 694 'num_of_dimensions')) 710 695 outfile.variables['vertices'][:] = mesh['vertices'] 711 if mesh['vertex_attributes'] != None \712 and (mesh['vertex_attributes'].shape[0] > 0 \713 and mesh['vertex_attributes'].shape[1] > 0):696 if (mesh['vertex_attributes'] != None and 697 (mesh['vertex_attributes'].shape[0] > 0 and 698 mesh['vertex_attributes'].shape[1] > 0)): 714 699 outfile.createDimension('num_of_vertex_attributes', 715 700 mesh['vertex_attributes'].shape[1]) … … 717 702 mesh['vertex_attribute_titles'].shape[1]) 718 703 outfile.createVariable('vertex_attributes', 719 n um.Float,704 netcdf_float, 720 705 ('num_of_vertices', 721 706 'num_of_vertex_attributes')) 722 707 outfile.createVariable('vertex_attribute_titles', 723 n um.Character,708 netcdf_char, 724 709 ('num_of_vertex_attributes', 725 710 'num_of_vertex_attribute_title_chars')) … … 732 717 if (mesh['segments'].shape[0] > 0): 733 718 outfile.createDimension('num_of_segments', mesh['segments'].shape[0]) 734 outfile.createVariable('segments', IntType,719 outfile.createVariable('segments', netcdf_int, 735 720 ('num_of_segments', 'num_of_segment_ends')) 736 721 outfile.variables['segments'][:] = mesh['segments'] 737 if (mesh['segment_tags'].shape[1] > 0):722 if mesh['segment_tags'].shape[1] > 0: 738 723 outfile.createDimension('num_of_segment_tag_chars', 739 724 mesh['segment_tags'].shape[1]) 740 725 outfile.createVariable('segment_tags', 741 n um.Character,726 netcdf_char, 742 727 ('num_of_segments', 743 728 'num_of_segment_tag_chars')) … … 747 732 if (mesh['triangles'].shape[0] > 0): 748 733 outfile.createDimension('num_of_triangles', mesh['triangles'].shape[0]) 749 outfile.createVariable('triangles', 750 IntType, 734 outfile.createVariable('triangles', netcdf_int, 751 735 ('num_of_triangles', 'num_of_triangle_vertices')) 752 outfile.createVariable('triangle_neighbors', 753 IntType, 736 outfile.createVariable('triangle_neighbors', netcdf_int, 754 737 ('num_of_triangles', 'num_of_triangle_faces')) 755 738 outfile.variables['triangles'][:] = mesh['triangles'] 756 739 outfile.variables['triangle_neighbors'][:] = mesh['triangle_neighbors'] 757 if mesh['triangle_tags'] != None \758 and (mesh['triangle_tags'].shape[1] > 0):740 if (mesh['triangle_tags'] != None and 741 (mesh['triangle_tags'].shape[1] > 0)): 759 742 outfile.createDimension('num_of_triangle_tag_chars', 760 743 mesh['triangle_tags'].shape[1]) 761 outfile.createVariable('triangle_tags', 762 num.Character, 744 outfile.createVariable('triangle_tags', netcdf_char, 763 745 ('num_of_triangles', 764 746 'num_of_triangle_tag_chars')) … … 769 751 if (mesh['points'].shape[0] > 0): 770 752 outfile.createDimension('num_of_points', mesh['points'].shape[0]) 771 outfile.createVariable('points', n um.Float, ('num_of_points',772 753 outfile.createVariable('points', netcdf_float, 754 ('num_of_points', 'num_of_dimensions')) 773 755 outfile.variables['points'][:] = mesh['points'] 774 756 if mesh['point_attributes'].shape[0] > 0 \ … … 776 758 outfile.createDimension('num_of_point_attributes', 777 759 mesh['point_attributes'].shape[1]) 778 outfile.createVariable('point_attributes', 779 num.Float, 760 outfile.createVariable('point_attributes', netcdf_float, 780 761 ('num_of_points', 'num_of_point_attributes')) 781 762 outfile.variables['point_attributes'][:] = mesh['point_attributes'] … … 785 766 outfile.createDimension('num_of_outline_segments', 786 767 mesh['outline_segments'].shape[0]) 787 outfile.createVariable('outline_segments', 788 IntType, 768 outfile.createVariable('outline_segments', netcdf_int, 789 769 ('num_of_outline_segments', 790 770 'num_of_segment_ends')) … … 793 773 outfile.createDimension('num_of_outline_segment_tag_chars', 794 774 mesh['outline_segment_tags'].shape[1]) 795 outfile.createVariable('outline_segment_tags', 796 num.Character, 775 outfile.createVariable('outline_segment_tags', netcdf_char, 797 776 ('num_of_outline_segments', 798 777 'num_of_outline_segment_tag_chars')) … … 803 782 if (mesh['holes'].shape[0] > 0): 804 783 outfile.createDimension('num_of_holes', mesh['holes'].shape[0]) 805 outfile.createVariable('holes', n um.Float, ('num_of_holes',806 784 outfile.createVariable('holes', netcdf_float, 785 ('num_of_holes', 'num_of_dimensions')) 807 786 outfile.variables['holes'][:] = mesh['holes'] 808 787 … … 810 789 if (mesh['regions'].shape[0] > 0): 811 790 outfile.createDimension('num_of_regions', mesh['regions'].shape[0]) 812 outfile.createVariable('regions', num.Float, ('num_of_regions', 813 'num_of_dimensions')) 814 outfile.createVariable('region_max_areas', num.Float, ('num_of_regions',)) 791 outfile.createVariable('regions', netcdf_float, 792 ('num_of_regions', 'num_of_dimensions')) 793 outfile.createVariable('region_max_areas', netcdf_float, 794 ('num_of_regions',)) 815 795 outfile.variables['regions'][:] = mesh['regions'] 816 796 outfile.variables['region_max_areas'][:] = mesh['region_max_areas'] … … 818 798 outfile.createDimension('num_of_region_tag_chars', 819 799 mesh['region_tags'].shape[1]) 820 outfile.createVariable('region_tags', n um.Character,800 outfile.createVariable('region_tags', netcdf_char, 821 801 ('num_of_regions', 822 802 'num_of_region_tag_chars')) … … 834 814 # @param file_name Path to the file to read. 835 815 # @return A dictionary containing the .msh file data. 816 # @note Throws IOError if file not found. 836 817 def _read_msh_file(file_name): 837 """ Read in an msh file. 838 """ 839 840 #Check contents 841 #Get NetCDF 842 # see if the file is there. Throw a QUIET IO error if it isn't 818 """ Read in an msh file.""" 819 820 #Check contents. Get NetCDF 843 821 fd = open(file_name, 'r') 844 822 fd.close() 845 823 846 # throws prints to screen if file not present824 # throws prints to screen if file not present 847 825 fid = NetCDFFile(file_name, netcdf_mode_r) 848 826 mesh = {} 849 827 850 # Get the variables 851 # the triangulation 828 # Get the variables - the triangulation 852 829 try: 853 830 mesh['vertices'] = fid.variables['vertices'][:] 854 831 except KeyError: 855 mesh['vertices'] = num.array([], num. Int) #array default#832 mesh['vertices'] = num.array([], num.int) #array default# 856 833 857 834 try: … … 859 836 except KeyError: 860 837 mesh['vertex_attributes'] = None 861 #for ob in mesh['vertices']:862 #mesh['vertex_attributes'].append([])863 838 864 839 mesh['vertex_attribute_titles'] = [] … … 873 848 mesh['segments'] = fid.variables['segments'][:] 874 849 except KeyError: 875 mesh['segments'] = num.array([], num. Int) #array default#850 mesh['segments'] = num.array([], num.int) #array default# 876 851 877 852 mesh['segment_tags'] =[] … … 888 863 mesh['triangle_neighbors'] = fid.variables['triangle_neighbors'][:] 889 864 except KeyError: 890 mesh['triangles'] = num.array([], num. Int)#array default#891 mesh['triangle_neighbors'] = num.array([], num. Int)#array default#892 893 mesh['triangle_tags'] = []865 mesh['triangles'] = num.array([], num.int) #array default# 866 mesh['triangle_neighbors'] = num.array([], num.int) #array default# 867 868 mesh['triangle_tags'] = [] 894 869 try: 895 870 tags = fid.variables['triangle_tags'][:] … … 916 891 mesh['outline_segments'] = fid.variables['outline_segments'][:] 917 892 except KeyError: 918 mesh['outline_segments'] = num.array([], num. Int) #array default#893 mesh['outline_segments'] = num.array([], num.int) #array default# 919 894 920 895 mesh['outline_segment_tags'] =[] … … 930 905 mesh['holes'] = fid.variables['holes'][:] 931 906 except KeyError: 932 mesh['holes'] = num.array([], num. Int)#array default#907 mesh['holes'] = num.array([], num.int) #array default# 933 908 934 909 try: 935 910 mesh['regions'] = fid.variables['regions'][:] 936 911 except KeyError: 937 mesh['regions'] = num.array([], num. Int)#array default#912 mesh['regions'] = num.array([], num.int) #array default# 938 913 939 914 mesh['region_tags'] =[] … … 949 924 mesh['region_max_areas'] = fid.variables['region_max_areas'][:] 950 925 except KeyError: 951 mesh['region_max_areas'] = num.array([], num.Int) #array default# 952 #mesh[''] = fid.variables[''][:] 926 mesh['region_max_areas'] = num.array([], num.int) #array default# 953 927 954 928 try: … … 972 946 # @note Used by alpha shapes 973 947 def export_boundary_file(file_name, points, title, delimiter=','): 974 """ 975 export a file, ofile, with the format 976 948 """Export a boundary file. 949 950 Format: 977 951 First line: Title variable 978 952 Following lines: [point index][delimiter][point index] … … 985 959 fd = open(file_name, 'w') 986 960 987 fd.write(title + "\n")988 989 # [point index][delimiter][point index]961 fd.write(title + '\n') 962 963 # [point index][delimiter][point index] 990 964 for point in points: 991 fd.write(str(point[0]) + delimiter + str(point[1]) + "\n")965 fd.write(str(point[0]) + delimiter + str(point[1]) + '\n') 992 966 993 967 fd.close() 994 968 995 969 996 ### 970 ################################################################################ 997 971 # IMPORT/EXPORT POINTS FILES 998 ### 972 ################################################################################ 999 973 1000 974 ## … … 1002 976 # @param point_atts 1003 977 def extent_point_atts(point_atts): 978 """Returns 4 points representing the extent 979 This loses attribute info. 1004 980 """ 1005 Returns 4 points representing the extent 1006 This losses attribute info. 1007 """ 981 1008 982 point_atts['pointlist'] = extent(point_atts['pointlist']) 1009 983 point_atts['attributelist'] = {} … … 1018 992 # [max_x, max_y], [min_x, max_y]] 1019 993 def extent(points): 1020 points = num.array(points, num. Float)994 points = num.array(points, num.float) 1021 995 1022 996 max_x = min_x = points[0][0] … … 1025 999 for point in points[1:]: 1026 1000 x = point[0] 1027 if x > max_x: max_x = x 1028 if x < min_x: min_x = x 1001 if x > max_x: 1002 max_x = x 1003 if x < min_x: 1004 min_x = x 1029 1005 1030 1006 y = point[1] 1031 if y > max_y: max_y = y 1032 if y < min_y: min_y = y 1007 if y > max_y: 1008 max_y = y 1009 if y < min_y: 1010 min_y = y 1033 1011 1034 1012 extent = num.array([[min_x, min_y], … … 1047 1025 # @param verbose True if this function is to be verbose. 1048 1026 def reduce_pts(infile, outfile, max_points, verbose = False): 1049 """ 1050 reduces a points file by removing every second point until the # of points 1027 """Reduce a points file until less than given size. 1028 1029 Reduces a points file by removing every second point until the # of points 1051 1030 is less than max_points. 1052 1031 """ … … 1091 1070 ## 1092 1071 # @brief 1093 # @param point_atts Object with attribute of 'point slist'.1072 # @param point_atts Object with attribute of 'pointlist'. 1094 1073 # @return 1095 1074 def point_atts2array(point_atts): 1096 1075 # convert attribute list to array of floats 1097 point_atts['pointlist'] = num.array(point_atts['pointlist'], num. Float)1076 point_atts['pointlist'] = num.array(point_atts['pointlist'], num.float) 1098 1077 1099 1078 for key in point_atts['attributelist'].keys(): 1100 1079 point_atts['attributelist'][key] = \ 1101 num.array(point_atts['attributelist'][key], num. Float)1080 num.array(point_atts['attributelist'][key], num.float) 1102 1081 1103 1082 return point_atts … … 1127 1106 """ 1128 1107 1129 point_attributes = num.array([], num. Float)1108 point_attributes = num.array([], num.float) 1130 1109 keys = dic.keys() 1131 1110 key = keys.pop(0) 1132 point_attributes = num.reshape(dic[key], (dic[key].shape[0],1))1111 point_attributes = num.reshape(dic[key], (dic[key].shape[0], 1)) 1133 1112 for key in keys: 1134 #point_attributes = concatenate([point_attributes, dic[key]], axis=1) 1135 reshaped = num.reshape(dic[key],(dic[key].shape[0],1)) 1113 reshaped = num.reshape(dic[key], (dic[key].shape[0], 1)) 1136 1114 point_attributes = num.concatenate([point_attributes, reshaped], axis=1) 1137 1115 … … 1144 1122 # @param indices_to_keep 1145 1123 # @return 1146 # FIXME(dsg), turn this dict plus methods into a class?1124 # @note FIXME(dsg), turn this dict plus methods into a class? 1147 1125 def take_points(dict, indices_to_keep): 1148 1126 dict = point_atts2array(dict) 1149 #FIXME maybe the points data structure should become a class? 1150 dict['pointlist'] = num.take(dict['pointlist'],indices_to_keep) 1127 dict['pointlist'] = num.take(dict['pointlist'], indices_to_keep) 1151 1128 1152 1129 for key in dict['attributelist'].keys(): 1153 dict['attributelist'][key] = num.take(dict['attributelist'][key],1154 indices_to_keep)1130 dict['attributelist'][key] = num.take(dict['attributelist'][key], 1131 indices_to_keep) 1155 1132 1156 1133 return dict … … 1161 1138 # @param dict2 ?? 1162 1139 # @return ?? 1163 def add_point_dictionaries 1140 def add_point_dictionaries(dict1, dict2): 1164 1141 """ 1165 1142 """ … … 1170 1147 combined = {} 1171 1148 combined['pointlist'] = num.concatenate((dict2['pointlist'], 1172 dict1['pointlist']), axis=0)1149 dict1['pointlist']), axis=0) 1173 1150 1174 1151 atts = {} … … 1176 1153 atts[key]= num.concatenate((dict2['attributelist'][key], 1177 1154 dict1['attributelist'][key]), axis=0) 1178 combined['attributelist'] =atts1155 combined['attributelist'] = atts 1179 1156 combined['geo_reference'] = dict1['geo_reference'] 1180 1157 -
branches/numpy/anuga/load_mesh/test_loadASCII.py
r6154 r6304 1 1 #!/usr/bin/env python 2 #3 2 4 3 import tempfile … … 10 9 from os.path import splitext 11 10 12 import Numericas num11 import numpy as num 13 12 14 13 from anuga.load_mesh.loadASCII import * 15 14 from anuga.coordinate_transforms.geo_reference import Geo_reference 16 15 import loadASCII 16 17 17 18 18 class loadASCIITestCase(unittest.TestCase): … … 25 25 self.dict['regions'] = [(0.3, 0.3),(0.3, 0.4)] 26 26 self.dict['region_tags'] = ['1.3', 'yeah'] 27 self.dict['region_max_areas'] = [36.0, -7.1]27 self.dict['region_max_areas'] = [36.0, -7.1] 28 28 self.dict['points'] = [(0.0, 0.0), (0.0, 4.0), (4.0, 0.0), (1.0, 1.0)] 29 29 self.dict['vertices'] = [(0.0, 0.0), (0.0, 4.0), … … 35 35 self.dict['triangle_tags'] = ['1.3', '1.3', 36 36 '1.3', '1.3'] 37 self.dict['vertex_attributes'] = [[1.2, 2.], [1.2,2.],38 [1.2, 2.], [1.2,2.], [1.2,3.]]37 self.dict['vertex_attributes'] = [[1.2, 2.], [1.2, 2.], 38 [1.2, 2.], [1.2, 2.], [1.2, 3.]] 39 39 self.dict['triangle_neighbors'] = [[-1, 2, 3], [3, 2, -1], 40 40 [-1, 1, 0], [1, -1, 0]] 41 41 self.dict['segment_tags'] = ['50', '40', '30', '20', '40'] 42 42 self.dict['vertex_attribute_titles'] = ['bed elevation', 'height'] 43 self.dict['geo_reference'] = Geo_reference(56, 1.9,1.9)43 self.dict['geo_reference'] = Geo_reference(56, 1.9, 1.9) 44 44 45 45 self.sparse_dict ={} … … 47 47 self.sparse_dict['outline_segment_tags'] = [] 48 48 self.sparse_dict['holes'] = [] 49 self.sparse_dict['points'] = [(0.0, 0.0), (9,8)]50 self.sparse_dict['point_attributes'] = [[], []] # points don't have to have51 #attributes49 self.sparse_dict['points'] = [(0.0, 0.0), (9, 8)] 50 self.sparse_dict['point_attributes'] = [[], []] # points don't have to 51 # have attributes 52 52 self.sparse_dict['regions'] = [] 53 53 self.sparse_dict['region_tags'] = [] … … 82 82 83 83 self.tri_dict ={} 84 self.tri_dict['outline_segments'] = [[0, 1]]84 self.tri_dict['outline_segments'] = [[0, 1]] 85 85 self.tri_dict['outline_segment_tags'] = [''] 86 86 self.tri_dict['holes'] = [] 87 self.tri_dict['points'] = [(9, 8),(7,8)]87 self.tri_dict['points'] = [(9, 8), (7, 8)] 88 88 self.tri_dict['point_attributes'] = [[],[]] 89 89 self.tri_dict['regions'] = [] 90 90 self.tri_dict['region_tags'] = [] 91 91 self.tri_dict['region_max_areas'] = [] 92 self.tri_dict['vertices'] = [[9, 8],[7,8], [4,5]]93 self.tri_dict['triangles'] = [[0, 1,2]]94 self.tri_dict['segments'] = [[0, 1]]92 self.tri_dict['vertices'] = [[9, 8], [7, 8], [4, 5]] 93 self.tri_dict['triangles'] = [[0, 1, 2]] 94 self.tri_dict['segments'] = [[0, 1]] 95 95 self.tri_dict['triangle_tags'] = [''] 96 96 self.tri_dict['vertex_attributes'] = None 97 self.tri_dict['triangle_neighbors'] = [[0, 0,0]]97 self.tri_dict['triangle_neighbors'] = [[0, 0, 0]] 98 98 self.tri_dict['segment_tags'] = [''] 99 99 self.tri_dict['vertex_attribute_titles'] = [] 100 100 101 101 self.seg_dict ={} 102 self.seg_dict['outline_segments'] = [[0, 1]]102 self.seg_dict['outline_segments'] = [[0, 1]] 103 103 self.seg_dict['outline_segment_tags'] = [''] 104 104 self.seg_dict['holes'] = [] 105 self.seg_dict['points'] = [(9, 8),(7,8)]106 self.seg_dict['point_attributes'] = [[], []]107 self.seg_dict['regions'] = [(5, 4)]105 self.seg_dict['points'] = [(9, 8), (7, 8)] 106 self.seg_dict['point_attributes'] = [[], []] 107 self.seg_dict['regions'] = [(5, 4)] 108 108 self.seg_dict['region_tags'] = [''] 109 109 self.seg_dict['region_max_areas'] = [-999] 110 self.seg_dict['vertices'] = [(9, 8),(7,8)]110 self.seg_dict['vertices'] = [(9, 8), (7, 8)] 111 111 self.seg_dict['triangles'] = [] 112 self.seg_dict['segments'] = [[0, 1]]112 self.seg_dict['segments'] = [[0, 1]] 113 113 self.seg_dict['triangle_tags'] = [] 114 114 self.seg_dict['vertex_attributes'] = None … … 118 118 119 119 self.reg_dict ={} 120 self.reg_dict['outline_segments'] = [[0, 1]]120 self.reg_dict['outline_segments'] = [[0, 1]] 121 121 self.reg_dict['outline_segment_tags'] = [''] 122 122 self.reg_dict['holes'] = [] 123 self.reg_dict['points'] = [(9, 8),(7,8)]124 self.reg_dict['point_attributes'] = [[], []]125 self.reg_dict['regions'] = [(5, 4)]123 self.reg_dict['points'] = [(9, 8), (7, 8)] 124 self.reg_dict['point_attributes'] = [[], []] 125 self.reg_dict['regions'] = [(5, 4)] 126 126 self.reg_dict['region_tags'] = [''] 127 127 self.reg_dict['region_max_areas'] = [] 128 self.reg_dict['vertices'] = [(9, 8),(7,8)]128 self.reg_dict['vertices'] = [(9, 8), (7, 8)] 129 129 self.reg_dict['triangles'] = [] 130 self.reg_dict['segments'] = [[0, 1]]130 self.reg_dict['segments'] = [[0, 1]] 131 131 self.reg_dict['triangle_tags'] = [] 132 self.reg_dict['vertex_attributes'] = [[], []]132 self.reg_dict['vertex_attributes'] = [[], []] 133 133 self.reg_dict['triangle_neighbors'] = [] 134 134 self.reg_dict['segment_tags'] = [''] … … 136 136 137 137 self.triangle_tags_dict ={} 138 self.triangle_tags_dict['outline_segments'] = [(0, 1), (1, 2), (0, 2), (0, 3)] 139 self.triangle_tags_dict['outline_segment_tags'] = ['50', '40', '30', '20'] 138 self.triangle_tags_dict['outline_segments'] = [(0, 1), (1, 2), 139 (0, 2), (0, 3)] 140 self.triangle_tags_dict['outline_segment_tags'] = ['50', '40', 141 '30', '20'] 140 142 self.triangle_tags_dict['holes'] = [(0.2, 0.6)] 141 self.triangle_tags_dict['point_attributes'] = [[5, 2], [4, 2], [3, 2], [2,2]] 143 self.triangle_tags_dict['point_attributes'] = [[5, 2], [4, 2], 144 [3, 2], [2,2]] 142 145 self.triangle_tags_dict['regions'] = [(0.3, 0.3),(0.3, 0.4)] 143 146 self.triangle_tags_dict['region_tags'] = ['1.3', 'yeah'] 144 self.triangle_tags_dict['region_max_areas'] = [36.0,-7.1] 145 self.triangle_tags_dict['points'] = [(0.0, 0.0), (0.0, 4.0), (4.0, 0.0), (1.0, 1.0)] 147 self.triangle_tags_dict['region_max_areas'] = [36.0, -7.1] 148 self.triangle_tags_dict['points'] = [(0.0, 0.0), (0.0, 4.0), 149 (4.0, 0.0), (1.0, 1.0)] 146 150 self.triangle_tags_dict['vertices'] = [(0.0, 0.0), (0.0, 4.0), 147 (4.0, 0.0), (1.0, 1.0), (2.0, 2.0)] 151 (4.0, 0.0), (1.0, 1.0), 152 (2.0, 2.0)] 148 153 self.triangle_tags_dict['triangles'] = [(3, 2, 4), (1, 0, 3), 149 (3, 4,1), (2, 3, 0)]154 (3, 4,1), (2, 3, 0)] 150 155 self.triangle_tags_dict['segments'] = [(0, 1), (1, 4), (2, 0), 151 (0, 3), (4, 2)] 152 self.triangle_tags_dict['triangle_tags'] = ['yeah', '1.3', 153 '1.3', ''] 156 (0, 3), (4, 2)] 157 self.triangle_tags_dict['triangle_tags'] = ['yeah', '1.3', '1.3', ''] 154 158 self.triangle_tags_dict['vertex_attributes'] = [[1.2,2.], [1.2,2.], 155 [1.2,2.], [1.2,2.], [1.2,3.]] 159 [1.2,2.], [1.2,2.], 160 [1.2,3.]] 156 161 self.triangle_tags_dict['triangle_neighbors'] = [[-1, 2, 3], [3, 2, -1], 157 [-1, 1, 0], [1, -1, 0]]162 [-1, 1, 0], [1, -1, 0]] 158 163 self.triangle_tags_dict['segment_tags'] = ['50', '40', '30', '20', '40'] 159 self.triangle_tags_dict['vertex_attribute_titles'] = ['bed elevation', 'height'] 160 self.triangle_tags_dict['geo_reference'] = Geo_reference(56,1.9,1.9) 164 self.triangle_tags_dict['vertex_attribute_titles'] = ['bed elevation', 165 'height'] 166 self.triangle_tags_dict['geo_reference'] = Geo_reference(56, 1.9, 1.9) 161 167 162 168 def tearDown(self): … … 169 175 170 176 meshDict = self.dict 171 fileName = tempfile.mktemp( ".tsh")177 fileName = tempfile.mktemp('.tsh') 172 178 export_mesh_file(fileName, meshDict) 173 179 loadedDict = import_mesh_file(fileName) 174 180 175 #print "*(*( meshDict" 176 #print meshDict 177 #print "*(*( loadedDcit" 178 #print loadedDict 179 #print "*(*(" 180 181 self.failUnless(num.alltrue(num.array(meshDict['vertices']) == 181 self.failUnless(num.alltrue(num.array(meshDict['vertices']) == 182 182 num.array(loadedDict['vertices'])), 183 183 'test_export_mesh_file failed. Test 1') 184 self.failUnless(num.alltrue(num.array(meshDict['triangles']) 184 self.failUnless(num.alltrue(num.array(meshDict['triangles']) == 185 185 num.array(loadedDict['triangles'])), 186 186 'test_export_mesh_file failed. Test 2') 187 self.failUnless(num.alltrue(num.array(meshDict['segments']) 187 self.failUnless(num.alltrue(num.array(meshDict['segments']) == 188 188 num.array(loadedDict['segments'])), 189 189 'test_export_mesh_file failed. Test 3') 190 self.failUnless(num.alltrue(num.array(meshDict['triangle_tags']) 190 self.failUnless(num.alltrue(num.array(meshDict['triangle_tags']) == 191 191 num.array(loadedDict['triangle_tags'])), 192 192 'test_export_mesh_file failed. Test 4') 193 193 194 self.failUnless(meshDict['vertex_attributes'] 194 self.failUnless(meshDict['vertex_attributes'] == 195 195 loadedDict['vertex_attributes'], 196 196 'test_export_mesh_file failed. Test 5') 197 self.failUnless(num.alltrue(num.array(meshDict['triangle_neighbors']) 197 self.failUnless(num.alltrue(num.array(meshDict['triangle_neighbors']) == 198 198 num.array(loadedDict['triangle_neighbors'])), 199 199 'test_export_mesh_file failed. Test 6') 200 self.failUnless(num.alltrue(num.array(meshDict['segment_tags']) 200 self.failUnless(num.alltrue(num.array(meshDict['segment_tags']) == 201 201 num.array(loadedDict['segment_tags'])), 202 202 'test_export_mesh_file failed. Test 7') 203 self.failUnless(num.alltrue(num.array(meshDict['vertex_attribute_titles']) 203 self.failUnless(num.alltrue(num.array(meshDict['vertex_attribute_titles']) == 204 204 num.array(loadedDict['vertex_attribute_titles'])), 205 205 'test_export_mesh_file failed. Test 8') 206 self.failUnless(num.alltrue(num.array(meshDict['geo_reference']) 206 self.failUnless(num.alltrue(num.array(meshDict['geo_reference']) == 207 207 num.array(loadedDict['geo_reference'])), 208 208 'test_export_mesh_file failed. Test 9') … … 212 212 def test_read_write_tsh_file(self): 213 213 dict = self.dict.copy() 214 fileName = tempfile.mktemp( ".tsh")215 export_mesh_file(fileName, dict)214 fileName = tempfile.mktemp('.tsh') 215 export_mesh_file(fileName, dict) 216 216 loaded_dict = import_mesh_file(fileName) 217 217 os.remove(fileName) 218 218 dict = self.dict 219 #print "*********************" 220 #print dict 221 #print "**loaded_dict*******************" 222 #print loaded_dict 223 #print "*********************" 224 self.check_mesh_dicts(loaded_dict,dict, 'test_read_write_msh_file') 219 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file') 225 220 226 221 def test_read_write_tsh_fileII(self): 227 222 dict = self.sparse_dict.copy() 228 fileName = tempfile.mktemp( ".tsh")229 export_mesh_file(fileName, dict)223 fileName = tempfile.mktemp('.tsh') 224 export_mesh_file(fileName, dict) 230 225 loaded_dict = import_mesh_file(fileName) 231 226 dict = self.sparse_dict 232 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file')227 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file') 233 228 os.remove(fileName) 234 229 235 230 def test_read_write_tsh_fileIII(self): 236 231 dict = self.blank_dict.copy() 237 fileName = tempfile.mktemp( ".tsh")238 export_mesh_file(fileName, dict)232 fileName = tempfile.mktemp('.tsh') 233 export_mesh_file(fileName, dict) 239 234 loaded_dict = import_mesh_file(fileName) 240 235 os.remove(fileName) … … 245 240 #print loaded_dict 246 241 #print "*********************" 247 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileIII')242 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileIII') 248 243 249 244 def test_read_write_tsh_file4(self): 250 245 dict = self.seg_dict.copy() 251 fileName = tempfile.mktemp( ".tsh")252 export_mesh_file(fileName, dict)246 fileName = tempfile.mktemp('.tsh') 247 export_mesh_file(fileName, dict) 253 248 loaded_dict = import_mesh_file(fileName) 254 249 os.remove(fileName) 255 250 dict = self.seg_dict 256 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file4')251 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file4') 257 252 258 253 def test_read_write_tsh_file5(self): 259 254 dict = self.triangle_tags_dict.copy() 260 fileName = tempfile.mktemp( ".tsh")261 export_mesh_file(fileName, dict)255 fileName = tempfile.mktemp('.tsh') 256 export_mesh_file(fileName, dict) 262 257 loaded_dict = import_mesh_file(fileName) 263 258 dict = self.triangle_tags_dict … … 267 262 #print loaded_dict 268 263 #print "*********************" 269 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file5')264 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file5') 270 265 os.remove(fileName) 271 266 272 267 def test_read_write_tsh_file6(self): 273 268 dict = self.tri_dict.copy() 274 fileName = tempfile.mktemp( ".tsh")275 export_mesh_file(fileName, dict)269 fileName = tempfile.mktemp('.tsh') 270 export_mesh_file(fileName, dict) 276 271 loaded_dict = import_mesh_file(fileName) 277 272 dict = self.tri_dict 278 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file6')273 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file6') 279 274 os.remove(fileName) 280 275 … … 285 280 import tempfile 286 281 287 fileName = tempfile.mktemp(".tsh") 288 #print fileName 282 fileName = tempfile.mktemp('.tsh') 289 283 try: 290 284 dict = import_mesh_file(fileName) … … 292 286 pass 293 287 else: 294 self.failUnless(0 ==1, 295 'imaginary file did not raise error!') 288 self.failUnless(0 == 1, 'imaginary file did not raise error!') 296 289 297 290 def test_read_write_tsh_file_bad(self): 298 291 dict = self.tri_dict.copy() 299 fileName = tempfile.mktemp( ".xxx")300 try: 301 export_mesh_file(fileName, dict)292 fileName = tempfile.mktemp('.xxx') 293 try: 294 export_mesh_file(fileName, dict) 302 295 except IOError: 303 296 pass 304 297 else: 305 self.failUnless(0 ==1, 306 'bad tsh file did not raise error!') 298 self.failUnless(0 == 1, 'bad tsh file did not raise error!') 307 299 308 300 def test_import_tsh_bad(self): … … 310 302 import tempfile 311 303 312 fileName = tempfile.mktemp( ".tsh")313 file = open(fileName, "w")304 fileName = tempfile.mktemp('.tsh') 305 file = open(fileName, 'w') 314 306 # this is a bad tsh file 315 file.write( "elevn\n\307 file.write('elevn\n\ 316 308 1.0 what \n\ 317 309 0.0 the \n\ 318 1.0 !!! \n ")310 1.0 !!! \n') 319 311 file.close() 320 312 #print fileName … … 324 316 pass 325 317 else: 326 self.failUnless(0 ==1, 327 'bad tsh file did not raise error!') 318 self.failUnless(0 == 1, 'bad tsh file did not raise error!') 328 319 os.remove(fileName) 329 320 … … 332 323 import tempfile 333 324 334 fileName = tempfile.mktemp( ".tsh")335 file = open(fileName, "w")336 file.write( "1.0 \n\325 fileName = tempfile.mktemp('.tsh') 326 file = open(fileName, 'w') 327 file.write('1.0 \n\ 337 328 showme1.0 0.0 10.0 \n\ 338 329 0.0 1.0\n\ 339 13.0 \n ")330 13.0 \n') 340 331 file.close() 341 #print fileName342 332 try: 343 333 dict = import_mesh_file(fileName) … … 345 335 pass 346 336 else: 347 self.failUnless(0 ==1, 348 'bad tsh file did not raise error!') 337 self.failUnless(0 == 1, 'bad tsh file did not raise error!') 349 338 350 339 os.remove(fileName) … … 355 344 def test_read_write_msh_file(self): 356 345 dict = self.dict.copy() 357 fileName = tempfile.mktemp( ".msh")358 export_mesh_file(fileName, dict)346 fileName = tempfile.mktemp('.msh') 347 export_mesh_file(fileName, dict) 359 348 loaded_dict = loadASCII._read_msh_file(fileName) 360 349 os.remove(fileName) … … 365 354 #print loaded_dict 366 355 #print "*********************" 367 self.check_mesh_dicts(loaded_dict, dict,'test_read_write_msh_file')356 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file') 368 357 369 358 def test_read_write_msh_fileII(self): 370 359 dict = self.sparse_dict.copy() 371 fileName = tempfile.mktemp( ".msh")372 export_mesh_file(fileName, dict)360 fileName = tempfile.mktemp('.msh') 361 export_mesh_file(fileName, dict) 373 362 loaded_dict = loadASCII._read_msh_file(fileName) 374 363 os.remove(fileName) … … 379 368 #print loaded_dict 380 369 #print "*********************" 381 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileII')370 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileII') 382 371 383 372 def test_read_write_msh_fileIII(self): 384 373 dict = self.blank_dict.copy() 385 fileName = tempfile.mktemp( ".msh")386 export_mesh_file(fileName, dict)374 fileName = tempfile.mktemp('.msh') 375 export_mesh_file(fileName, dict) 387 376 loaded_dict = loadASCII._read_msh_file(fileName) 388 377 os.remove(fileName) … … 393 382 #print loaded_dict 394 383 #print "*********************" 395 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileIII')384 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileIII') 396 385 397 386 def test_read_write_msh_file4(self): 398 387 dict = self.seg_dict.copy() 399 fileName = tempfile.mktemp( ".msh")400 export_mesh_file(fileName, dict)388 fileName = tempfile.mktemp('.msh') 389 export_mesh_file(fileName, dict) 401 390 loaded_dict = loadASCII._read_msh_file(fileName) 402 391 os.remove(fileName) … … 407 396 #print loaded_dict 408 397 #print "*********************" 409 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileIII')398 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file4') 410 399 411 400 def test_read_write_msh_file5(self): 412 401 dict = self.triangle_tags_dict.copy() 413 fileName = tempfile.mktemp( ".msh")414 export_mesh_file(fileName, dict)402 fileName = tempfile.mktemp('.msh') 403 export_mesh_file(fileName, dict) 415 404 loaded_dict = loadASCII._read_msh_file(fileName) 416 405 os.remove(fileName) … … 421 410 #print loaded_dict 422 411 #print "*********************" 423 self.check_mesh_dicts(loaded_dict,dict, 'test_read_write_msh_fileIII') 424 412 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file5') 425 413 426 414 def test_read_write_msh_file6(self): 427 415 dict = self.tri_dict.copy() 428 fileName = tempfile.mktemp( ".msh")429 export_mesh_file(fileName, dict)416 fileName = tempfile.mktemp('.msh') 417 export_mesh_file(fileName, dict) 430 418 loaded_dict = loadASCII._read_msh_file(fileName) 431 419 os.remove(fileName) 432 420 dict = self.tri_dict 433 #print "*********************"434 #print dict435 #print "**loaded_dict*******************"436 #print loaded_dict437 #print "*********************"438 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileIII')421 print "*********************" 422 print dict 423 print "**loaded_dict*******************" 424 print loaded_dict 425 print "*********************" 426 self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file6') 439 427 440 def check_mesh_dicts(self, loaded_dict, dict, fail_string 428 def check_mesh_dicts(self, loaded_dict, dict, fail_string): 441 429 assert num.allclose(num.array(loaded_dict['points']), 442 430 num.array(dict['points'])) 443 444 assert num.allclose(num.array(loaded_dict['point_attributes']), 431 assert num.allclose(num.array(loaded_dict['point_attributes']), 445 432 num.array(dict['point_attributes'])) 446 433 assert num.allclose(num.array(loaded_dict['outline_segments']), 447 434 num.array(dict['outline_segments'])) 448 435 449 self.failUnless(loaded_dict['outline_segment_tags'] 436 self.failUnless(loaded_dict['outline_segment_tags'] == 450 437 dict['outline_segment_tags'], 451 438 fail_string + ' failed!! Test 4') 452 453 439 454 440 assert num.allclose(num.array(loaded_dict['regions']), 455 441 num.array(dict['regions'])) 456 442 457 self.failUnless(loaded_dict['region_tags'] == 458 dict['region_tags'], 443 self.failUnless(loaded_dict['region_tags'] == dict['region_tags'], 459 444 fail_string + ' failed!! Test 5') 460 445 … … 473 458 assert num.allclose(num.array(dict['segments']), 474 459 num.array(loaded_dict['segments'])) 460 475 461 for ob, ldob in map(None,dict['triangle_tags'], 476 462 loaded_dict['triangle_tags']): 477 463 self.failUnless(ob == ldob, 478 fail_string + ' failed!! Test triangle_tags') 464 fail_string + ' failed!! Test triangle_tags') 465 479 466 # A bit hacky 480 self.failUnless((loaded_dict['vertex_attributes'] 481 dict['vertex_attributes']) or \482 (loaded_dict['vertex_attributes'] 467 self.failUnless((loaded_dict['vertex_attributes'] == 468 dict['vertex_attributes']) or \ 469 (loaded_dict['vertex_attributes'] == None and \ 483 470 dict['vertex_attributes'] == []), 484 471 fail_string + ' failed!! Test vertex_attributes') … … 489 476 for seg, ldseg in map(None,dict['segment_tags'], 490 477 loaded_dict['segment_tags']): 491 self.failUnless(seg 492 fail_string + ' failed!! Test 8')478 self.failUnless(seg == ldseg, 479 fail_string + ' failed!! Test 8') 493 480 try: 494 481 assert num.allclose(num.array(dict['vertex_attribute_titles']), 495 482 num.array(loaded_dict['vertex_attribute_titles'])) 496 483 except TypeError: 497 self.failUnless(num.alltrue(num.array(loaded_dict['vertex_attribute_titles']) == num.array(dict['vertex_attribute_titles'])), 484 self.failUnless(num.alltrue(num.array(loaded_dict['vertex_attribute_titles']) == 485 num.array(dict['vertex_attribute_titles'])), 498 486 fail_string + ' failed!! Test 8') 499 487 try: 500 self.failUnless(loaded_dict['geo_reference'] 501 dict['geo_reference'],502 fail_string + ' failed!! Test geo_reference')488 self.failUnless(loaded_dict['geo_reference'] == 489 dict['geo_reference'], 490 fail_string + ' failed!! Test geo_reference') 503 491 except KeyError: 504 492 self.failUnless(not dict.has_key('geo_reference' and 505 loaded_dict['geo_reference'] == None),506 fail_string + ' failed!! Test geo_reference')493 loaded_dict['geo_reference'] == None), 494 fail_string + ' failed!! Test geo_reference') 507 495 508 496 ########################## BAD .MSH ########################## … … 512 500 import tempfile 513 501 514 fileName = tempfile.mktemp(".msh") 515 #print fileName 502 fileName = tempfile.mktemp('.msh') 516 503 try: 517 504 dict = import_mesh_file(fileName) … … 519 506 pass 520 507 else: 521 self.failUnless(0 ==1, 522 'imaginary file did not raise error!') 508 self.failUnless(0 == 1, 'imaginary file did not raise error!') 523 509 524 510 def throws_error_2_screen_test_import_mesh_bad(self): … … 526 512 import tempfile 527 513 528 fileName = tempfile.mktemp( ".msh")529 file = open(fileName, "w")530 # 531 file.write( "elevn\n\514 fileName = tempfile.mktemp('.msh') 515 file = open(fileName, 'w') 516 # this is a bad tsh file 517 file.write('elevn\n\ 532 518 1.0 what \n\ 533 519 0.0 the \n\ 534 1.0 !!! \n ")520 1.0 !!! \n') 535 521 file.close() 536 #print fileName537 522 try: 538 523 dict = import_mesh_file(fileName) … … 540 525 pass 541 526 else: 542 self.failUnless(0 ==1, 543 'bad msh file did not raise error!') 527 self.failUnless(0 == 1, 'bad msh file did not raise error!') 544 528 os.remove(fileName) 545 529 546 ######547 # Test the clean_line() utility function.548 ######549 550 def test_clean_line_01(self):551 test_line = 'abc, ,,xyz,123'552 result = clean_line(test_line, ',')553 self.failUnless(result == ['abc', '', 'xyz', '123'])554 555 def test_clean_line_02(self):556 test_line = ' abc , ,, xyz , 123 '557 result = clean_line(test_line, ',')558 self.failUnless(result == ['abc', '', 'xyz', '123'])559 560 def test_clean_line_03(self):561 test_line = '1||||2'562 result = clean_line(test_line, '|')563 self.failUnless(result == ['1', '2'])564 565 530 #------------------------------------------------------------- 566 if __name__ == "__main__":531 if __name__ == '__main__': 567 532 568 533 suite = unittest.makeSuite(loadASCIITestCase,'test') 569 #suite = unittest.makeSuite(loadASCIITestCase,'test_read_write_tsh_file4')570 534 runner = unittest.TextTestRunner() #verbosity=2) 571 535 runner.run(suite) -
branches/numpy/anuga/mesh_engine/mesh_engine.py
r6155 r6304 11 11 #import anuga.mesh_engine.list_dic as triang 12 12 13 import Numericas num13 import numpy as num 14 14 15 15 from anuga.utilities.numerical_tools import ensure_numeric … … 46 46 47 47 try: 48 points = ensure_numeric(points, num. Float)48 points = ensure_numeric(points, num.float) 49 49 except ValueError: 50 50 msg = 'ERROR: Inconsistent points array.' … … 60 60 61 61 try: 62 # If Int is used, instead of Int32, it fails in Linux63 segments = ensure_numeric(segments, num. Int32)62 # If int is used, instead of int32, it fails in Linux 63 segments = ensure_numeric(segments, num.int32) 64 64 65 65 except ValueError: … … 72 72 73 73 try: 74 holes = ensure_numeric(holes, num. Float)74 holes = ensure_numeric(holes, num.float) 75 75 except ValueError: 76 76 msg = 'ERROR: Inconsistent holess array.' … … 80 80 regions = add_area_tag(regions) 81 81 try: 82 regions = ensure_numeric(regions, num. Float)82 regions = ensure_numeric(regions, num.float) 83 83 except (ValueError, TypeError): 84 84 msg = 'ERROR: Inconsistent regions array.' … … 90 90 91 91 try: 92 pointatts = ensure_numeric(pointatts, num. Float)92 pointatts = ensure_numeric(pointatts, num.float) 93 93 except (ValueError, TypeError): 94 94 msg = 'ERROR: Inconsistent point attributes array.' … … 103 103 104 104 try: 105 segatts = ensure_numeric(segatts, num. Int32)105 segatts = ensure_numeric(segatts, num.int32) 106 106 except ValueError: 107 107 msg = 'ERROR: Inconsistent point attributes array.' -
branches/numpy/anuga/mesh_engine/mesh_engine_c_layer.c
r4917 r6304 8 8 9 9 This code interfaces pmesh directly with "triangle", a general 10 purpose triangulation code. In doing so, Python Numeric data structures10 purpose triangulation code. In doing so, Python numeric data structures 11 11 are passed to C for use by "triangle" and the results are then 12 12 converted back. This was accomplished using the Python/C API. … … 64 64 #define PY_ARRAY_UNIQUE_SYMBOL API_YEAH 65 65 //#define NO_IMPORT_ARRAY 66 #include " Numeric/arrayobject.h"66 #include "numpy/arrayobject.h" 67 67 #include <sys/types.h> 68 68 … … 245 245 abs quantity_ext.c compute_gradients 246 246 247 PyArray_FromDims allolws you to create a Numeric array with unitialized data.247 PyArray_FromDims allolws you to create a numeric array with unitialized data. 248 248 The first argument is the size of the second argument ( 249 249 the dimensions array). … … 351 351 352 352 353 /* These memory blocks are passed into Numeric arrays353 /* These memory blocks are passed into numeric arrays 354 354 so don't free them */ 355 355 /* -
branches/numpy/anuga/mesh_engine/test_generate_mesh.py
r6174 r6304 12 12 from anuga.mesh_engine.mesh_engine import generate_mesh 13 13 14 import Numericas num14 import numpy as num 15 15 16 16 from anuga.utilities.numerical_tools import ensure_numeric … … 43 43 pointattlist,segattlist, mode, points) 44 44 45 correct = num.array([(1, 0, 2), (2, 3, 1)] , num.Int) #array default#45 correct = num.array([(1, 0, 2), (2, 3, 1)]) 46 46 self.failUnless(num.alltrue(data['generatedtrianglelist'].flat == \ 47 47 correct.flat), 48 48 'trianglelist is wrong!') 49 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)] , num.Int) #array default#49 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)]) 50 50 self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \ 51 51 correct.flat), … … 74 74 data = generate_mesh(points,seglist,holelist,regionlist, 75 75 pointattlist,segattlist, mode, points) 76 correct = num.array([(1, 0, 2), (2, 3, 1)] , num.Int) #array default#76 correct = num.array([(1, 0, 2), (2, 3, 1)]) 77 77 self.failUnless(num.alltrue(data['generatedtrianglelist'].flat == \ 78 78 correct.flat), 79 79 'trianglelist is wrong!') 80 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)] , num.Int) #array default#80 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)]) 81 81 self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \ 82 82 correct.flat), … … 154 154 pointattlist,segattlist, mode, points) 155 155 156 correct = num.array([(1, 0, 2), (2, 3, 1)] , num.Int) #array default#156 correct = num.array([(1, 0, 2), (2, 3, 1)]) 157 157 self.failUnless(num.alltrue(data['generatedtrianglelist'].flat == \ 158 158 correct.flat), 159 159 'trianglelist is wrong!') 160 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)] , num.Int) #array default#160 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)]) 161 161 self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \ 162 162 correct.flat), … … 170 170 171 171 self.failUnless(num.alltrue(data['generatedsegmentmarkerlist'] == \ 172 num.array([1,2,3,4] , num.Int)), #array default#172 num.array([1,2,3,4])), 173 173 'Failed!') 174 174 … … 388 388 389 389 390 correct = num.array([(1, 0, 2), (2, 3, 1)] , num.Int) #array default#390 correct = num.array([(1, 0, 2), (2, 3, 1)]) 391 391 self.failUnless(num.alltrue(data['generatedtrianglelist'].flat == \ 392 392 correct.flat), 393 393 'trianglelist is wrong!') 394 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)] , num.Int) #array default#394 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)]) 395 395 self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \ 396 396 correct.flat), … … 407 407 correct.flat), 408 408 'Failed') 409 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)] , num.Int) #array default#409 correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)]) 410 410 self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \ 411 411 correct.flat), 412 412 'Failed!') 413 413 414 correct = num.array(segattlist , num.Int) #array default#414 correct = num.array(segattlist) 415 415 self.failUnless(num.allclose(data['generatedsegmentmarkerlist'].flat, 416 416 correct.flat), … … 418 418 419 419 # I copied these answers from the output, so bad test.. 420 correct = num.array([(-1, 1, -1), (-1, 0, -1)] , num.Int) #array default#420 correct = num.array([(-1, 1, -1), (-1, 0, -1)]) 421 421 self.failUnless(num.alltrue(data['generatedtriangleneighborlist'].flat == \ 422 422 correct.flat), … … 467 467 468 468 suite = unittest.makeSuite(triangTestCase,'test') 469 #suite = unittest.makeSuite(triangTestCase,'testrectangleIIb')470 #suite = unittest.makeSuite(triangTestCase,'testsegmarker')471 #suite = unittest.makeSuite(triangTestCase,'testrectangle_regionsII')472 469 runner = unittest.TextTestRunner() #verbosity=2) 473 470 runner.run(suite) -
branches/numpy/anuga/pmesh/mesh.py
r6156 r6304 22 22 import types 23 23 import exceptions 24 25 import numpy as num 24 26 25 27 … … 37 39 except ImportError: 38 40 # Hand-built mockup of the things we need from the kinds package, since it 39 # was recently removed from the standard Numeric distro. Some users may41 # was recently removed from the standard numeric distro. Some users may 40 42 # not have it by default. 41 43 class _bunch: … … 117 119 118 120 class Vertex(Point): 119 """ 120 A point on the mesh. 121 """A point on the mesh. 121 122 Object attributes based on the Triangle program 122 123 """ 123 def __init__(self,X,Y, attributes = None): 124 125 VERTEXSQUARESIDELENGTH = 6 126 127 def __init__(self, X, Y, attributes=None): 124 128 __slots__ = ['x','y','attributes'] 125 126 assert (type(X) == types.FloatType or type(X) == types.IntType) 127 assert (type(Y) == types.FloatType or type(Y) == types.IntType) 128 self.x=X 129 self.y=Y 130 self.attributes=[] 131 132 if attributes is None: 133 self.attributes=[] 134 else: 129 130 # we don't care what we get, as long as we can get float *value* 131 self.x = float(X) 132 self.y = float(Y) 133 134 self.attributes = [] 135 if not attributes is None: 135 136 self.attributes=attributes 136 137 137 138 138 def setAttributes(self,attributes): 139 """ 140 attributes is a list. 141 """ 139 """attributes is a list. """ 140 142 141 self.attributes = attributes 143 142 144 VERTEXSQUARESIDELENGTH = 6145 143 def draw(self, canvas, tags, colour = 'black',scale = 1, xoffset = 0, 146 144 yoffset =0, ): … … 176 174 def __repr__(self): 177 175 return "[(%f,%f),%r]" % (self.x,self.y,self.attributes) 178 176 177 179 178 class Hole(Point): 180 """ 181 A region of the mesh were no triangles are generated. 179 """A region of the mesh were no triangles are generated. 182 180 Defined by a point in the hole enclosed by segments. 183 181 """ … … 201 199 202 200 class Region(Point): 203 """ 204 A region of the mesh, defined by a point in the region 205 enclosed by segments. Used to tag areas. 201 """A region of the mesh. 202 Defined by a point in the region enclosed by segments. Used to tag areas. 206 203 """ 204 207 205 CROSSLENGTH = 6 208 206 TAG = 0 209 207 MAXAREA = 1 210 208 211 def __init__(self,X,Y, tag = None, maxArea = None): 212 """Precondition: tag is a string and maxArea is a real 213 """ 214 # This didn't work. 215 #super(Region,self)._init_(self,X,Y) 209 def __init__(self, X, Y, tag=None, maxArea=None): 210 """Precondition: tag is a string and maxArea is a real""" 211 216 212 self.x=X 217 213 self.y=Y 218 self.attributes = [] # index 0 is the tag string219 #optoinal index 1 is the max triangle area220 #NOTE the size of this attribute is assumed221 # to be 1 or 2 in regionstrings2int214 self.attributes = [] # index 0 is the tag string 215 # optional index 1 is the max triangle area 216 # NOTE the size of this attribute is assumed 217 # to be 1 or 2 in regionstrings2int 222 218 if tag is None: 223 219 self.attributes.append("") -
branches/numpy/anuga/pmesh/mesh_interface.py
r6180 r6304 3 3 from anuga.utilities.polygon import point_in_polygon ,populate_polygon 4 4 from anuga.utilities.numerical_tools import ensure_numeric 5 import Numericas num5 import numpy as num 6 6 from anuga.utilities.polygon import inside_polygon 7 7 … … 156 156 157 157 # Simple check 158 bounding_polygon = ensure_numeric(bounding_polygon, num. Float)158 bounding_polygon = ensure_numeric(bounding_polygon, num.float) 159 159 msg = 'Bounding polygon must be a list of points or an Nx2 array' 160 160 assert len(bounding_polygon.shape) == 2, msg -
branches/numpy/anuga/pmesh/test_mesh.py
r6172 r6304 15 15 from anuga.utilities.polygon import is_inside_polygon ### inside_polygon 16 16 17 import Numericas num17 import numpy as num 18 18 19 19 class meshTestCase(unittest.TestCase): … … 428 428 vert = m.getMeshVerticeAttributes() 429 429 430 self.failUnless(vert[0] == [12.0, 2.0] and 431 vert[1] == [9.0, 7.0] and 432 vert[2] == [14.0,3.0] and 433 vert[3] == [12.232233047033631, 4.4142135623730949] and 434 vert[4] == [13.0, 2.5] , 430 self.failUnless(num.all(vert[0] == [12.0, 2.0]) and 431 num.all(vert[1] == [9.0, 7.0]) and 432 num.all(vert[2] == [14.0,3.0]) and 433 num.all(vert[3] == [12.232233047033631, 434 4.4142135623730949]) and 435 num.all(vert[4] == [13.0, 2.5]) , 435 436 'vertex attributes are wrong!') 436 437 … … 1655 1656 #print "dict['vertices']",dict['vertices'] 1656 1657 1657 self.failUnless( dict['vertices'] == answer, 1658 'test_Mesh2IOTriangulationDict failed. test 2') 1659 1660 self.failUnless(num.alltrue(dict['vertices'].flat == verts.flat), 1658 self.failUnless(num.alltrue(dict['vertices'] == answer), 1659 'test_Mesh2IOTriangulationDict failed. test 2') 1660 1661 self.failUnless(num.alltrue(dict['vertices'].flatten() == 1662 verts.flatten()), 1661 1663 'test_Mesh2IOTriangulationDict failed. test vert') 1662 self.failUnless(num.alltrue(dict['vertex_attributes'].flat == vert_as.flat), 1664 self.failUnless(num.alltrue(dict['vertex_attributes'].flatten() == 1665 vert_as.flatten()), 1663 1666 'test_Mesh2IOTriangulationDict failed. test vert ats') 1664 1667 … … 1716 1719 #print "dict['vertices']",dict['vertices'] 1717 1720 1718 self.failUnless( dict['vertices'] == answer,1719 1720 1721 self.failUnless( dict['vertices'] == verts,1722 1723 self.failUnless( dict['vertex_attributes'] == vert_as,1724 1725 1726 self.failUnless( dict['segments'][0] == [0,1],1721 self.failUnless(num.alltrue(dict['vertices'] == answer), 1722 'test_Mesh2IOTriangulationDict failed. test 2') 1723 1724 self.failUnless(num.alltrue(dict['vertices'] == verts), 1725 'test_Mesh2IOTriangulationDict failed. test vert') 1726 self.failUnless(num.alltrue(dict['vertex_attributes'] == vert_as), 1727 'test_Mesh2IOTriangulationDict failed. test vert ats') 1728 1729 self.failUnless(num.alltrue(dict['segments'][0] == [0,1]), 1727 1730 'test_Mesh2IODict failed. test 3') 1728 1731 1729 self.failUnless( 1732 self.failUnless(dict['segment_tags'] == seg_tags, 1730 1733 'test_Mesh2IODict failed. test 3') 1731 1734 #print " dict['triangles'][0]", dict['triangles'][0] 1732 self.failUnless( dict['triangles'][0] == [3,2,4],1735 self.failUnless(num.alltrue(dict['triangles'][0] == [3,2,4]), 1733 1736 'test_Mesh2IODict failed. test 5') 1734 self.failUnless( dict['triangle_neighbors'][0] == [-1,2,3],1737 self.failUnless(num.alltrue(dict['triangle_neighbors'][0] == [-1,2,3]), 1735 1738 'test_Mesh2IODict failed. test 6') 1736 1739 #print "dict['triangle_tags'][0]", dict['triangle_tags'][0] 1737 self.failUnless( 1738 1740 self.failUnless(dict['triangle_tags'][0] == "1.3", 1741 'test_Mesh2IODict failed. test 7') 1739 1742 1740 1743 seg = m.getUserSegments() … … 2198 2201 vert = m.get_user_vertices(absolute=True) 2199 2202 2200 self.failUnless(num.alltrue(vert.flat == num.array(points).flat), 2203 self.failUnless(num.alltrue(vert.flatten() == 2204 num.array(points).flatten()), 2201 2205 'FAILED!') 2202 2206 … … 2311 2315 if __name__ == "__main__": 2312 2316 suite = unittest.makeSuite(meshTestCase,'test') 2313 #suite = unittest.makeSuite(meshTestCase,'mode_string_float_problems')2314 #suite = unittest.makeSuite(meshTestCase,'test_import_mesh')2315 #suite = unittest.makeSuite(meshTestCase,'test_asciiFile')2316 #suite = unittest.makeSuite(meshTestCase,'test_mesh2IO')2317 #suite = unittest.makeSuite(meshTestCase,'test_add_points_and_segmentsII')2318 2317 runner = unittest.TextTestRunner() #verbosity=2) 2319 2318 runner.run(suite) -
branches/numpy/anuga/pmesh/test_mesh_interface.py
r6199 r6304 1 1 #!/usr/bin/env python 2 # 2 3 3 import tempfile 4 4 import unittest … … 13 13 from anuga.coordinate_transforms.geo_reference import Geo_reference,DEFAULT_ZONE 14 14 15 15 16 class TestCase(unittest.TestCase): 16 17 def setUp(self): 17 18 pass 18 19 19 20 def tearDown(self): 20 21 pass … … 23 24 x=-500 24 25 y=-1000 25 mesh_geo = geo_reference=Geo_reference(56, x,y)26 27 # These are the absolute values 28 polygon_absolute = [[0,0], [100,0],[100,100],[0,100]]29 26 mesh_geo = geo_reference=Geo_reference(56, x, y) 27 28 # These are the absolute values 29 polygon_absolute = [[0,0], [100,0], [100,100], [0,100]] 30 30 31 x_p = -10 31 32 y_p = -40 … … 33 34 polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute) 34 35 35 boundary_tags = {'walls':[0,1],'bom':[2,3]} 36 37 inner1_polygon_absolute = [[10,10],[20,10],[20,20],[10,20]] 38 inner1_polygon = geo_ref_poly. \ 39 change_points_geo_ref(inner1_polygon_absolute) 40 41 inner2_polygon_absolute = [[30,30],[40,30],[40,40],[30,40]] 42 inner2_polygon = geo_ref_poly. \ 43 change_points_geo_ref(inner2_polygon_absolute) 44 45 interior_regions = [(inner1_polygon, 5),(inner2_polygon, 10)] 46 47 #print polygon 48 #print boundary_tags 49 36 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 37 38 inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]] 39 inner1_polygon = geo_ref_poly.\ 40 change_points_geo_ref(inner1_polygon_absolute) 41 42 inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]] 43 inner2_polygon = geo_ref_poly.\ 44 change_points_geo_ref(inner2_polygon_absolute) 45 46 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)] 47 50 48 m = create_mesh_from_regions(polygon, 51 49 boundary_tags, … … 56 54 57 55 # Test the mesh instance 58 self.failUnless(len(m.regions)==3, 59 'FAILED!') 56 self.failUnless(len(m.regions)==3, 'FAILED!') 60 57 segs = m.getUserSegments() 61 self.failUnless(len(segs)==12, 62 'FAILED!') 63 self.failUnless(len(m.userVertices)==12, 64 'FAILED!') 65 self.failUnless(segs[0].tag=='walls', 66 'FAILED!') 67 self.failUnless(segs[1].tag=='walls', 68 'FAILED!') 69 70 self.failUnless(segs[2].tag=='bom', 71 'FAILED!') 72 self.failUnless(segs[3].tag=='bom', 73 'FAILED!') 58 self.failUnless(len(segs)==12, 'FAILED!') 59 self.failUnless(len(m.userVertices)==12, 'FAILED!') 60 self.failUnless(segs[0].tag=='walls', 'FAILED!') 61 self.failUnless(segs[1].tag=='walls', 'FAILED!') 62 self.failUnless(segs[2].tag=='bom', 'FAILED!') 63 self.failUnless(segs[3].tag=='bom', 'FAILED!') 74 64 75 65 # Assuming the order of the region points is known. … … 77 67 # a black box) 78 68 poly_point = m.getRegions()[0] 79 80 #print "poly_point", poly_point 81 #print "polygon_absolute",polygon_absolute 82 69 83 70 # poly_point values are relative to the mesh geo-ref 84 71 # make them absolute 85 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y],86 polygon_absolute, closed =False),72 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y], 73 polygon_absolute, closed=False), 87 74 'FAILED!') 88 75 89 76 # Assuming the order of the region points is known. 90 77 # (This isn't true, if you consider create_mesh_from_regions 91 78 # a black box) 92 79 poly_point = m.getRegions()[1] 93 94 #print "poly_point", poly_point 95 #print "polygon_absolute",polygon_absolute 96 80 97 81 # poly_point values are relative to the mesh geo-ref 98 82 # make them absolute 99 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y],83 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y], 100 84 inner1_polygon_absolute, 101 closed =False),85 closed=False), 102 86 'FAILED!') 103 87 104 88 # Assuming the order of the region points is known. 105 89 # (This isn't true, if you consider create_mesh_from_regions 106 90 # a black box) 107 91 poly_point = m.getRegions()[2] 108 109 #print "poly_point", poly_point 110 #print "polygon_absolute",polygon_absolute 111 92 112 93 # poly_point values are relative to the mesh geo-ref 113 94 # make them absolute 114 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y],95 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y], 115 96 inner2_polygon_absolute, 116 closed =False),97 closed=False), 117 98 'FAILED!') 118 119 99 120 100 def test_create_mesh_from_regions_with_caching(self): 121 101 x=-500 122 102 y=-1000 123 mesh_geo = geo_reference=Geo_reference(56, x,y)124 125 # These are the absolute values 126 polygon_absolute = [[0,0], [100,0],[100,100],[0,100]]127 103 mesh_geo = geo_reference=Geo_reference(56, x, y) 104 105 # These are the absolute values 106 polygon_absolute = [[0,0], [100,0], [100,100], [0,100]] 107 128 108 x_p = -10 129 109 y_p = -40 … … 131 111 polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute) 132 112 133 boundary_tags = {'walls': [0,1],'bom':[2,3]}134 135 inner1_polygon_absolute = [[10,10], [20,10],[20,20],[10,20]]136 inner1_polygon = geo_ref_poly. 137 change_points_geo_ref(inner1_polygon_absolute)138 139 inner2_polygon_absolute = [[30,30], [40,30],[40,40],[30,40]]140 inner2_polygon = geo_ref_poly. 141 change_points_geo_ref(inner2_polygon_absolute)142 143 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]113 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 114 115 inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]] 116 inner1_polygon = geo_ref_poly.\ 117 change_points_geo_ref(inner1_polygon_absolute) 118 119 inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]] 120 inner2_polygon = geo_ref_poly.\ 121 change_points_geo_ref(inner2_polygon_absolute) 122 123 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)] 144 124 145 125 interior_holes = None … … 147 127 # Clear cache first 148 128 from anuga.caching import cache 129 149 130 cache(_create_mesh_from_regions, 150 131 (polygon, boundary_tags), … … 159 140 clear=1) 160 141 161 #print polygon162 #print boundary_tags163 164 142 m = create_mesh_from_regions(polygon, 165 143 boundary_tags, … … 173 151 174 152 # Test the mesh instance 175 self.failUnless(len(m.regions)==3, 176 'FAILED!') 153 self.failUnless(len(m.regions)==3, 'FAILED!') 177 154 segs = m.getUserSegments() 178 self.failUnless(len(segs)==12, 179 'FAILED!') 180 self.failUnless(len(m.userVertices)==12, 181 'FAILED!') 182 self.failUnless(segs[0].tag=='walls', 183 'FAILED!') 184 self.failUnless(segs[1].tag=='walls', 185 'FAILED!') 186 187 self.failUnless(segs[2].tag=='bom', 188 'FAILED!') 189 self.failUnless(segs[3].tag=='bom', 190 'FAILED!') 155 self.failUnless(len(segs)==12, 'FAILED!') 156 self.failUnless(len(m.userVertices)==12, 'FAILED!') 157 self.failUnless(segs[0].tag=='walls', 'FAILED!') 158 self.failUnless(segs[1].tag=='walls', 'FAILED!') 159 self.failUnless(segs[2].tag=='bom', 'FAILED!') 160 self.failUnless(segs[3].tag=='bom', 'FAILED!') 191 161 192 162 # Assuming the order of the region points is known. … … 194 164 # a black box) 195 165 poly_point = m.getRegions()[0] 196 197 #print "poly_point", poly_point 198 #print "polygon_absolute",polygon_absolute 199 166 200 167 # poly_point values are relative to the mesh geo-ref 201 168 # make them absolute 202 self.failUnless(is_inside_polygon([poly_point.x+x,poly_point.y+y], 203 polygon_absolute, closed = False), 169 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y], 170 polygon_absolute, 171 closed=False), 204 172 'FAILED!') 205 173 206 174 # Assuming the order of the region points is known. 207 175 # (This isn't true, if you consider create_mesh_from_regions 208 176 # a black box) 209 177 poly_point = m.getRegions()[1] 210 211 #print "poly_point", poly_point 212 #print "polygon_absolute",polygon_absolute 213 178 214 179 # poly_point values are relative to the mesh geo-ref 215 180 # make them absolute 216 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y],181 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y], 217 182 inner1_polygon_absolute, 218 closed =False),183 closed=False), 219 184 'FAILED!') 220 185 221 186 # Assuming the order of the region points is known. 222 187 # (This isn't true, if you consider create_mesh_from_regions 223 188 # a black box) 224 189 poly_point = m.getRegions()[2] 225 226 #print "poly_point", poly_point 227 #print "polygon_absolute",polygon_absolute 228 190 229 191 # poly_point values are relative to the mesh geo-ref 230 192 # make them absolute 231 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y],193 self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y], 232 194 inner2_polygon_absolute, 233 closed =False),195 closed=False), 234 196 'FAILED!') 235 236 197 237 198 # Now create m using cached values … … 245 206 use_cache=True) 246 207 247 248 249 250 208 def test_create_mesh_from_regions2(self): 251 252 # These are the absolute values 253 min_x = -10 209 # These are the absolute values 210 min_x = -10 254 211 min_y = -88 255 polygon_absolute = [[min_x,min_y], [1000,100],[1000,1000],[100,1000]]256 212 polygon_absolute = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]] 213 257 214 x_p = -10 258 215 y_p = -40 … … 261 218 polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute) 262 219 263 boundary_tags = {'walls': [0,1],'bom':[2,3]}264 265 inner1_polygon_absolute = [[10,10], [20,10],[20,20],[10,20]]266 inner1_polygon = geo_ref_poly. 267 change_points_geo_ref(inner1_polygon_absolute)268 269 inner2_polygon_absolute = [[30,30], [40,30],[40,40],[30,40]]270 inner2_polygon = geo_ref_poly. 271 change_points_geo_ref(inner2_polygon_absolute)272 273 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]220 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 221 222 inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]] 223 inner1_polygon = geo_ref_poly.\ 224 change_points_geo_ref(inner1_polygon_absolute) 225 226 inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]] 227 inner2_polygon = geo_ref_poly.\ 228 change_points_geo_ref(inner2_polygon_absolute) 229 230 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)] 274 231 m = create_mesh_from_regions(polygon, 275 232 boundary_tags, … … 277 234 interior_regions=interior_regions, 278 235 poly_geo_reference=geo_ref_poly) 279 280 236 281 237 # Test the mesh instance 282 self.failUnless(len(m.regions)==3, 283 'FAILED!') 238 self.failUnless(len(m.regions)==3, 'FAILED!') 284 239 segs = m.getUserSegments() 285 self.failUnless(len(segs)==12, 286 'FAILED!') 287 self.failUnless(len(m.userVertices)==12, 288 'FAILED!') 289 self.failUnless(segs[0].tag=='walls', 290 'FAILED!') 291 self.failUnless(segs[1].tag=='walls', 292 'FAILED!') 293 294 self.failUnless(segs[2].tag=='bom', 295 'FAILED!') 296 self.failUnless(segs[3].tag=='bom', 297 'FAILED!') 298 299 self.failUnless(m.geo_reference.get_zone()==zone, 300 'FAILED!') 301 self.failUnless(m.geo_reference.get_xllcorner()==min_x, 302 'FAILED!') 303 self.failUnless(m.geo_reference.get_yllcorner()==min_y, 304 'FAILED!') 305 306 240 self.failUnless(len(segs)==12, 'FAILED!') 241 self.failUnless(len(m.userVertices)==12, 'FAILED!') 242 self.failUnless(segs[0].tag=='walls', 'FAILED!') 243 self.failUnless(segs[1].tag=='walls', 'FAILED!') 244 self.failUnless(segs[2].tag=='bom', 'FAILED!') 245 self.failUnless(segs[3].tag=='bom', 'FAILED!') 246 self.failUnless(m.geo_reference.get_zone()==zone, 'FAILED!') 247 self.failUnless(m.geo_reference.get_xllcorner()==min_x, 'FAILED!') 248 self.failUnless(m.geo_reference.get_yllcorner()==min_y, 'FAILED!') 249 307 250 def test_create_mesh_from_regions3(self): 308 309 # These are the absolute values 310 min_x = -10 251 # These are the absolute values 252 min_x = -10 311 253 min_y = -88 312 polygon = [[min_x,min_y], [1000,100],[1000,1000],[100,1000]]313 254 polygon = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]] 255 314 256 315 257 x_p = -10 316 258 y_p = -40 317 259 geo_ref_poly = Geo_reference(56, x_p, y_p) 318 319 boundary_tags = {'walls': [0,1],'bom':[2,3]}320 321 inner1_polygon_absolute = [[10,10], [20,10],[20,20],[10,20]]322 inner1_polygon = geo_ref_poly. 323 change_points_geo_ref(inner1_polygon_absolute)324 325 inner2_polygon_absolute = [[30,30], [40,30],[40,40],[30,40]]326 inner2_polygon = geo_ref_poly. 327 change_points_geo_ref(inner2_polygon_absolute)328 329 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]260 261 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 262 263 inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]] 264 inner1_polygon = geo_ref_poly.\ 265 change_points_geo_ref(inner1_polygon_absolute) 266 267 inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]] 268 inner2_polygon = geo_ref_poly.\ 269 change_points_geo_ref(inner2_polygon_absolute) 270 271 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)] 330 272 m = create_mesh_from_regions(polygon, 331 273 boundary_tags, 332 274 10000000, 333 275 interior_regions=interior_regions) 334 335 276 336 277 # Test the mesh instance 337 self.failUnless(len(m.regions)==3, 338 'FAILED!') 278 self.failUnless(len(m.regions) == 3, 'FAILED!') 339 279 segs = m.getUserSegments() 340 self.failUnless(len(segs)==12, 341 'FAILED!') 342 self.failUnless(len(m.userVertices)==12, 343 'FAILED!') 344 self.failUnless(segs[0].tag=='walls', 345 'FAILED!') 346 self.failUnless(segs[1].tag=='walls', 347 'FAILED!') 348 349 self.failUnless(segs[2].tag=='bom', 350 'FAILED!') 351 self.failUnless(segs[3].tag=='bom', 352 'FAILED!') 353 354 self.failUnless(m.geo_reference.get_zone()==DEFAULT_ZONE, 355 'FAILED!') 356 self.failUnless(m.geo_reference.get_xllcorner()==min_x, 357 'FAILED!') 358 self.failUnless(m.geo_reference.get_yllcorner()==min_y, 359 'FAILED!') 280 self.failUnless(len(segs) == 12, 'FAILED!') 281 self.failUnless(len(m.userVertices) == 12, 'FAILED!') 282 self.failUnless(segs[0].tag == 'walls', 'FAILED!') 283 self.failUnless(segs[1].tag == 'walls', 'FAILED!') 284 self.failUnless(segs[2].tag == 'bom', 'FAILED!') 285 self.failUnless(segs[3].tag == 'bom', 'FAILED!') 286 self.failUnless(m.geo_reference.get_zone() == DEFAULT_ZONE, 'FAILED!') 287 self.failUnless(m.geo_reference.get_xllcorner() == min_x, 'FAILED!') 288 self.failUnless(m.geo_reference.get_yllcorner() == min_y, 'FAILED!') 360 289 361 290 def test_create_mesh_from_regions4(self): 362 363 file_name = tempfile.mktemp(".tsh") 364 291 file_name = tempfile.mktemp('.tsh') 292 365 293 # These are the absolute values 366 294 density_outer = 1000 367 min_outer = 0 295 min_outer = 0 368 296 max_outer = 1000 369 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer],370 [max_outer,max_outer],[min_outer,max_outer]]371 297 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer], 298 [max_outer,max_outer], [min_outer,max_outer]] 299 372 300 density_inner1 = 10000000 373 301 inner_buffer = 100 374 302 min_inner1 = min_outer + inner_buffer 375 303 max_inner1 = max_outer - inner_buffer 376 inner1_polygon = [[min_inner1,min_inner1],[max_inner1,min_inner1], 377 [max_inner1,max_inner1],[min_inner1,max_inner1]] 378 379 380 boundary_tags = {'walls':[0,1],'bom':[2,3]} 381 304 inner1_polygon = [[min_inner1,min_inner1], [max_inner1,min_inner1], 305 [max_inner1,max_inner1], [min_inner1,max_inner1]] 306 307 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 308 382 309 interior_regions = [(inner1_polygon, density_inner1)] 383 create_mesh_from_regions(polygon_outer 384 , boundary_tags 385 , density_outer 386 , interior_regions=interior_regions 387 ,filename=file_name 388 #,verbose=True 389 ,verbose=False 390 ) 391 310 create_mesh_from_regions(polygon_outer, 311 boundary_tags, 312 density_outer, 313 interior_regions=interior_regions, 314 filename=file_name, verbose=False) 315 392 316 m = importMeshFromFile(file_name) 393 394 #print "file_name",file_name 317 395 318 self.failUnless(len(m.getTriangulation()) <= 900, 396 319 'Test mesh interface failed!') 397 320 self.failUnless(len(m.getTriangulation()) >= 200, 398 321 'Test mesh interface failed!') 399 400 create_mesh_from_regions(polygon_outer 401 , boundary_tags 402 , interior_regions=interior_regions 403 ,filename=file_name 404 #,verbose=True 405 ,verbose=False 406 ) 407 322 323 create_mesh_from_regions(polygon_outer, 324 boundary_tags, 325 interior_regions=interior_regions, 326 filename=file_name, 327 verbose=False) 328 408 329 m = importMeshFromFile(file_name) 409 410 #print "len(m.meshTriangles)",len(m.meshTriangles) 330 411 331 self.failUnless(len(m.getTriangulation()) <= 100, 412 332 'Test mesh interface failed!') 413 333 414 334 os.remove(file_name) 415 335 416 336 def test_create_mesh_from_regions5(self): 417 418 file_name = tempfile.mktemp(".tsh") 419 420 # These are the absolute values 421 density_outer = 10000000 422 min_outer = 0 337 file_name = tempfile.mktemp('.tsh') 338 339 # These are the absolute values 340 density_outer = 10000000 341 min_outer = 0 423 342 max_outer = 1000 424 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer],425 [max_outer,max_outer],[min_outer,max_outer]]426 343 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer], 344 [max_outer,max_outer], [min_outer,max_outer]] 345 427 346 density_inner1 = 1000 428 347 inner_buffer = 100 429 348 min_inner1 = min_outer + inner_buffer 430 349 max_inner1 = max_outer - inner_buffer 431 inner1_polygon = [[min_inner1,min_inner1],[max_inner1,min_inner1], 432 [max_inner1,max_inner1],[min_inner1,max_inner1]] 433 434 435 boundary_tags = {'walls':[0,1],'bom':[2,3]} 436 350 inner1_polygon = [[min_inner1,min_inner1], [max_inner1,min_inner1], 351 [max_inner1,max_inner1], [min_inner1,max_inner1]] 352 353 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 354 437 355 interior_regions = [(inner1_polygon, density_inner1)] 438 create_mesh_from_regions(polygon_outer 439 , boundary_tags 440 , density_outer 441 , interior_regions=interior_regions 442 ,filename=file_name 443 #,verbose=True 444 ,verbose=False 445 ) 446 356 create_mesh_from_regions(polygon_outer, 357 boundary_tags, 358 density_outer, 359 interior_regions=interior_regions, 360 filename=file_name, 361 verbose=False) 362 447 363 m = importMeshFromFile(file_name) 448 #print "file_name",file_name 449 #print "len(m.meshTriangles",len(m.meshTriangles) 450 self.failUnless(len(m.getTriangulation()) <= 2000, 364 self.failUnless(len(m.getTriangulation()) <= 2000, 451 365 'Test mesh interface failed!') 452 453 366 self.failUnless(len(m.getTriangulation()) >= 900, 454 367 'Test mesh interface failed!') 455 368 456 369 os.remove(file_name) 457 370 458 371 def test_create_mesh_from_regions6(self): 459 460 file_name = tempfile.mktemp(".tsh") 461 372 file_name = tempfile.mktemp('.tsh') 373 462 374 # These are the absolute values 463 375 density_outer = 1000 464 min_outer = 0 376 min_outer = 0 465 377 max_outer = 1000 466 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer],467 [max_outer,max_outer], [min_outer,max_outer]]378 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer], 379 [max_outer,max_outer], [min_outer,max_outer]] 468 380 469 381 delta = 10 … … 471 383 min_inner1 = min_outer + delta 472 384 max_inner1 = max_outer - delta 473 inner1_polygon = [[min_inner1,min_inner1],[max_inner1,min_inner1], 474 [max_inner1,max_inner1],[min_inner1,max_inner1]] 475 476 477 density_inner2 = 10000000 385 inner1_polygon = [[min_inner1,min_inner1], [max_inner1,min_inner1], 386 [max_inner1,max_inner1], [min_inner1,max_inner1]] 387 388 density_inner2 = 10000000 478 389 min_inner2 = min_outer + 2*delta 479 390 max_inner2 = max_outer - 2*delta 480 inner2_polygon = [[min_inner2,min_inner2], [max_inner2,min_inner2],481 [max_inner2,max_inner2], [min_inner2,max_inner2]]482 483 boundary_tags = {'walls': [0,1],'bom':[2,3]}484 391 inner2_polygon = [[min_inner2,min_inner2], [max_inner2,min_inner2], 392 [max_inner2,max_inner2], [min_inner2,max_inner2]] 393 394 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 395 485 396 interior_regions = [(inner1_polygon, density_inner1), 486 397 (inner2_polygon, density_inner2)] … … 491 402 filename=file_name, 492 403 verbose=False) 493 404 494 405 m = importMeshFromFile(file_name) 495 #print "file_name",file_name 496 #print "len(m.meshTriangles",len(m.meshTriangles) 497 self.failUnless(len(m.getTriangulation()) <= 2000, 406 self.failUnless(len(m.getTriangulation()) <= 2000, 498 407 'Test mesh interface failed!') 499 500 408 self.failUnless(len(m.getTriangulation()) >= 900, 501 409 'Test mesh interface failed!') 502 410 503 411 os.remove(file_name) 504 412 505 413 def test_create_mesh_from_regions7(self): 506 507 file_name = tempfile.mktemp(".tsh") 508 414 file_name = tempfile.mktemp('.tsh') 415 509 416 # These are the absolute values 510 417 density_outer = 1001 511 min_outer = 0 418 min_outer = 0 512 419 max_outer = 1000 513 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer],514 [max_outer,max_outer],[min_outer,max_outer]]420 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer], 421 [max_outer,max_outer], [min_outer,max_outer]] 515 422 516 423 delta = 10 … … 518 425 min_inner1 = min_outer + delta 519 426 max_inner1 = max_outer - delta 520 inner1_polygon = [[min_inner1,min_inner1],[max_inner1,min_inner1], 521 [max_inner1,max_inner1],[min_inner1,max_inner1]] 522 523 524 density_inner2 = 1000 427 inner1_polygon = [[min_inner1,min_inner1], [max_inner1,min_inner1], 428 [max_inner1,max_inner1], [min_inner1,max_inner1]] 429 430 density_inner2 = 1000 525 431 min_inner2 = min_outer + 2*delta 526 432 max_inner2 = max_outer - 2*delta 527 inner2_polygon = [[min_inner2,min_inner2], [max_inner2,min_inner2],528 [max_inner2,max_inner2],[min_inner2,max_inner2]]529 530 boundary_tags = {'walls': [0,1],'bom':[2,3]}531 532 # Note the list order is important433 inner2_polygon = [[min_inner2,min_inner2], [max_inner2,min_inner2], 434 [max_inner2,max_inner2], [min_inner2,max_inner2]] 435 436 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 437 438 # Note the list order is important 533 439 # The last region added will be the region triangle uses, 534 440 # if two regions points are in the same bounded area. 535 interior_regions = [(inner2_polygon, density_inner2),(inner1_polygon, density_inner1)] 441 interior_regions = [(inner2_polygon, density_inner2), 442 (inner1_polygon, density_inner1)] 536 443 create_mesh_from_regions(polygon_outer, 537 444 boundary_tags, … … 540 447 filename=file_name, 541 448 verbose=False) 542 449 543 450 m = importMeshFromFile(file_name) 544 #print "file_name",file_name 545 #print "len(m.meshTriangles",len(m.meshTriangles) 546 self.failUnless(len(m.getTriangulation()) <= 3000, 451 self.failUnless(len(m.getTriangulation()) <= 3000, 547 452 'Test mesh interface failed!') 548 549 453 self.failUnless(len(m.getTriangulation()) >= 2000, 550 454 'Test mesh interface failed!') … … 552 456 os.remove(file_name) 553 457 554 555 458 def test_create_mesh_from_regions_interior_regions(self): 556 """Test that create_mesh_from_regions fails when an interior region is557 outside bounding polygon. """558 559 560 # These are the absolute values 561 min_x = 10 459 '''Test that create_mesh_from_regions fails when an interior 460 region is outside bounding polygon. 461 ''' 462 463 # These are the absolute values 464 min_x = 10 562 465 min_y = 88 563 polygon = [[min_x,min_y], [1000,100],[1000,1000],[100,1000]]564 565 boundary_tags = {'walls': [0,1],'bom':[2,3]}566 # boundary_tags = {'walls':[0,1]} 466 polygon = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]] 467 468 boundary_tags = {'walls': [0,1], 'bom': [2,3]} 469 567 470 # This one is inside bounding polygon - should pass 568 inner_polygon = [[800,400], [900,500],[800,600]]471 inner_polygon = [[800,400], [900,500], [800,600]] 569 472 570 473 interior_regions = [(inner_polygon, 5)] … … 574 477 interior_regions=interior_regions) 575 478 576 577 479 # This one sticks outside bounding polygon - should fail 578 inner_polygon = [[800,400], [900,500],[800,600], [200, 995]]579 inner_polygon1 = [[800,400], [1100,500],[800,600]]480 inner_polygon = [[800,400], [900,500], [800,600], [200, 995]] 481 inner_polygon1 = [[800,400], [1100,500], [800,600]] 580 482 interior_regions = [[inner_polygon, 50], [inner_polygon1, 50]] 581 483 582 583 584 484 try: 585 485 m = create_mesh_from_regions(polygon, … … 593 493 msg = 'Interior polygon sticking outside bounding polygon should ' 594 494 msg += 'cause an Exception to be raised' 595 raise msg495 raise Exception, msg 596 496 597 497 def test_create_mesh_from_regions_interior_regions1(self): 598 """Test that create_mesh_from_regions fails when an interior region is599 outside bounding polygon. """600 498 '''Test that create_mesh_from_regions fails 499 when an interior region is outside bounding polygon. 500 ''' 601 501 602 502 # These are the values 603 604 503 d0 = [310000, 7690000] 605 504 d1 = [280000, 7690000] … … 609 508 d5 = [300000, 7590000] 610 509 d6 = [340000, 7610000] 611 612 510 poly_all = [d0, d1, d2, d3, d4, d5, d6] 613 511 614 512 i0 = [304000, 7607000] 615 513 i1 = [302000, 7605000] … … 619 517 # i4 = [310000, 7580000] 620 518 i5 = [307000, 7606000] 621 622 519 poly_onslow = [i0, i1, i2, i3, i4, i5] 623 520 624 # Thevenard Island521 # Thevenard Island 625 522 j0 = [294000, 7629000] 626 523 j1 = [285000, 7625000] 627 524 j2 = [294000, 7621000] 628 525 j3 = [299000, 7625000] 629 630 526 poly_thevenard = [j0, j1, j2, j3] 631 527 632 # med res around onslow528 # med res around onslow 633 529 l0 = [300000, 7610000] 634 530 l1 = [285000, 7600000] 635 531 l2 = [300000, 7597500] 636 l3 = [310000, 7770000] # this one is outside637 # l3 = [310000, 7630000] # this one is NOT outside532 l3 = [310000, 7770000] # this one is outside 533 # l3 = [310000, 7630000] # this one is NOT outside 638 534 l4 = [315000, 7610000] 639 535 poly_coast = [l0, l1, l2, l3, l4] 640 536 641 # general coast and local area to onslow region537 # general coast and local area to onslow region 642 538 m0 = [270000, 7581000] 643 539 m1 = [300000, 7591000] … … 646 542 m4 = [290000, 7640000] 647 543 m5 = [260000, 7600000] 648 649 544 poly_region = [m0, m1, m2, m3, m4, m5] 650 545 651 546 # This one sticks outside bounding polygon - should fail 652 653 interior_regions = [[poly_onslow, 50000], [poly_region, 50000], [poly_coast,100000], [poly_thevenard, 100000]] 654 655 boundary_tags = {'walls':[0,1],'bom':[2]} 656 547 interior_regions = [[poly_onslow, 50000], [poly_region, 50000], 548 [poly_coast, 100000], [poly_thevenard, 100000]] 549 boundary_tags = {'walls': [0,1], 'bom': [2]} 550 657 551 try: 658 552 m = create_mesh_from_regions(poly_all, … … 666 560 msg = 'Interior polygon sticking outside bounding polygon should ' 667 561 msg += 'cause an Exception to be raised' 668 raise msg 669 670 562 raise Exception, msg 671 563 672 564 def FIXME_test_create_mesh_with_multiply_tagged_segments(self): 673 """Test that create_mesh_from_regions fails when565 '''Test that create_mesh_from_regions fails when 674 566 segments are listed repeatedly in boundary_tags. 675 """ 676 677 678 679 680 # These are the absolute values 681 min_x = 10 567 ''' 568 569 # These are the absolute values 570 min_x = 10 682 571 min_y = 88 683 polygon = [[min_x,min_y],[1000,100],[1000,1000],[100,1000]] 684 685 686 boundary_tags = {'walls':[0,1],'bom':[1,2]} 572 polygon = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]] 573 boundary_tags = {'walls': [0,1], 'bom': [1,2]} 687 574 688 575 # This one is inside bounding polygon - should pass 689 inner_polygon = [[800,400],[900,500],[800,600]] 690 576 inner_polygon = [[800,400], [900,500], [800,600]] 691 577 interior_regions = [(inner_polygon, 5)] 692 578 m = create_mesh_from_regions(polygon, 693 579 boundary_tags, 694 580 10000000, 695 interior_regions=interior_regions, verbose=False)696 581 interior_regions=interior_regions, 582 verbose=False) 697 583 698 584 # This one sticks outside bounding polygon - should fail 699 inner_polygon = [[800,400], [900,500],[800,600]]585 inner_polygon = [[800,400], [900,500], [800,600]] 700 586 interior_regions = [(inner_polygon, 5)] 701 702 703 704 587 try: 705 588 m = create_mesh_from_regions(polygon, … … 712 595 msg = 'Tags are listed repeatedly, but create mesh from regions ' 713 596 msg += 'does not cause an Exception to be raised' 714 raise msg 715 716 717 597 raise Exception, msg 718 598 719 599 def test_create_mesh_from_regions_with_duplicate_verts(self): 720 721 # These are the absolute values 722 723 polygon_absolute = [[0.0,0.0], 724 [0,4.0], 725 [4.0,4.0], 726 [4.0,0.0], 727 [4.0,0.0]] 728 600 # These are the absolute values 601 polygon_absolute = [[0.0, 0.0], 602 [0, 4.0], 603 [4.0, 4.0], 604 [4.0, 0.0], 605 [4.0, 0.0]] 729 606 x_p = -10 730 607 y_p = -40 … … 732 609 geo_ref_poly = Geo_reference(zone, x_p, y_p) 733 610 polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute) 734 735 boundary_tags = {'50':[0], 736 '40':[1], 737 '30':[2], 738 'no where seg':[3], 739 '20':[4] 740 } 741 611 boundary_tags = {'50': [0], 612 '40': [1], 613 '30': [2], 614 'no where seg': [3], 615 '20': [4]} 742 616 m = create_mesh_from_regions(polygon, 743 617 boundary_tags, 744 618 10000000, 745 poly_geo_reference=geo_ref_poly, verbose=False)746 747 748 fileName = "badmesh.tsh"619 poly_geo_reference=geo_ref_poly, 620 verbose=False) 621 622 fileName = 'badmesh.tsh' 749 623 #m.export_mesh_file(fileName) 750 751 624 752 625 def concept_create_mesh_from_regions_with_ungenerate(self): 753 626 x=0 754 627 y=0 755 mesh_geo = geo_reference=Geo_reference(56,x,y) 756 757 # These are the absolute values 758 polygon_absolute = [[0,0],[100,0],[100,100],[0,100]] 759 628 mesh_geo = geo_reference=Geo_reference(56, x, y) 629 630 # These are the absolute values 631 polygon_absolute = [[0,0], [100,0], [100,100], [0,100]] 760 632 x_p = -10 761 633 y_p = -40 … … 763 635 polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute) 764 636 765 boundary_tags = {'walls': [0,1],'bom':[2]}766 767 inner1_polygon_absolute = [[10,10], [20,10],[20,20],[10,20]]768 inner1_polygon = geo_ref_poly. 769 change_points_geo_ref(inner1_polygon_absolute)770 771 inner2_polygon_absolute = [[30,30], [40,30],[40,40],[30,40]]772 inner2_polygon = geo_ref_poly. 773 change_points_geo_ref(inner2_polygon_absolute)774 637 boundary_tags = {'walls': [0,1], 'bom': [2]} 638 639 inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]] 640 inner1_polygon = geo_ref_poly.\ 641 change_points_geo_ref(inner1_polygon_absolute) 642 643 inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]] 644 inner2_polygon = geo_ref_poly.\ 645 change_points_geo_ref(inner2_polygon_absolute) 646 775 647 max_area = 10000000 776 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]648 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)] 777 649 m = create_mesh_from_regions(polygon, 778 650 boundary_tags, … … 781 653 poly_geo_reference=geo_ref_poly, 782 654 mesh_geo_reference=mesh_geo) 783 784 m.export_mesh_file('a_test_mesh_iknterface.tsh') 785 786 fileName = tempfile.mktemp( ".txt")787 file = open(fileName, "w")788 file.write( "1 ?? ??\n\655 656 m.export_mesh_file('a_test_mesh_iknterface.tsh') 657 658 fileName = tempfile.mktemp('.txt') 659 file = open(fileName, 'w') 660 file.write(' 1 ?? ??\n\ 789 661 90.0 90.0\n\ 790 662 81.0 90.0\n\ … … 799 671 10.0 80.0\n\ 800 672 END\n\ 801 END\n ")802 file.close() 803 673 END\n') 674 file.close() 675 804 676 m.import_ungenerate_file(fileName, tag='wall') 805 677 os.remove(fileName) 806 m.generate_mesh(maximum_triangle_area=max_area, verbose=False)678 m.generate_mesh(maximum_triangle_area=max_area, verbose=False) 807 679 m.export_mesh_file('b_test_mesh_iknterface.tsh') 808 680 809 681 def concept_ungenerateII(self): 810 811 682 from anuga.shallow_water import Domain, Reflective_boundary, \ 812 683 Dirichlet_boundary 684 813 685 x=0 814 686 y=0 815 mesh_geo = geo_reference=Geo_reference(56,x,y) 816 817 # These are the absolute values 818 polygon_absolute = [[0,0],[100,0],[100,100],[0,100]] 819 687 mesh_geo = geo_reference=Geo_reference(56, x, y) 688 689 # These are the absolute values 690 polygon_absolute = [[0,0], [100,0], [100,100], [0,100]] 820 691 x_p = -10 821 692 y_p = -40 … … 823 694 polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute) 824 695 825 boundary_tags = {'wall': [0,1,3],'wave':[2]}826 827 inner1_polygon_absolute = [[10,10], [20,10],[20,20],[10,20]]828 inner1_polygon = geo_ref_poly. 829 change_points_geo_ref(inner1_polygon_absolute)830 831 inner2_polygon_absolute = [[30,30], [40,30],[40,40],[30,40]]832 inner2_polygon = geo_ref_poly. 833 change_points_geo_ref(inner2_polygon_absolute)834 696 boundary_tags = {'wall': [0,1,3], 'wave': [2]} 697 698 inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]] 699 inner1_polygon = geo_ref_poly.\ 700 change_points_geo_ref(inner1_polygon_absolute) 701 702 inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]] 703 inner2_polygon = geo_ref_poly.\ 704 change_points_geo_ref(inner2_polygon_absolute) 705 835 706 max_area = 1 836 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]707 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)] 837 708 m = create_mesh_from_regions(polygon, 838 709 boundary_tags, … … 841 712 poly_geo_reference=geo_ref_poly, 842 713 mesh_geo_reference=mesh_geo) 843 844 m.export_mesh_file('a_test_mesh_iknterface.tsh') 845 846 fileName = tempfile.mktemp( ".txt")847 file = open(fileName, "w")848 file.write( "1 ?? ??\n\714 715 m.export_mesh_file('a_test_mesh_iknterface.tsh') 716 717 fileName = tempfile.mktemp('.txt') 718 file = open(fileName, 'w') 719 file.write(' 1 ?? ??\n\ 849 720 90.0 90.0\n\ 850 721 81.0 90.0\n\ … … 859 730 10.0 80.0\n\ 860 731 END\n\ 861 END\n ")862 file.close() 863 864 m.import_ungenerate_file(fileName) #, tag='wall')732 END\n') 733 file.close() 734 735 m.import_ungenerate_file(fileName) #, tag='wall') 865 736 os.remove(fileName) 866 m.generate_mesh(maximum_triangle_area=max_area, verbose=False)867 mesh_filename = "bento_b.tsh"737 m.generate_mesh(maximum_triangle_area=max_area, verbose=False) 738 mesh_filename = 'bento_b.tsh' 868 739 m.export_mesh_file(mesh_filename) 869 740 870 741 domain = Domain(mesh_filename, use_cache = False) 871 742 872 743 Br = Reflective_boundary(domain) 873 Bd = Dirichlet_boundary([3, 0,0])874 domain.set_boundary( {'wall': Br, 'wave': Bd})744 Bd = Dirichlet_boundary([3, 0, 0]) 745 domain.set_boundary({'wall': Br, 'wave': Bd}) 875 746 yieldstep = 0.1 876 747 finaltime = 10 877 for t in domain.evolve(yieldstep, finaltime): 748 for t in domain.evolve(yieldstep, finaltime): 878 749 domain.write_time() 879 750 880 751 def concept_ungenerateIII(self): 881 882 752 from anuga.shallow_water import Domain, Reflective_boundary, \ 883 753 Dirichlet_boundary 884 885 754 from anuga.pmesh.mesh_interface import create_mesh_from_regions 886 887 # These are the absolute values 888 polygon = [[0,0],[100,0],[100,100],[0,100]] 889 890 boundary_tags = {'wall':[0,1,3],'wave':[2]} 891 892 inner1_polygon = [[10,10],[20,10],[20,20],[10,20]] 893 894 895 inner2_polygon = [[30,30],[40,30],[40,40],[30,40]] 896 897 755 756 # These are the absolute values 757 polygon = [[0,0], [100,0], [100,100], [0,100]] 758 759 boundary_tags = {'wall': [0,1,3], 'wave': [2]} 760 inner1_polygon = [[10,10], [20,10], [20,20], [10,20]] 761 inner2_polygon = [[30,30], [40,30], [40,40], [30,40]] 762 898 763 max_area = 1 899 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]764 interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)] 900 765 m = create_mesh_from_regions(polygon, 901 766 boundary_tags, 902 767 max_area, 903 768 interior_regions=interior_regions) 904 905 fileName = tempfile.mktemp( ".txt")906 file = open(fileName, "w")907 file.write( "1 ?? ??\n\769 770 fileName = tempfile.mktemp('.txt') 771 file = open(fileName, 'w') 772 file.write(' 1 ?? ??\n\ 908 773 90.0 90.0\n\ 909 774 81.0 90.0\n\ … … 918 783 10.0 80.0\n\ 919 784 END\n\ 920 END\n ")921 file.close() 922 923 m.import_ungenerate_file(fileName) 785 END\n') 786 file.close() 787 788 m.import_ungenerate_file(fileName) 924 789 os.remove(fileName) 925 m.generate_mesh(maximum_triangle_area=max_area, verbose=False)926 mesh_filename = "mesh.tsh"790 m.generate_mesh(maximum_triangle_area=max_area, verbose=False) 791 mesh_filename = 'mesh.tsh' 927 792 m.export_mesh_file(mesh_filename) 928 793 929 domain = Domain(mesh_filename, use_cache =False)930 794 domain = Domain(mesh_filename, use_cache=False) 795 931 796 Br = Reflective_boundary(domain) 932 Bd = Dirichlet_boundary([3, 0,0])933 domain.set_boundary( {'wall': Br, 'wave': Bd})797 Bd = Dirichlet_boundary([3, 0, 0]) 798 domain.set_boundary({'wall': Br, 'wave': Bd}) 934 799 yieldstep = 0.1 935 800 finaltime = 10 936 for t in domain.evolve(yieldstep, finaltime): 801 for t in domain.evolve(yieldstep, finaltime): 937 802 domain.write_time() 938 803 939 940 941 804 def test_create_mesh_from_regions_check_segs(self): 942 """Test that create_mesh_from_regions fails when an interior region is943 outside bounding polygon. """944 945 946 # These are the absolute values 947 min_x = 10 805 '''Test that create_mesh_from_regions fails 806 when an interior region is outside bounding polygon. 807 ''' 808 809 # These are the absolute values 810 min_x = 10 948 811 min_y = 88 949 polygon = [[min_x,min_y],[1000,100],[1000,1000],[100,1000]] 950 951 boundary_tags = {'walls':[0,1,3],'bom':[2]} 952 # boundary_tags = {'walls':[0,1]} 812 polygon = [[min_x,min_y], [1000,100], [1000,1000], [100,1000]] 813 boundary_tags = {'walls': [0,1,3], 'bom': [2]} 814 953 815 # This one is inside bounding polygon - should pass 954 inner_polygon = [[800,400],[900,500],[800,600]] 955 816 inner_polygon = [[800,400], [900,500], [800,600]] 956 817 interior_regions = [(inner_polygon, 5)] 957 818 m = create_mesh_from_regions(polygon, … … 960 821 interior_regions=interior_regions) 961 822 962 boundary_tags = {'walls':[0,1,3,4],'bom':[2]} 963 823 boundary_tags = {'walls': [0,1,3,4], 'bom': [2]} 964 824 try: 965 825 m = create_mesh_from_regions(polygon, … … 970 830 pass 971 831 else: 972 msg = ' segment out of bounds not caught '973 raise msg974 975 832 msg = 'Segment out of bounds not caught ' 833 raise Exception, msg 834 835 976 836 #------------------------------------------------------------- 977 837 if __name__ == "__main__": 978 838 suite = unittest.makeSuite(TestCase,'test') 979 #suite = unittest.makeSuite(TestCase,'test_create_mesh_from_regions_check_segs')980 839 runner = unittest.TextTestRunner() #verbosity=2) 981 840 runner.run(suite) 982 841 -
branches/numpy/anuga/shallow_water/benchmark_sww2dem.py
r6162 r6304 25 25 26 26 from Scientific.IO.NetCDF import NetCDFFile 27 import Numericas num27 import numpy as num 28 28 29 29 from anuga.fit_interpolate.interpolate import Interpolate … … 101 101 sww_fileName = tempfile.mktemp(".sww" ) 102 102 # sww_fileName = "aa.sww" 103 elevation = num.array(range(len(mesh_dict["vertices"])), num. Int) #array default#103 elevation = num.array(range(len(mesh_dict["vertices"])), num.int) #array default# 104 104 stage = elevation 105 105 ymomentum = elevation … … 111 111 sww.store_header(fid, 0, 112 112 len(mesh_dict['triangles']), 113 len(mesh_dict["vertices"]),sww_precision=num. Float)113 len(mesh_dict["vertices"]),sww_precision=num.float) 114 114 sww.store_triangulation(fid, 115 115 mesh_dict["vertices"], mesh_dict['triangles'], -
branches/numpy/anuga/shallow_water/data_manager.py
r6224 r6304 61 61 from os import sep, path, remove, mkdir, access, F_OK, W_OK, getcwd 62 62 63 import Numericas num63 import numpy as num 64 64 65 65 from Scientific.IO.NetCDF import NetCDFFile … … 76 76 default_minimum_storable_height 77 77 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 78 from anuga.config import netcdf_float, netcdf_float32, netcdf_int 78 79 from anuga.config import max_float 79 80 from anuga.utilities.numerical_tools import ensure_numeric, mean … … 343 344 from Scientific.IO.NetCDF import NetCDFFile 344 345 345 self.precision = n um.Float32 #Use single precision for quantities346 self.precision = netcdf_float32 #Use single precision for quantities 346 347 self.recursion = recursion 347 348 self.mode = mode … … 438 439 439 440 # store the connectivity data 440 points = num.concatenate( (X[:,num. NewAxis],Y[:,num.NewAxis]), axis=1 )441 points = num.concatenate( (X[:,num.newaxis],Y[:,num.newaxis]), axis=1 ) 441 442 self.writer.store_triangulation(fid, 442 443 points, 443 # V.astype(volumes.typecode()), 444 V.astype(num.Float32), 444 V.astype(num.float32), 445 445 Z, 446 446 points_georeference=\ … … 561 561 # Define a zero vector of same size and type as A 562 562 # for use with momenta 563 null = num.zeros(num.size(A), A. typecode())563 null = num.zeros(num.size(A), A.dtype.char) #??# 564 564 565 565 # Get xmomentum where depth exceeds minimum_storable_height … … 622 622 from Scientific.IO.NetCDF import NetCDFFile 623 623 624 self.precision = n um.Float #Use full precision624 self.precision = netcdf_float #Use full precision 625 625 626 626 Data_format.__init__(self, domain, 'sww', mode) … … 650 650 651 651 652 fid.createVariable('volumes', n um.Int, ('number_of_volumes',653 'number_of_vertices'))652 fid.createVariable('volumes', netcdf_int, ('number_of_volumes', 653 'number_of_vertices')) 654 654 655 655 fid.createVariable('time', self.precision, ('number_of_timesteps',)) … … 1304 1304 1305 1305 M = size #Number of lines 1306 xx = num.zeros((M,3), num. Float)1307 yy = num.zeros((M,3), num. Float)1308 zz = num.zeros((M,3), num. Float)1306 xx = num.zeros((M,3), num.float) 1307 yy = num.zeros((M,3), num.float) 1308 zz = num.zeros((M,3), num.float) 1309 1309 1310 1310 for i in range(M): … … 1349 1349 1350 1350 M = len(lines) #Number of lines 1351 x = num.zeros((M,3), num. Float)1352 y = num.zeros((M,3), num. Float)1353 z = num.zeros((M,3), num. Float)1351 x = num.zeros((M,3), num.float) 1352 y = num.zeros((M,3), num.float) 1353 z = num.zeros((M,3), num.float) 1354 1354 1355 1355 for i, line in enumerate(lines): … … 1409 1409 # @param step Timestep stride. 1410 1410 def filter_netcdf(filename1, filename2, first=0, last=None, step=1): 1411 """Read netcdf filename1, pick timesteps first:step:last and save to 1411 """Filter data file, selecting timesteps first:step:last. 1412 1413 Read netcdf filename1, pick timesteps first:step:last and save to 1412 1414 nettcdf file filename2 1413 1415 """ … … 1426 1428 for name in infile.variables: 1427 1429 var = infile.variables[name] 1428 outfile.createVariable(name, var. typecode(), var.dimensions)1430 outfile.createVariable(name, var.dtype.char, var.dimensions) #??# 1429 1431 1430 1432 # Copy the static variables … … 1499 1501 Convert to NetCDF pts format which is 1500 1502 1501 points: (Nx2) Float array1502 elevation: N Float array1503 points: (Nx2) float array 1504 elevation: N float array 1503 1505 """ 1504 1506 … … 1658 1660 1659 1661 # Variable definitions 1660 outfile.createVariable('points', n um.Float, ('number_of_points',1661 'number_of_dimensions'))1662 outfile.createVariable('elevation', n um.Float, ('number_of_points',))1662 outfile.createVariable('points', netcdf_float, ('number_of_points', 1663 'number_of_dimensions')) 1664 outfile.createVariable('elevation', netcdf_float, ('number_of_points',)) 1663 1665 1664 1666 # Get handles to the variables … … 1684 1686 newcols = lenv # ncols_in_bounding_box 1685 1687 1686 telev = num.zeros(newcols, num. Float)1687 tpoints = num.zeros((newcols, 2), num. Float)1688 telev = num.zeros(newcols, num.float) 1689 tpoints = num.zeros((newcols, 2), num.float) 1688 1690 1689 1691 local_index = 0 … … 1801 1803 Convert to NetCDF pts format which is 1802 1804 1803 points: (Nx2) Float array1804 elevation: N Float array1805 points: (Nx2) float array 1806 elevation: N float array 1805 1807 """ 1806 1808 … … 2245 2247 # Comment out for reduced memory consumption 2246 2248 for name in ['stage', 'xmomentum', 'ymomentum']: 2247 q = fid.variables[name][:].flat 2249 q = fid.variables[name][:].flatten() 2248 2250 if timestep is not None: 2249 2251 q = q[timestep*len(x):(timestep+1)*len(x)] 2250 2252 if verbose: print ' %s in [%f, %f]' %(name, min(q), max(q)) 2251 2253 for name in ['elevation']: 2252 q = fid.variables[name][:].flat 2254 q = fid.variables[name][:].flatten() 2253 2255 if verbose: print ' %s in [%f, %f]' %(name, min(q), max(q)) 2254 2256 … … 2256 2258 if verbose: print 'Processing quantity %s' %quantity 2257 2259 2258 # Turn NetCDF objects into Numeric arrays2260 # Turn NetCDF objects into numeric arrays 2259 2261 try: 2260 2262 q = fid.variables[quantity][:] … … 2269 2271 #q has a time component, must be reduced alongthe temporal dimension 2270 2272 if verbose: print 'Reducing quantity %s' %quantity 2271 q_reduced = num.zeros(number_of_points, num. Float)2273 q_reduced = num.zeros(number_of_points, num.float) 2272 2274 2273 2275 if timestep is not None: … … 2329 2331 y = y + yllcorner - newyllcorner 2330 2332 2331 vertex_points = num.concatenate ((x[:,num. NewAxis], y[:,num.NewAxis]), axis=1)2333 vertex_points = num.concatenate ((x[:,num.newaxis], y[:,num.newaxis]), axis=1) 2332 2334 assert len(vertex_points.shape) == 2 2333 2335 2334 grid_points = num.zeros ((ncols*nrows, 2), num. Float)2336 grid_points = num.zeros ((ncols*nrows, 2), num.float) 2335 2337 2336 2338 for i in xrange(nrows): … … 2359 2361 #Interpolate using quantity values 2360 2362 if verbose: print 'Interpolating' 2361 grid_values = interp.interpolate(q, grid_points).flat 2363 grid_values = interp.interpolate(q, grid_points).flatten() 2362 2364 2363 2365 if verbose: 2364 print 'Interpolated values are in [%f, %f]' %(min(grid_values ),2365 max(grid_values ))2366 print 'Interpolated values are in [%f, %f]' %(min(grid_values.flat), 2367 max(grid_values.flat)) 2366 2368 2367 2369 #Assign NODATA_value to all points outside bounding polygon (from interpolation mesh) … … 2631 2633 if verbose: print 'Processing quantity %s' % quantity 2632 2634 2633 # Turn NetCDF objects into Numeric arrays2635 # Turn NetCDF objects into numeric arrays 2634 2636 quantity_dict = {} 2635 2637 for name in fid.variables.keys(): … … 2644 2646 if verbose: print 'Reducing quantity %s' % quantity 2645 2647 2646 q_reduced = num.zeros(number_of_points, num. Float)2648 q_reduced = num.zeros(number_of_points, num.float) 2647 2649 for k in range(number_of_points): 2648 2650 q_reduced[k] = reduction(q[:,k]) … … 2658 2660 2659 2661 # Create grid and update xll/yll corner and x,y 2660 vertex_points = num.concatenate((x[:, num. NewAxis], y[:, num.NewAxis]), axis=1)2662 vertex_points = num.concatenate((x[:, num.newaxis], y[:, num.newaxis]), axis=1) 2661 2663 assert len(vertex_points.shape) == 2 2662 2664 … … 2667 2669 # Interpolate using quantity values 2668 2670 if verbose: print 'Interpolating' 2669 interpolated_values = interp.interpolate(q, data_points).flat 2671 interpolated_values = interp.interpolate(q, data_points).flatten 2670 2672 2671 2673 if verbose: 2672 print 'Interpolated values are in [%f, %f]' % (min(interpolated_values),2673 max(interpolated_values))2674 print 'Interpolated values are in [%f, %f]' \ 2675 % (min(interpolated_values.flat), max(interpolated_values.flat)) 2674 2676 2675 2677 # Assign NODATA_value to all points outside bounding polygon … … 2878 2880 2879 2881 # variable definitions 2880 fid.createVariable('elevation', n um.Float, ('number_of_rows',2881 'number_of_columns'))2882 fid.createVariable('elevation', netcdf_float, ('number_of_rows', 2883 'number_of_columns')) 2882 2884 2883 2885 # Get handles to the variables … … 2959 2961 from Scientific.IO.NetCDF import NetCDFFile 2960 2962 2961 precision = num. Float2963 precision = num.float 2962 2964 2963 2965 msg = 'Must use latitudes and longitudes for minlat, maxlon etc' … … 3078 3080 # elevations = file_e.variables['ELEVATION'][kmin:kmax, lmin:lmax] 3079 3081 # elif latitudes2[0]==latitudes[-1] and latitudes2[-1]==latitudes[0]: 3080 # from Numericimport asarray3082 # from numpy import asarray 3081 3083 # elevations=elevations.tolist() 3082 3084 # elevations.reverse() 3083 3085 # elevations=asarray(elevations) 3084 3086 # else: 3085 # from Numericimport asarray3087 # from numpy import asarray 3086 3088 # elevations=elevations.tolist() 3087 3089 # elevations.reverse() … … 3195 3197 sww.store_header(outfile, times, number_of_volumes, 3196 3198 number_of_points, description=description, 3197 verbose=verbose, sww_precision=n um.Float)3199 verbose=verbose, sww_precision=netcdf_float) 3198 3200 3199 3201 # Store 3200 3202 from anuga.coordinate_transforms.redfearn import redfearn 3201 x = num.zeros(number_of_points, num. Float) #Easting3202 y = num.zeros(number_of_points, num. Float) #Northing3203 x = num.zeros(number_of_points, num.float) #Easting 3204 y = num.zeros(number_of_points, num.float) #Northing 3203 3205 3204 3206 if verbose: print 'Making triangular grid' … … 3234 3236 volumes.append([v4,v3,v2]) #Lower element 3235 3237 3236 volumes = num.array(volumes , num.Int) #array default#3238 volumes = num.array(volumes) 3237 3239 3238 3240 if origin is None: … … 3255 3257 outfile.variables['z'][:] = z #FIXME HACK for bacwards compat. 3256 3258 outfile.variables['elevation'][:] = z 3257 outfile.variables['volumes'][:] = volumes.astype(num. Int32) #For Opteron 643259 outfile.variables['volumes'][:] = volumes.astype(num.int32) #For Opteron 64 3258 3260 3259 3261 #Time stepping … … 3387 3389 d = len(q) 3388 3390 3389 T = num.zeros(N, num. Float) # Time3390 Q = num.zeros((N, d), num. Float) # Values3391 T = num.zeros(N, num.float) # Time 3392 Q = num.zeros((N, d), num.float) # Values 3391 3393 3392 3394 for i, line in enumerate(lines): … … 3424 3426 fid.createDimension('number_of_timesteps', len(T)) 3425 3427 3426 fid.createVariable('time', n um.Float, ('number_of_timesteps',))3428 fid.createVariable('time', netcdf_float, ('number_of_timesteps',)) 3427 3429 3428 3430 fid.variables['time'][:] = T … … 3434 3436 name = 'Attribute%d' % i 3435 3437 3436 fid.createVariable(name, n um.Float, ('number_of_timesteps',))3438 fid.createVariable(name, netcdf_float, ('number_of_timesteps',)) 3437 3439 fid.variables[name][:] = Q[:,i] 3438 3440 … … 3505 3507 time_interp = get_time_interp(time,t) 3506 3508 3507 # Get the variables as Numeric arrays3509 # Get the variables as numeric arrays 3508 3510 x = fid.variables['x'][:] # x-coordinates of vertices 3509 3511 y = fid.variables['y'][:] # y-coordinates of vertices … … 3518 3520 # FIXME (Ole): Something like this might be better: 3519 3521 # concatenate((x, y), axis=1) 3520 # or concatenate((x[:,num. NewAxis], x[:,num.NewAxis]), axis=1)3522 # or concatenate((x[:,num.newaxis], x[:,num.newaxis]), axis=1) 3521 3523 3522 3524 conserved_quantities = [] … … 3706 3708 # @param boundary 3707 3709 def weed(coordinates, volumes, boundary=None): 3708 if type(coordinates) == num.ArrayType:3710 if isinstance(coordinates, num.ndarray): 3709 3711 coordinates = coordinates.tolist() 3710 if type(volumes) == num.ArrayType:3712 if isinstance(volumes, num.ndarray): 3711 3713 volumes = volumes.tolist() 3712 3714 … … 3854 3856 3855 3857 # variable definition 3856 outfile.createVariable('elevation', n um.Float, ('number_of_points',))3858 outfile.createVariable('elevation', netcdf_float, ('number_of_points',)) 3857 3859 3858 3860 # Get handle to the variable … … 3867 3869 3868 3870 lower_index = global_index 3869 telev = num.zeros(ncols_new, num. Float)3871 telev = num.zeros(ncols_new, num.float) 3870 3872 local_index = 0 3871 3873 trow = i * cellsize_ratio … … 3995 3997 from anuga.coordinate_transforms.redfearn import redfearn 3996 3998 3997 precision = n um.Float # So if we want to change the precision its done here3999 precision = netcdf_float # So if we want to change the precision its done here 3998 4000 3999 4001 # go in to the bath dir and load the only file, … … 4096 4098 ################################# 4097 4099 4098 outfile.createVariable('volumes', n um.Int, ('number_of_volumes',4099 'number_of_vertices'))4100 outfile.createVariable('volumes', netcdf_int, ('number_of_volumes', 4101 'number_of_vertices')) 4100 4102 4101 4103 outfile.createVariable('time', precision, ('number_of_timesteps',)) … … 4113 4115 from anuga.coordinate_transforms.redfearn import redfearn 4114 4116 4115 x = num.zeros(number_of_points, num. Float) #Easting4116 y = num.zeros(number_of_points, num. Float) #Northing4117 x = num.zeros(number_of_points, num.float) #Easting 4118 y = num.zeros(number_of_points, num.float) #Northing 4117 4119 4118 4120 if verbose: print 'Making triangular grid' … … 4150 4152 volumes.append([v4,v2,v3]) #Lower element 4151 4153 4152 volumes = num.array(volumes , num.Int) #array default#4154 volumes = num.array(volumes) 4153 4155 4154 4156 geo_ref = Geo_reference(refzone, min(x), min(y)) … … 4175 4177 outfile.variables['z'][:] = z 4176 4178 outfile.variables['elevation'][:] = z 4177 outfile.variables['volumes'][:] = volumes.astype(num. Int32) # On Opteron 644179 outfile.variables['volumes'][:] = volumes.astype(num.int32) # On Opteron 64 4178 4180 4179 4181 stage = outfile.variables['stage'] … … 4367 4369 lat_name = 'LAT' 4368 4370 time_name = 'TIME' 4369 precision = n um.Float # So if we want to change the precision its done here4371 precision = netcdf_float # So if we want to change the precision its done here 4370 4372 4371 4373 ## … … 4648 4650 lonlatdep = p_array.array('f') 4649 4651 lonlatdep.read(mux_file, columns * points_num) 4650 lonlatdep = num.array(lonlatdep, typecode=num.Float)4652 lonlatdep = num.array(lonlatdep, dtype=num.float) 4651 4653 lonlatdep = num.reshape(lonlatdep, (points_num, columns)) 4652 4654 … … 4655 4657 lon_sorted.sort() 4656 4658 4657 if not lon == lon_sorted:4659 if not num.alltrue(lon == lon_sorted): 4658 4660 msg = "Longitudes in mux file are not in ascending order" 4659 4661 raise IOError, msg … … 4661 4663 lat_sorted = list(lat) 4662 4664 lat_sorted.sort() 4663 4664 # UNUSED?4665 ## if not lat == lat_sorted:4666 ## msg = "Latitudes in mux file are not in ascending order"4667 4665 4668 4666 nc_file = Write_nc(quantity, … … 4677 4675 hz_p_array = p_array.array('f') 4678 4676 hz_p_array.read(mux_file, points_num) 4679 hz_p = num.array(hz_p_array, typecode=num.Float)4677 hz_p = num.array(hz_p_array, dtype=num.float) 4680 4678 hz_p = num.reshape(hz_p, (len(lon), len(lat))) 4681 4679 hz_p = num.transpose(hz_p) # mux has lat varying fastest, nc has long v.f. … … 4775 4773 QUANTITY = 2 4776 4774 4777 long_lat_dep = ensure_numeric(long_lat_dep, num. Float)4775 long_lat_dep = ensure_numeric(long_lat_dep, num.float) 4778 4776 4779 4777 num_points = long_lat_dep.shape[0] … … 4813 4811 # FIXME - make this faster/do this a better way 4814 4812 # use numeric transpose, after reshaping the quantity vector 4815 quantity = num.zeros(num_points, num. Float)4813 quantity = num.zeros(num_points, num.float) 4816 4814 4817 4815 for lat_i, _ in enumerate(lat): … … 5266 5264 5267 5265 points_utm=ensure_numeric(points_utm) 5268 assert ensure_numeric(mesh_dic['generatedpointlist']) \5269 == ensure_numeric(points_utm)5266 assert num.alltrue(ensure_numeric(mesh_dic['generatedpointlist']) 5267 == ensure_numeric(points_utm)) 5270 5268 5271 5269 volumes = mesh_dic['generatedtrianglelist'] … … 5285 5283 sww = Write_sww() 5286 5284 sww.store_header(outfile, times, len(volumes), len(points_utm), 5287 verbose=verbose, sww_precision=n um.Float)5285 verbose=verbose, sww_precision=netcdf_float) 5288 5286 outfile.mean_stage = mean_stage 5289 5287 outfile.zscale = zscale … … 5309 5307 xmomentum=xmomentum, 5310 5308 ymomentum=ymomentum, 5311 sww_precision=num. Float)5309 sww_precision=num.float) 5312 5310 j += 1 5313 5311 … … 5356 5354 numSrc = len(filenames) 5357 5355 5358 file_params = -1 * num.ones(3, num. Float) # [nsta,dt,nt]5356 file_params = -1 * num.ones(3, num.float) # [nsta,dt,nt] 5359 5357 5360 5358 # Convert verbose to int C flag … … 5365 5363 5366 5364 if weights is None: 5367 weights = num.ones(numSrc )5365 weights = num.ones(numSrc, num.int) #array default# 5368 5366 5369 5367 if permutation is None: 5370 permutation = ensure_numeric([], num. Float)5368 permutation = ensure_numeric([], num.float) 5371 5369 5372 5370 # Call underlying C implementation urs2sts_ext.c … … 5416 5414 5417 5415 times = dt * num.arange(parameters_index) 5418 latitudes = num.zeros(number_of_selected_stations, num. Float)5419 longitudes = num.zeros(number_of_selected_stations, num. Float)5420 elevation = num.zeros(number_of_selected_stations, num. Float)5421 quantity = num.zeros((number_of_selected_stations, parameters_index), num. Float)5416 latitudes = num.zeros(number_of_selected_stations, num.float) 5417 longitudes = num.zeros(number_of_selected_stations, num.float) 5418 elevation = num.zeros(number_of_selected_stations, num.float) 5419 quantity = num.zeros((number_of_selected_stations, parameters_index), num.float) 5422 5420 5423 5421 starttime = 1e16 … … 5543 5541 if weights is None: 5544 5542 # Default is equal weighting 5545 weights = num.ones(numSrc, num. Float) / numSrc5543 weights = num.ones(numSrc, num.float) / numSrc 5546 5544 else: 5547 5545 weights = ensure_numeric(weights) … … 5665 5663 # 0 to number_of_points-1 5666 5664 if permutation is None: 5667 permutation = num.arange(number_of_points, typecode=num.Int)5665 permutation = num.arange(number_of_points, dtype=num.int) 5668 5666 5669 5667 # NetCDF file definition … … 5679 5677 description=description, 5680 5678 verbose=verbose, 5681 sts_precision=n um.Float)5679 sts_precision=netcdf_float) 5682 5680 5683 5681 # Store 5684 5682 from anuga.coordinate_transforms.redfearn import redfearn 5685 5683 5686 x = num.zeros(number_of_points, num. Float) # Easting5687 y = num.zeros(number_of_points, num. Float) # Northing5684 x = num.zeros(number_of_points, num.float) # Easting 5685 y = num.zeros(number_of_points, num.float) # Northing 5688 5686 5689 5687 # Check zone boundaries … … 5716 5714 5717 5715 elevation = num.resize(elevation, outfile.variables['elevation'][:].shape) 5718 outfile.variables['permutation'][:] = permutation.astype(num. Int32) # Opteron 645716 outfile.variables['permutation'][:] = permutation.astype(num.int32) # Opteron 64 5719 5717 outfile.variables['x'][:] = x - geo_ref.get_xllcorner() 5720 5718 outfile.variables['y'][:] = y - geo_ref.get_yllcorner() … … 5821 5819 # @param smoothing True if smoothing is to be used. 5822 5820 # @param order 5823 # @param sww_precision Data type of the quantitiy to be written (Float32)5821 # @param sww_precision Data type of the quantitiy written (netcdf constant) 5824 5822 # @param verbose True if this function is to be verbose. 5825 5823 # @note If 'times' is a list, the info will be made relative. … … 5832 5830 smoothing=True, 5833 5831 order=1, 5834 sww_precision=n um.Float32,5832 sww_precision=netcdf_float32, 5835 5833 verbose=False): 5836 5834 """Write an SWW file header. … … 5865 5863 # This is being used to seperate one number from a list. 5866 5864 # what it is actually doing is sorting lists from numeric arrays. 5867 if type(times) is list or type(times) is num.ArrayType:5865 if type(times) is list or isinstance(times, num.ndarray): 5868 5866 number_of_times = len(times) 5869 5867 times = ensure_numeric(times) … … 5914 5912 outfile.createVariable('z', sww_precision, ('number_of_points',)) 5915 5913 5916 outfile.createVariable('volumes', n um.Int, ('number_of_volumes',5917 'number_of_vertices'))5914 outfile.createVariable('volumes', netcdf_int, ('number_of_volumes', 5915 'number_of_vertices')) 5918 5916 5919 5917 # Doing sww_precision instead of Float gives cast errors. 5920 outfile.createVariable('time', n um.Float,5918 outfile.createVariable('time', netcdf_float, 5921 5919 ('number_of_timesteps',)) 5922 5920 … … 5932 5930 #outfile.variables[q+Write_sww.RANGE][1] = -max_float # Max 5933 5931 5934 if type(times) is list or type(times) is num.ArrayType:5932 if type(times) is list or isinstance(times, num.ndarray): 5935 5933 outfile.variables['time'][:] = times #Store time relative 5936 5934 … … 6035 6033 outfile.variables['z'][:] = elevation 6036 6034 outfile.variables['elevation'][:] = elevation #FIXME HACK 6037 outfile.variables['volumes'][:] = volumes.astype(num. Int32) #On Opteron 646035 outfile.variables['volumes'][:] = volumes.astype(num.int32) #On Opteron 64 6038 6036 6039 6037 q = 'elevation' … … 6051 6049 # @param verbose True if this function is to be verbose. 6052 6050 # @param **quant 6053 def store_quantities(self, outfile, sww_precision=num. Float32,6051 def store_quantities(self, outfile, sww_precision=num.float32, 6054 6052 slice_index=None, time=None, 6055 6053 verbose=False, **quant): … … 6236 6234 # @param number_of_points The number of URS gauge sites. 6237 6235 # @param description Description string to write into the STS file. 6238 # @param sts_precision Format of data to write ( default Float32).6236 # @param sts_precision Format of data to write (netcdf constant ONLY). 6239 6237 # @param verbose True if this function is to be verbose. 6240 6238 # @note If 'times' is a list, the info will be made relative. … … 6244 6242 number_of_points, 6245 6243 description='Converted from URS mux2 format', 6246 sts_precision=n um.Float32,6244 sts_precision=netcdf_float32, 6247 6245 verbose=False): 6248 6246 """ … … 6267 6265 # This is being used to seperate one number from a list. 6268 6266 # what it is actually doing is sorting lists from numeric arrays. 6269 if type(times) is list or type(times) is num.ArrayType:6267 if type(times) is list or isinstance(times, num.ndarray): 6270 6268 number_of_times = len(times) 6271 6269 times = ensure_numeric(times) … … 6287 6285 6288 6286 # Variable definitions 6289 outfile.createVariable('permutation', n um.Int, ('number_of_points',))6287 outfile.createVariable('permutation', netcdf_int, ('number_of_points',)) 6290 6288 outfile.createVariable('x', sts_precision, ('number_of_points',)) 6291 6289 outfile.createVariable('y', sts_precision, ('number_of_points',)) … … 6302 6300 6303 6301 # Doing sts_precision instead of Float gives cast errors. 6304 outfile.createVariable('time', n um.Float, ('number_of_timesteps',))6302 outfile.createVariable('time', netcdf_float, ('number_of_timesteps',)) 6305 6303 6306 6304 for q in Write_sts.sts_quantities: … … 6314 6312 outfile.variables[q + Write_sts.RANGE][1] = -max_float # Max 6315 6313 6316 if type(times) is list or type(times) is num.ArrayType:6314 if type(times) is list or isinstance(times, num.ndarray): 6317 6315 outfile.variables['time'][:] = times #Store time relative 6318 6316 … … 6423 6421 # @param verboseTrue if this function is to be verbose. 6424 6422 # @param **quant Extra keyword args. 6425 def store_quantities(self, outfile, sts_precision=num. Float32,6423 def store_quantities(self, outfile, sts_precision=num.float32, 6426 6424 slice_index=None, time=None, 6427 6425 verbose=False, **quant): … … 6514 6512 lonlatdep = p_array.array('f') 6515 6513 lonlatdep.read(mux_file, columns * self.points_num) 6516 lonlatdep = num.array(lonlatdep, typecode=num.Float)6514 lonlatdep = num.array(lonlatdep, dtype=num.float) 6517 6515 lonlatdep = num.reshape(lonlatdep, (self.points_num, columns)) 6518 6516 self.lonlatdep = lonlatdep … … 6550 6548 hz_p_array = p_array.array('f') 6551 6549 hz_p_array.read(self.mux_file, self.points_num) 6552 hz_p = num.array(hz_p_array, typecode=num.Float)6550 hz_p = num.array(hz_p_array, dtype=num.float) 6553 6551 self.iter_time_step += 1 6554 6552 … … 6695 6693 # array to store data, number in there is to allow float... 6696 6694 # i'm sure there is a better way! 6697 data = num.array([], typecode=num.Float)6695 data = num.array([], dtype=num.float) 6698 6696 data = num.resize(data, ((len(lines)-1), len(header_fields))) 6699 6697 … … 6861 6859 time += fid.starttime[0] 6862 6860 6863 # Get the variables as Numeric arrays6861 # Get the variables as numeric arrays 6864 6862 x = fid.variables['x'][:] # x-coordinates of nodes 6865 6863 y = fid.variables['y'][:] # y-coordinates of nodes … … 6870 6868 6871 6869 # Mesh (nodes (Mx2), triangles (Nx3)) 6872 nodes = num.concatenate((x[:,num. NewAxis], y[:,num.NewAxis]), axis=1)6870 nodes = num.concatenate((x[:,num.newaxis], y[:,num.newaxis]), axis=1) 6873 6871 triangles = fid.variables['volumes'][:] 6874 6872 … … 7293 7291 7294 7292 # Get the relevant quantities (Convert from single precison) 7295 elevation = num.array(fid.variables['elevation'][:], num. Float)7296 stage = num.array(fid.variables['stage'][:], num. Float)7293 elevation = num.array(fid.variables['elevation'][:], num.float) 7294 stage = num.array(fid.variables['stage'][:], num.float) 7297 7295 7298 7296 # Here's where one could convert nodal information to centroid … … 7311 7309 # and call it here 7312 7310 7313 points = num.concatenate((x[:,num. NewAxis], y[:,num.NewAxis]), axis=1)7311 points = num.concatenate((x[:,num.newaxis], y[:,num.newaxis]), axis=1) 7314 7312 7315 7313 point_indices = inside_polygon(points, polygon) -
branches/numpy/anuga/shallow_water/eq_test.py
r6162 r6304 66 66 67 67 from anuga.abstract_2d_finite_volumes.util import file_function 68 import Numericas num68 import numpy as num 69 69 from pylab import plot, ion, hold,savefig 70 70 … … 75 75 76 76 y = 10000 77 points=num.array([[0]*2]*max , num.Int) #array default#77 points=num.array([[0]*2]*max) 78 78 print points 79 79 half_max_skip=(max*skip)/2 … … 87 87 number_points = profile_lenght/interval 88 88 y = 10000 89 points=num.array([[0]*2]*number_points , num.Int) #array default#89 points=num.array([[0]*2]*number_points) 90 90 print points 91 91 half_profile=profile_lenght/2 -
branches/numpy/anuga/shallow_water/eqf_v2.py
r4436 r6304 26 26 """ 27 27 28 import numpy as num 29 30 28 31 def earthquake_tsunami(length, width, strike, depth, \ 29 32 dip, x0=0.0, y0=0.0, slip=1.0, rake=90.,\ … … 110 113 111 114 from math import sin, cos, radians, exp, cosh 112 from Numeric import zeros, Float113 115 #from okada import okadatest 114 116 … … 142 144 #z1 = okada(xr,yr,depth,length,width,dip,rake,slip) 143 145 144 z2 = zeros(N, Float)146 z2 = num.zeros(N, num.float) 145 147 alp = 0.5 146 148 disl3 = 0.0 … … 182 184 """ 183 185 184 from Numeric import zeros, Float 185 U = zeros(9, Float) 186 DU = zeros(9, Float) 186 U = num.zeros(9, num.float) 187 DU = num.zeros(9, num.float) 187 188 188 189 F0 = 0.0 -
branches/numpy/anuga/shallow_water/shallow_water_domain.py
r6190 r6304 80 80 # $LastChangedBy$ 81 81 82 import Numericas num82 import numpy as num 83 83 84 84 from anuga.abstract_2d_finite_volumes.neighbour_mesh import segment_midpoints … … 1081 1081 self.normals = domain.normals 1082 1082 1083 self.conserved_quantities = num.zeros(3, num. Float)1083 self.conserved_quantities = num.zeros(3, num.float) 1084 1084 1085 1085 def __repr__(self): … … 1501 1501 if callable(f): 1502 1502 N = 3 1503 x = num.ones(3, num. Float)1504 y = num.ones(3, num. Float)1503 x = num.ones(3, num.float) 1504 y = num.ones(3, num.float) 1505 1505 try: 1506 1506 q = f(1.0, x=x, y=y) … … 1511 1511 1512 1512 try: 1513 q = num.array(q, num. Float)1513 q = num.array(q, num.float) 1514 1514 except: 1515 1515 msg = 'Return value from vector function %s could ' %f 1516 msg += 'not be converted into a Numeric array of floats.\n'1516 msg += 'not be converted into a numeric array of floats.\n' 1517 1517 msg += 'Specified function should return either list or array.' 1518 1518 raise msg … … 1520 1520 # Is this really what we want? 1521 1521 msg = 'Return vector from function %s ' %f 1522 msg += 'must have same lenght as input vectors' 1522 msg += 'must have same length as input vectors' 1523 msg += ' (type(q)=%s' % type(q) 1523 1524 assert len(q) == N, msg 1524 1525 … … 1622 1623 1623 1624 try: 1624 s_vec = self.speed * num.ones(N, num. Float)1625 s_vec = self.speed * num.ones(N, num.float) 1625 1626 except: 1626 1627 msg = 'Speed must be either callable or a scalar: %s' %self.s … … 1635 1636 1636 1637 try: 1637 phi_vec = self.phi * num.ones(N, num. Float)1638 phi_vec = self.phi * num.ones(N, num.float) 1638 1639 except: 1639 1640 msg = 'Angle must be either callable or a scalar: %s' %self.phi … … 1712 1713 quantity_name, 1713 1714 rate=0.0, 1714 1715 center=None, radius=None, 1715 1716 polygon=None, 1716 1717 default_rate=None, … … 1775 1776 assert is_inside_polygon(point, bounding_polygon), msg 1776 1777 1777 1778 1778 if polygon is not None: 1779 1779 … … 1835 1835 1836 1836 # Check and store default_rate 1837 1838 1837 msg = 'Keyword argument default_rate must be either None ' 1838 msg += 'or a function of time.\n I got %s' %(str(default_rate)) 1839 1839 assert default_rate is None or \ 1840 1840 type(default_rate) in [IntType, FloatType] or \ … … 1920 1920 1921 1921 """ 1922 1923 1924 1925 1922 if callable(self.rate): 1923 rate = self.rate(t) 1924 else: 1925 rate = self.rate 1926 1926 1927 1927 return rate … … 1964 1964 1965 1965 Used for implementing Rainfall over the entire domain. 1966 1967 1968 1969 1970 1966 1967 Current Limited to only One Gauge.. 1968 1969 Need to add Spatial Varying Capability 1970 (This module came from copying and amending the Inflow Code) 1971 1971 1972 1972 Rainfall(rain) … … 1974 1974 domain 1975 1975 rain [mm/s]: Total rain rate over the specified domain. 1976 1977 1976 NOTE: Raingauge Data needs to reflect the time step. 1977 IE: if Gauge is mm read at a time step, then the input 1978 1978 here is as mm/(timeStep) so 10mm in 5minutes becomes 1979 1979 10/(5x60) = 0.0333mm/s. 1980 1981 1980 1982 1981 This parameter can be either a constant or a 1983 1982 function of time. Positive values indicate inflow, … … 1992 1991 Examples 1993 1992 How to put them in a run File... 1994 1993 1995 1994 #------------------------------------------------------------------------ 1996 1995 # Setup specialised forcing terms … … 2009 2008 def __init__(self, 2010 2009 domain, 2011 2012 2010 rate=0.0, 2011 center=None, radius=None, 2013 2012 polygon=None, 2014 2013 default_rate=None, … … 2071 2070 # The outflow area is 0.07**2*pi=0.0154 m^2 2072 2071 # This corresponds to a rate of change of 0.003/0.0154 = 0.2 m/s 2073 # 2072 # 2074 2073 Inflow((0.7, 0.4), 0.07, -0.003) 2075 2074 … … 2098 2097 def __init__(self, 2099 2098 domain, 2100 2101 2099 rate=0.0, 2100 center=None, radius=None, 2102 2101 polygon=None, 2103 2102 default_rate=None, … … 2123 2122 """ 2124 2123 2125 2126 2127 2128 2124 if callable(self.rate): 2125 _rate = self.rate(t)/self.exchange_area 2126 else: 2127 _rate = self.rate/self.exchange_area 2129 2128 2130 2129 return _rate -
branches/numpy/anuga/shallow_water/shallow_water_ext.c
r5967 r6304 15 15 16 16 #include "Python.h" 17 #include " Numeric/arrayobject.h"17 #include "numpy/arrayobject.h" 18 18 #include "math.h" 19 19 #include <stdio.h> -
branches/numpy/anuga/shallow_water/smf.py
r6157 r6304 47 47 """ 48 48 49 import Numericas num49 import numpy as num 50 50 51 51 … … 388 388 389 389 from math import sin, cos, radians, exp, cosh 390 # from Numeric import zeros, Float391 390 392 391 #ensure vectors x and y have the same length … … 416 415 yr = ((x-x0) * sina + (y-y0) * cosa) + y0 417 416 418 z = num.zeros(N, num. Float)417 z = num.zeros(N, num.float) 419 418 maxz = 0.0 420 419 minz = 0.0 -
branches/numpy/anuga/shallow_water/test_all.py
r3691 r6304 78 78 if __name__ == '__main__': 79 79 suite = regressionTest() 80 runner = unittest.TextTestRunner() # (verbosity=2)80 runner = unittest.TextTestRunner() #verbosity=2) 81 81 runner.run(suite) -
branches/numpy/anuga/shallow_water/test_data_manager.py
r6224 r6304 7 7 import unittest 8 8 import copy 9 import Numericas num9 import numpy as num 10 10 11 11 from anuga.utilities.numerical_tools import mean … … 25 25 from anuga.utilities.system_tools import get_pathname_from_package 26 26 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 27 from anuga.config import netcdf_float 27 28 28 29 # This is needed to run the tests of local functions … … 67 68 #Initial condition - with jumps 68 69 bed = domain.quantities['elevation'].vertex_values 69 stage = num.zeros(bed.shape, num. Float)70 stage = num.zeros(bed.shape, num.float) 70 71 71 72 h = 0.3 … … 109 110 110 111 fid.createDimension(long_name,nx) 111 fid.createVariable(long_name, 'd',(long_name,))112 fid.createVariable(long_name,netcdf_float,(long_name,)) 112 113 fid.variables[long_name].point_spacing='uneven' 113 114 fid.variables[long_name].units='degrees_east' … … 115 116 116 117 fid.createDimension(lat_name,ny) 117 fid.createVariable(lat_name, 'd',(lat_name,))118 fid.createVariable(lat_name,netcdf_float,(lat_name,)) 118 119 fid.variables[lat_name].point_spacing='uneven' 119 120 fid.variables[lat_name].units='degrees_north' … … 121 122 122 123 fid.createDimension('TIME',six) 123 fid.createVariable('TIME', 'd',('TIME',))124 fid.createVariable('TIME',netcdf_float,('TIME',)) 124 125 fid.variables['TIME'].point_spacing='uneven' 125 126 fid.variables['TIME'].units='seconds' … … 129 130 name = ext[1:3].upper() 130 131 if name == 'E.': name = 'ELEVATION' 131 fid.createVariable(name, 'd',('TIME', lat_name, long_name))132 fid.createVariable(name,netcdf_float,('TIME', lat_name, long_name)) 132 133 fid.variables[name].units='CENTIMETERS' 133 134 fid.variables[name].missing_value=-1.e+034 … … 189 190 V = fid.variables['volumes'] 190 191 191 assert num.allclose (x[:], self.X.flat )192 assert num.allclose (y[:], self.Y.flat )193 assert num.allclose (z[:], self.F.flat )192 assert num.allclose (x[:], self.X.flatten()) 193 assert num.allclose (y[:], self.Y.flatten()) 194 assert num.allclose (z[:], self.F.flatten()) 194 195 195 196 P = len(self.domain) … … 521 522 #Check contents 522 523 #Get NetCDF 523 fid = NetCDFFile(sww.filename, inetcdf_mode_r)524 fid = NetCDFFile(sww.filename, netcdf_mode_r) 524 525 525 526 # Get the variables … … 589 590 if t == 0.0: 590 591 assert num.allclose(stage, self.initial_stage) 591 assert num.allclose(stage_file[:], stage.flat )592 assert num.allclose(stage_file[:], stage.flatten()) 592 593 else: 593 594 assert not num.allclose(stage, self.initial_stage) 594 assert not num.allclose(stage_file[:], stage.flat )595 assert not num.allclose(stage_file[:], stage.flatten()) 595 596 596 597 fid.close() … … 855 856 xvec = range(10) 856 857 #z = range(100) 857 z = num.zeros(100 )858 z = num.zeros(100, num.int) #array default# 858 859 NODATA_value = -9999 859 860 count = -1 … … 914 915 915 916 #create new reference points 916 newz = num.zeros(19 )917 newz = num.zeros(19, num.int) #array default# 917 918 newz[0:2] = ref_elevation[32:34] 918 919 newz[2:5] = ref_elevation[35:38] … … 985 986 xvec = range(10) 986 987 #z = range(100) 987 z = num.zeros(100 )988 z = num.zeros(100, num.int) #array default# 988 989 NODATA_value = -9999 989 990 count = -1 … … 1044 1045 1045 1046 #create new reference points 1046 newz = num.zeros(14 )1047 newz = num.zeros(14, num.int) #array default# 1047 1048 newz[0:2] = ref_elevation[32:34] 1048 1049 newz[2:5] = ref_elevation[35:38] … … 2543 2544 2544 2545 bed = domain.quantities['elevation'].vertex_values 2545 stage = num.zeros(bed.shape, num. Float)2546 stage = num.zeros(bed.shape, num.float) 2546 2547 2547 2548 h = 0.3 … … 2793 2794 2794 2795 # Invoke interpolation for vertex points 2795 points = num.concatenate( (x[:,num. NewAxis],y[:,num.NewAxis]), axis=1 )2796 points = num.concatenate( (x[:,num.newaxis],y[:,num.newaxis]), axis=1 ) 2796 2797 sww2pts(self.domain.get_name(), 2797 2798 quantity = 'elevation', … … 3171 3172 for fid in [fid1,fid2,fid3]: 3172 3173 fid.createDimension(long_name,nx) 3173 fid.createVariable(long_name, 'd',(long_name,))3174 fid.createVariable(long_name,netcdf_float,(long_name,)) 3174 3175 fid.variables[long_name].point_spacing='uneven' 3175 3176 fid.variables[long_name].units='degrees_east' … … 3177 3178 3178 3179 fid.createDimension(lat_name,ny) 3179 fid.createVariable(lat_name, 'd',(lat_name,))3180 fid.createVariable(lat_name,netcdf_float,(lat_name,)) 3180 3181 fid.variables[lat_name].point_spacing='uneven' 3181 3182 fid.variables[lat_name].units='degrees_north' … … 3183 3184 3184 3185 fid.createDimension(time_name,2) 3185 fid.createVariable(time_name, 'd',(time_name,))3186 fid.createVariable(time_name,netcdf_float,(time_name,)) 3186 3187 fid.variables[time_name].point_spacing='uneven' 3187 3188 fid.variables[time_name].units='seconds' … … 3192 3193 for fid in [fid4]: 3193 3194 fid.createDimension(long_name,nx) 3194 fid.createVariable(long_name, 'd',(long_name,))3195 fid.createVariable(long_name,netcdf_float,(long_name,)) 3195 3196 fid.variables[long_name].point_spacing='uneven' 3196 3197 fid.variables[long_name].units='degrees_east' … … 3198 3199 3199 3200 fid.createDimension(lat_name,ny) 3200 fid.createVariable(lat_name, 'd',(lat_name,))3201 fid.createVariable(lat_name,netcdf_float,(lat_name,)) 3201 3202 fid.variables[lat_name].point_spacing='uneven' 3202 3203 fid.variables[lat_name].units='degrees_north' … … 3222 3223 3223 3224 for fid in [fid1,fid2,fid3]: 3224 fid.createVariable(name[fid], 'd',(time_name,lat_name,long_name))3225 fid.createVariable(name[fid],netcdf_float,(time_name,lat_name,long_name)) 3225 3226 fid.variables[name[fid]].point_spacing='uneven' 3226 3227 fid.variables[name[fid]].units=units[fid] … … 3230 3231 3231 3232 for fid in [fid4]: 3232 fid.createVariable(name[fid], 'd',(lat_name,long_name))3233 fid.createVariable(name[fid],netcdf_float,(lat_name,long_name)) 3233 3234 fid.variables[name[fid]].point_spacing='uneven' 3234 3235 fid.variables[name[fid]].units=units[fid] … … 3335 3336 for fid in [fid1,fid2,fid3]: 3336 3337 fid.createDimension(long_name,nx) 3337 fid.createVariable(long_name, 'd',(long_name,))3338 fid.createVariable(long_name,netcdf_float,(long_name,)) 3338 3339 fid.variables[long_name].point_spacing='uneven' 3339 3340 fid.variables[long_name].units='degrees_east' … … 3341 3342 3342 3343 fid.createDimension(lat_name,ny) 3343 fid.createVariable(lat_name, 'd',(lat_name,))3344 fid.createVariable(lat_name,netcdf_float,(lat_name,)) 3344 3345 fid.variables[lat_name].point_spacing='uneven' 3345 3346 fid.variables[lat_name].units='degrees_north' … … 3347 3348 3348 3349 fid.createDimension(time_name,2) 3349 fid.createVariable(time_name, 'd',(time_name,))3350 fid.createVariable(time_name,netcdf_float,(time_name,)) 3350 3351 fid.variables[time_name].point_spacing='uneven' 3351 3352 fid.variables[time_name].units='seconds' … … 3356 3357 for fid in [fid4]: 3357 3358 fid.createDimension(long_name,nx) 3358 fid.createVariable(long_name, 'd',(long_name,))3359 fid.createVariable(long_name,netcdf_float,(long_name,)) 3359 3360 fid.variables[long_name].point_spacing='uneven' 3360 3361 fid.variables[long_name].units='degrees_east' … … 3362 3363 3363 3364 fid.createDimension(lat_name,ny) 3364 fid.createVariable(lat_name, 'd',(lat_name,))3365 fid.createVariable(lat_name,netcdf_float,(lat_name,)) 3365 3366 fid.variables[lat_name].point_spacing='uneven' 3366 3367 fid.variables[lat_name].units='degrees_north' … … 3386 3387 3387 3388 for fid in [fid1,fid2,fid3]: 3388 fid.createVariable(name[fid], 'd',(time_name,lat_name,long_name))3389 fid.createVariable(name[fid],netcdf_float,(time_name,lat_name,long_name)) 3389 3390 fid.variables[name[fid]].point_spacing='uneven' 3390 3391 fid.variables[name[fid]].units=units[fid] … … 3394 3395 3395 3396 for fid in [fid4]: 3396 fid.createVariable(name[fid], 'd',(lat_name,long_name))3397 fid.createVariable(name[fid],netcdf_float,(lat_name,long_name)) 3397 3398 fid.variables[name[fid]].point_spacing='uneven' 3398 3399 fid.variables[name[fid]].units=units[fid] … … 3966 3967 fid.createDimension('number_of_points', nrows*ncols) 3967 3968 3968 fid.createVariable('elevation', n um.Float, ('number_of_points',))3969 fid.createVariable('elevation', netcdf_float, ('number_of_points',)) 3969 3970 3970 3971 elevation = fid.variables['elevation'] … … 3993 3994 3994 3995 #generate a stencil for computing the decimated values 3995 stencil = num.ones((3,3), num. Float) / 9.03996 stencil = num.ones((3,3), num.float) / 9.0 3996 3997 3997 3998 decimate_dem(root, stencil=stencil, cellsize_new=100) … … 4049 4050 fid.createDimension('number_of_points', nrows*ncols) 4050 4051 4051 fid.createVariable('elevation', n um.Float, ('number_of_points',))4052 fid.createVariable('elevation', netcdf_float, ('number_of_points',)) 4052 4053 4053 4054 elevation = fid.variables['elevation'] … … 4087 4088 4088 4089 #generate a stencil for computing the decimated values 4089 stencil = num.ones((3,3), num. Float) / 9.04090 stencil = num.ones((3,3), num.float) / 9.0 4090 4091 4091 4092 decimate_dem(root, stencil=stencil, cellsize_new=100) … … 4950 4951 4951 4952 ## 7th test 4952 m2d = num.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]] , num.Int) #array default#4953 m2d = num.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]) 4953 4954 kmin, kmax, lmin, lmax = data_manager._get_min_max_indexes( 4954 4955 latitudes,longitudes, … … 4963 4964 #print "longitudes_news",longitudes_news 4964 4965 4965 self.failUnless(latitudes_new == [2, 1] and \ 4966 longitudes_news == [10, 20], 4967 'failed') 4968 4969 self.failUnless(m2d == [[5,6],[9,10]], 4970 'failed') 4966 self.failUnless(num.alltrue(latitudes_new == [2, 1]) and 4967 num.alltrue(longitudes_news == [10, 20]), 4968 'failed') 4969 4970 self.failUnless(num.alltrue(m2d == [[5,6],[9,10]]), 'failed') 4971 4971 4972 4972 def test_get_min_max_indexes_lat_ascending(self): … … 5010 5010 longitudes = [148,149,150,151] 5011 5011 5012 m2d = num.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]] , num.Int) #array default#5012 m2d = num.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]) 5013 5013 5014 5014 # k - lat … … 5031 5031 #print "longitudes_new",longitudes_new 5032 5032 5033 self.failUnless(latitudes_new == [-30, -35, -40] and \5033 self.failUnless(latitudes_new == [-30, -35, -40] and 5034 5034 longitudes_new == [148, 149,150], 5035 5036 self.failUnless( m2d == [[0,1,2],[4,5,6],[8,9,10]],5037 5035 'failed') 5036 self.failUnless(num.alltrue(m2d == [[0,1,2],[4,5,6],[8,9,10]]), 5037 'failed') 5038 5038 5039 5039 def test_get_min_max_indexes3(self): … … 5477 5477 quantities_init[i] = ensure_numeric(quantities_init[i]) 5478 5478 #print "HA_init", HA_init 5479 q_time = num.zeros((time_step_count, points_num), num. Float)5479 q_time = num.zeros((time_step_count, points_num), num.float) 5480 5480 for time in range(time_step_count): 5481 5481 q_time[time,:] = quantities_init[i] #* time * 4 … … 5561 5561 quantities_init[i] = ensure_numeric(quantities_init[i]) 5562 5562 #print "HA_init", HA_init 5563 q_time = num.zeros((time_step_count, points_num), num. Float)5563 q_time = num.zeros((time_step_count, points_num), num.float) 5564 5564 for time in range(time_step_count): 5565 5565 q_time[time,:] = quantities_init[i] #* time * 4 … … 6017 6017 if ha is None: 6018 6018 this_ha = e 6019 quantities_init[0].append(num.ones(time_step_count,num. Float)*this_ha) # HA6019 quantities_init[0].append(num.ones(time_step_count,num.float)*this_ha) # HA 6020 6020 else: 6021 6021 quantities_init[0].append(ha[i]) 6022 6022 if ua is None: 6023 6023 this_ua = n 6024 quantities_init[1].append(num.ones(time_step_count,num. Float)*this_ua) # UA6024 quantities_init[1].append(num.ones(time_step_count,num.float)*this_ua) # UA 6025 6025 else: 6026 6026 quantities_init[1].append(ua[i]) 6027 6027 if va is None: 6028 6028 this_va = e 6029 quantities_init[2].append(num.ones(time_step_count,num. Float)*this_va) #6029 quantities_init[2].append(num.ones(time_step_count,num.float)*this_va) # 6030 6030 else: 6031 6031 quantities_init[2].append(va[i]) … … 6037 6037 files = [] 6038 6038 for i, q in enumerate(quantities): 6039 q_time = num.zeros((time_step_count, points_num), num. Float)6039 q_time = num.zeros((time_step_count, points_num), num.float) 6040 6040 quantities_init[i] = ensure_numeric(quantities_init[i]) 6041 6041 for time in range(time_step_count): … … 6106 6106 lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)] 6107 6107 n=len(lat_long_points) 6108 first_tstep=num.ones(n,num. Int)6109 last_tstep=time_step_count*num.ones(n,num. Int)6110 depth=20*num.ones(n,num. Float)6111 ha=2*num.ones((n,time_step_count),num. Float)6112 ua=5*num.ones((n,time_step_count),num. Float)6113 va=-10*num.ones((n,time_step_count),num. Float)6108 first_tstep=num.ones(n,num.int) 6109 last_tstep=time_step_count*num.ones(n,num.int) 6110 depth=20*num.ones(n,num.float) 6111 ha=2*num.ones((n,time_step_count),num.float) 6112 ua=5*num.ones((n,time_step_count),num.float) 6113 va=-10*num.ones((n,time_step_count),num.float) 6114 6114 #-ve added to take into account mux file format where south is positive. 6115 6115 base_name, files = self.write_mux2(lat_long_points, … … 6121 6121 va=va) 6122 6122 6123 weights=num.ones(1, num. Float)6123 weights=num.ones(1, num.float) 6124 6124 #ensure that files are indeed mux2 files 6125 6125 times, latitudes, longitudes, elevation, stage, starttime = read_mux2_py([files[0]],weights) … … 6161 6161 lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)] 6162 6162 n=len(lat_long_points) 6163 first_tstep=num.ones(n,num. Int)6164 last_tstep=(time_step_count)*num.ones(n,num. Int)6165 depth=20*num.ones(n,num. Float)6166 ha=2*num.ones((n,time_step_count),num. Float)6163 first_tstep=num.ones(n,num.int) 6164 last_tstep=(time_step_count)*num.ones(n,num.int) 6165 depth=20*num.ones(n,num.float) 6166 ha=2*num.ones((n,time_step_count),num.float) 6167 6167 ha[0]=num.arange(0,time_step_count)+1 6168 6168 ha[1]=time_step_count-num.arange(1,time_step_count+1) … … 6170 6170 ha[2]=num.arange(2*time_step_count,3*time_step_count) 6171 6171 ha[3]=num.arange(3*time_step_count,4*time_step_count) 6172 ua=5*num.ones((n,time_step_count),num. Float)6173 va=-10*num.ones((n,time_step_count),num. Float)6172 ua=5*num.ones((n,time_step_count),num.float) 6173 va=-10*num.ones((n,time_step_count),num.float) 6174 6174 #-ve added to take into account mux file format where south is positive. 6175 6175 base_name, files = self.write_mux2(lat_long_points, … … 6181 6181 va=va) 6182 6182 6183 weights=num.ones(1, num. Float)6183 weights=num.ones(1, num.float) 6184 6184 #ensure that files are indeed mux2 files 6185 6185 times, latitudes, longitudes, elevation, stage,starttime=read_mux2_py([files[0]],weights) … … 6219 6219 lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)] 6220 6220 n=len(lat_long_points) 6221 first_tstep=num.ones(n,num. Int)6221 first_tstep=num.ones(n,num.int) 6222 6222 first_tstep[0]+=1 6223 6223 first_tstep[2]+=1 6224 last_tstep=(time_step_count)*num.ones(n,num. Int)6224 last_tstep=(time_step_count)*num.ones(n,num.int) 6225 6225 last_tstep[0]-=1 6226 6226 6227 depth=20*num.ones(n,num. Float)6228 ha=2*num.ones((n,time_step_count),num. Float)6227 depth=20*num.ones(n,num.float) 6228 ha=2*num.ones((n,time_step_count),num.float) 6229 6229 ha[0]=num.arange(0,time_step_count) 6230 6230 ha[1]=num.arange(time_step_count,2*time_step_count) 6231 6231 ha[2]=num.arange(2*time_step_count,3*time_step_count) 6232 6232 ha[3]=num.arange(3*time_step_count,4*time_step_count) 6233 ua=5*num.ones((n,time_step_count),num. Float)6234 va=-10*num.ones((n,time_step_count),num. Float)6233 ua=5*num.ones((n,time_step_count),num.float) 6234 va=-10*num.ones((n,time_step_count),num.float) 6235 6235 #-ve added to take into account mux file format where south is positive. 6236 6236 base_name, files = self.write_mux2(lat_long_points, … … 6242 6242 va=va) 6243 6243 6244 weights=num.ones(1, num. Float)6244 weights=num.ones(1, num.float) 6245 6245 #ensure that files are indeed mux2 files 6246 6246 times, latitudes, longitudes, elevation, stage, starttime=read_mux2_py([files[0]],weights) … … 6308 6308 6309 6309 # Create different timeseries starting and ending at different times 6310 first_tstep=num.ones(n, num. Int)6310 first_tstep=num.ones(n, num.int) 6311 6311 first_tstep[0]+=2 # Point 0 starts at 2 6312 6312 first_tstep[1]+=4 # Point 1 starts at 4 6313 6313 first_tstep[2]+=3 # Point 2 starts at 3 6314 6314 6315 last_tstep=(time_step_count)*num.ones(n,num. Int)6315 last_tstep=(time_step_count)*num.ones(n,num.int) 6316 6316 last_tstep[0]-=1 # Point 0 ends 1 step early 6317 6317 last_tstep[1]-=2 # Point 1 ends 2 steps early … … 6319 6319 6320 6320 # Create varying elevation data (positive values for seafloor) 6321 gauge_depth=20*num.ones(n,num. Float)6321 gauge_depth=20*num.ones(n,num.float) 6322 6322 for i in range(n): 6323 6323 gauge_depth[i] += i**2 6324 6324 6325 6325 # Create data to be written to first mux file 6326 ha0=2*num.ones((n,time_step_count),num. Float)6326 ha0=2*num.ones((n,time_step_count),num.float) 6327 6327 ha0[0]=num.arange(0,time_step_count) 6328 6328 ha0[1]=num.arange(time_step_count,2*time_step_count) 6329 6329 ha0[2]=num.arange(2*time_step_count,3*time_step_count) 6330 6330 ha0[3]=num.arange(3*time_step_count,4*time_step_count) 6331 ua0=5*num.ones((n,time_step_count),num. Float)6332 va0=-10*num.ones((n,time_step_count),num. Float)6331 ua0=5*num.ones((n,time_step_count),num.float) 6332 va0=-10*num.ones((n,time_step_count),num.float) 6333 6333 6334 6334 # Ensure data used to write mux file to be zero when gauges are … … 6369 6369 # For each quantity read the associated list of source mux2 file with 6370 6370 # extention associated with that quantity 6371 file_params=-1*num.ones(3,num. Float) #[nsta,dt,nt]6371 file_params=-1*num.ones(3,num.float) #[nsta,dt,nt] 6372 6372 OFFSET = 5 6373 6373 … … 6414 6414 6415 6415 # Create different timeseries starting and ending at different times 6416 first_tstep=num.ones(n,num. Int)6416 first_tstep=num.ones(n,num.int) 6417 6417 first_tstep[0]+=2 # Point 0 starts at 2 6418 6418 first_tstep[1]+=4 # Point 1 starts at 4 6419 6419 first_tstep[2]+=3 # Point 2 starts at 3 6420 6420 6421 last_tstep=(time_step_count)*num.ones(n,num. Int)6421 last_tstep=(time_step_count)*num.ones(n,num.int) 6422 6422 last_tstep[0]-=1 # Point 0 ends 1 step early 6423 6423 last_tstep[1]-=2 # Point 1 ends 2 steps early … … 6425 6425 6426 6426 # Create varying elevation data (positive values for seafloor) 6427 gauge_depth=20*num.ones(n,num. Float)6427 gauge_depth=20*num.ones(n,num.float) 6428 6428 for i in range(n): 6429 6429 gauge_depth[i] += i**2 6430 6430 6431 6431 # Create data to be written to second mux file 6432 ha1=num.ones((n,time_step_count),num. Float)6432 ha1=num.ones((n,time_step_count),num.float) 6433 6433 ha1[0]=num.sin(times_ref) 6434 6434 ha1[1]=2*num.sin(times_ref - 3) … … 6437 6437 ha1[4]=num.sin(2*times_ref-0.7) 6438 6438 6439 ua1=num.zeros((n,time_step_count),num. Float)6439 ua1=num.zeros((n,time_step_count),num.float) 6440 6440 ua1[0]=3*num.cos(times_ref) 6441 6441 ua1[1]=2*num.sin(times_ref-0.7) … … 6443 6443 ua1[4]=2*num.ones(time_step_count) 6444 6444 6445 va1=num.zeros((n,time_step_count),num. Float)6445 va1=num.zeros((n,time_step_count),num.float) 6446 6446 va1[0]=2*num.cos(times_ref-0.87) 6447 6447 va1[1]=3*num.ones(time_step_count) … … 6516 6516 if ha is None: 6517 6517 this_ha = e 6518 quantities_init[0].append(num.ones(time_step_count,num. Float)*this_ha) # HA6518 quantities_init[0].append(num.ones(time_step_count,num.float)*this_ha) # HA 6519 6519 else: 6520 6520 quantities_init[0].append(ha[i]) 6521 6521 if ua is None: 6522 6522 this_ua = n 6523 quantities_init[1].append(num.ones(time_step_count,num. Float)*this_ua) # UA6523 quantities_init[1].append(num.ones(time_step_count,num.float)*this_ua) # UA 6524 6524 else: 6525 6525 quantities_init[1].append(ua[i]) 6526 6526 if va is None: 6527 6527 this_va = e 6528 quantities_init[2].append(num.ones(time_step_count,num. Float)*this_va) #6528 quantities_init[2].append(num.ones(time_step_count,num.float)*this_va) # 6529 6529 else: 6530 6530 quantities_init[2].append(va[i]) … … 6534 6534 #print i, q 6535 6535 6536 q_time = num.zeros((time_step_count, points_num), num. Float)6536 q_time = num.zeros((time_step_count, points_num), num.float) 6537 6537 quantities_init[i] = ensure_numeric(quantities_init[i]) 6538 6538 for time in range(time_step_count): … … 6620 6620 # For each quantity read the associated list of source mux2 file with 6621 6621 # extention associated with that quantity 6622 file_params=-1*num.ones(3,num. Float) # [nsta,dt,nt]6622 file_params=-1*num.ones(3,num.float) # [nsta,dt,nt] 6623 6623 OFFSET = 5 6624 6624 … … 6639 6639 parameters_index = data.shape[1]-OFFSET 6640 6640 6641 quantity=num.zeros((number_of_selected_stations, parameters_index), num. Float)6641 quantity=num.zeros((number_of_selected_stations, parameters_index), num.float) 6642 6642 6643 6643 … … 6674 6674 lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)] 6675 6675 n=len(lat_long_points) 6676 first_tstep=num.ones(n,num. Int)6676 first_tstep=num.ones(n,num.int) 6677 6677 first_tstep[0]+=1 6678 6678 first_tstep[2]+=1 6679 last_tstep=(time_step_count)*num.ones(n,num. Int)6679 last_tstep=(time_step_count)*num.ones(n,num.int) 6680 6680 last_tstep[0]-=1 6681 6681 6682 gauge_depth=20*num.ones(n,num. Float)6683 ha=2*num.ones((n,time_step_count),num. Float)6682 gauge_depth=20*num.ones(n,num.float) 6683 ha=2*num.ones((n,time_step_count),num.float) 6684 6684 ha[0]=num.arange(0,time_step_count) 6685 6685 ha[1]=num.arange(time_step_count,2*time_step_count) 6686 6686 ha[2]=num.arange(2*time_step_count,3*time_step_count) 6687 6687 ha[3]=num.arange(3*time_step_count,4*time_step_count) 6688 ua=5*num.ones((n,time_step_count),num. Float)6689 va=-10*num.ones((n,time_step_count),num. Float)6688 ua=5*num.ones((n,time_step_count),num.float) 6689 va=-10*num.ones((n,time_step_count),num.float) 6690 6690 6691 6691 base_name, files = self.write_mux2(lat_long_points, … … 6760 6760 #momentum = velocity_ua *(stage+depth) 6761 6761 6762 depth=num.zeros((len(lat_long_points),time_step_count),num. Float)6762 depth=num.zeros((len(lat_long_points),time_step_count),num.float) 6763 6763 for i in range(len(lat_long_points)): 6764 6764 depth[i]=gauge_depth[i]+tide+ha[i] … … 6789 6789 lat_long_points =[(-21.,114.5),(-21.,113.5),(-21.,114.), (-21.,115.)] 6790 6790 n=len(lat_long_points) 6791 first_tstep=num.ones(n,num. Int)6791 first_tstep=num.ones(n,num.int) 6792 6792 first_tstep[0]+=1 6793 6793 first_tstep[2]+=1 6794 last_tstep=(time_step_count)*num.ones(n,num. Int)6794 last_tstep=(time_step_count)*num.ones(n,num.int) 6795 6795 last_tstep[0]-=1 6796 6796 6797 gauge_depth=20*num.ones(n,num. Float)6798 ha=2*num.ones((n,time_step_count),num. Float)6797 gauge_depth=20*num.ones(n,num.float) 6798 ha=2*num.ones((n,time_step_count),num.float) 6799 6799 ha[0]=num.arange(0,time_step_count) 6800 6800 ha[1]=num.arange(time_step_count,2*time_step_count) 6801 6801 ha[2]=num.arange(2*time_step_count,3*time_step_count) 6802 6802 ha[3]=num.arange(3*time_step_count,4*time_step_count) 6803 ua=5*num.ones((n,time_step_count),num. Float)6804 va=-10*num.ones((n,time_step_count),num. Float)6803 ua=5*num.ones((n,time_step_count),num.float) 6804 va=-10*num.ones((n,time_step_count),num.float) 6805 6805 6806 6806 base_name, files = self.write_mux2(lat_long_points, … … 6851 6851 lat_long_points =[(-21.,113.5),(-21.,114.5),(-21.,114.), (-21.,115.)] 6852 6852 n=len(lat_long_points) 6853 first_tstep=num.ones(n,num. Int)6853 first_tstep=num.ones(n,num.int) 6854 6854 first_tstep[0]+=1 6855 6855 first_tstep[2]+=1 6856 last_tstep=(time_step_count)*num.ones(n,num. Int)6856 last_tstep=(time_step_count)*num.ones(n,num.int) 6857 6857 last_tstep[0]-=1 6858 6858 6859 gauge_depth=20*num.ones(n,num. Float)6860 ha=2*num.ones((n,time_step_count),num. Float)6859 gauge_depth=20*num.ones(n,num.float) 6860 ha=2*num.ones((n,time_step_count),num.float) 6861 6861 ha[0]=num.arange(0,time_step_count) 6862 6862 ha[1]=num.arange(time_step_count,2*time_step_count) 6863 6863 ha[2]=num.arange(2*time_step_count,3*time_step_count) 6864 6864 ha[3]=num.arange(3*time_step_count,4*time_step_count) 6865 ua=5*num.ones((n,time_step_count),num. Float)6866 va=-10*num.ones((n,time_step_count),num. Float)6865 ua=5*num.ones((n,time_step_count),num.float) 6866 va=-10*num.ones((n,time_step_count),num.float) 6867 6867 6868 6868 base_name, files = self.write_mux2(lat_long_points, … … 6914 6914 lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)] 6915 6915 n=len(lat_long_points) 6916 first_tstep=num.ones(n,num. Int)6916 first_tstep=num.ones(n,num.int) 6917 6917 first_tstep[0]+=1 6918 6918 first_tstep[2]+=1 6919 last_tstep=(time_step_count)*num.ones(n,num. Int)6919 last_tstep=(time_step_count)*num.ones(n,num.int) 6920 6920 last_tstep[0]-=1 6921 6921 6922 gauge_depth=20*num.ones(n,num. Float)6923 ha=2*num.ones((n,time_step_count),num. Float)6922 gauge_depth=20*num.ones(n,num.float) 6923 ha=2*num.ones((n,time_step_count),num.float) 6924 6924 ha[0]=num.arange(0,time_step_count) 6925 6925 ha[1]=num.arange(time_step_count,2*time_step_count) 6926 6926 ha[2]=num.arange(2*time_step_count,3*time_step_count) 6927 6927 ha[3]=num.arange(3*time_step_count,4*time_step_count) 6928 ua=5*num.ones((n,time_step_count),num. Float)6929 va=-10*num.ones((n,time_step_count),num. Float)6928 ua=5*num.ones((n,time_step_count),num.float) 6929 va=-10*num.ones((n,time_step_count),num.float) 6930 6930 6931 6931 # Create two identical mux files to be combined by urs2sts … … 7016 7016 #momentum = velocity_ua *(stage+depth) 7017 7017 7018 depth=num.zeros((len(lat_long_points),time_step_count),num. Float)7018 depth=num.zeros((len(lat_long_points),time_step_count),num.float) 7019 7019 for i in range(len(lat_long_points)): 7020 7020 depth[i]=gauge_depth[i]+tide+2.0*ha[i] … … 7386 7386 lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)] 7387 7387 n=len(lat_long_points) 7388 first_tstep=num.ones(n,num. Int)7388 first_tstep=num.ones(n,num.int) 7389 7389 first_tstep[0]+=1 7390 7390 first_tstep[2]+=1 7391 last_tstep=(time_step_count)*num.ones(n,num. Int)7391 last_tstep=(time_step_count)*num.ones(n,num.int) 7392 7392 last_tstep[0]-=1 7393 7393 7394 gauge_depth=20*num.ones(n,num. Float)7395 ha=2*num.ones((n,time_step_count),num. Float)7394 gauge_depth=20*num.ones(n,num.float) 7395 ha=2*num.ones((n,time_step_count),num.float) 7396 7396 ha[0]=num.arange(0,time_step_count) 7397 7397 ha[1]=num.arange(time_step_count,2*time_step_count) 7398 7398 ha[2]=num.arange(2*time_step_count,3*time_step_count) 7399 7399 ha[3]=num.arange(3*time_step_count,4*time_step_count) 7400 ua=5*num.ones((n,time_step_count),num. Float)7401 va=-10*num.ones((n,time_step_count),num. Float)7400 ua=5*num.ones((n,time_step_count),num.float) 7401 va=-10*num.ones((n,time_step_count),num.float) 7402 7402 7403 7403 # Create two identical mux files to be combined by urs2sts … … 7530 7530 #momentum = velocity_ua *(stage+depth) 7531 7531 7532 depth=num.zeros((len(lat_long_points),time_step_count),num. Float)7532 depth=num.zeros((len(lat_long_points),time_step_count),num.float) 7533 7533 for i in range(len(lat_long_points)): 7534 7534 depth[i]=gauge_depth[i]+tide+2.0*ha[i] … … 7573 7573 lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)] 7574 7574 n=len(lat_long_points) 7575 first_tstep=num.ones(n,num. Int)7575 first_tstep=num.ones(n,num.int) 7576 7576 first_tstep[0]+=1 7577 7577 first_tstep[2]+=1 7578 last_tstep=(time_step_count)*num.ones(n,num. Int)7578 last_tstep=(time_step_count)*num.ones(n,num.int) 7579 7579 last_tstep[0]-=1 7580 7580 7581 gauge_depth=20*num.ones(n,num. Float)7582 ha=2*num.ones((n,time_step_count),num. Float)7581 gauge_depth=20*num.ones(n,num.float) 7582 ha=2*num.ones((n,time_step_count),num.float) 7583 7583 ha[0]=num.arange(0,time_step_count) 7584 7584 ha[1]=num.arange(time_step_count,2*time_step_count) 7585 7585 ha[2]=num.arange(2*time_step_count,3*time_step_count) 7586 7586 ha[3]=num.arange(3*time_step_count,4*time_step_count) 7587 ua=5*num.ones((n,time_step_count),num. Float)7588 va=-10*num.ones((n,time_step_count),num. Float)7587 ua=5*num.ones((n,time_step_count),num.float) 7588 va=-10*num.ones((n,time_step_count),num.float) 7589 7589 7590 7590 # Create two identical mux files to be combined by urs2sts … … 7669 7669 7670 7670 # Create different timeseries starting and ending at different times 7671 first_tstep=num.ones(n,num. Int)7671 first_tstep=num.ones(n,num.int) 7672 7672 first_tstep[0]+=2 # Point 0 starts at 2 7673 7673 first_tstep[1]+=4 # Point 1 starts at 4 7674 7674 first_tstep[2]+=3 # Point 2 starts at 3 7675 7675 7676 last_tstep=(time_step_count)*num.ones(n,num. Int)7676 last_tstep=(time_step_count)*num.ones(n,num.int) 7677 7677 last_tstep[0]-=1 # Point 0 ends 1 step early 7678 7678 last_tstep[1]-=2 # Point 1 ends 2 steps early … … 7687 7687 7688 7688 # Create varying elevation data (positive values for seafloor) 7689 gauge_depth=20*num.ones(n,num. Float)7689 gauge_depth=20*num.ones(n,num.float) 7690 7690 for i in range(n): 7691 7691 gauge_depth[i] += i**2 … … 7694 7694 7695 7695 # Create data to be written to first mux file 7696 ha0=2*num.ones((n,time_step_count),num. Float)7696 ha0=2*num.ones((n,time_step_count),num.float) 7697 7697 ha0[0]=num.arange(0,time_step_count) 7698 7698 ha0[1]=num.arange(time_step_count,2*time_step_count) 7699 7699 ha0[2]=num.arange(2*time_step_count,3*time_step_count) 7700 7700 ha0[3]=num.arange(3*time_step_count,4*time_step_count) 7701 ua0=5*num.ones((n,time_step_count),num. Float)7702 va0=-10*num.ones((n,time_step_count),num. Float)7701 ua0=5*num.ones((n,time_step_count),num.float) 7702 va0=-10*num.ones((n,time_step_count),num.float) 7703 7703 7704 7704 # Ensure data used to write mux file to be zero when gauges are … … 7731 7731 7732 7732 # Create data to be written to second mux file 7733 ha1=num.ones((n,time_step_count),num. Float)7733 ha1=num.ones((n,time_step_count),num.float) 7734 7734 ha1[0]=num.sin(times_ref) 7735 7735 ha1[1]=2*num.sin(times_ref - 3) … … 7738 7738 ha1[4]=num.sin(2*times_ref-0.7) 7739 7739 7740 ua1=num.zeros((n,time_step_count),num. Float)7740 ua1=num.zeros((n,time_step_count),num.float) 7741 7741 ua1[0]=3*num.cos(times_ref) 7742 7742 ua1[1]=2*num.sin(times_ref-0.7) … … 7744 7744 ua1[4]=2*num.ones(time_step_count) 7745 7745 7746 va1=num.zeros((n,time_step_count),num. Float)7746 va1=num.zeros((n,time_step_count),num.float) 7747 7747 va1[0]=2*num.cos(times_ref-0.87) 7748 va1[1]=3*num.ones(time_step_count )7748 va1[1]=3*num.ones(time_step_count, num.int) #array default# 7749 7749 va1[3]=2*num.sin(times_ref-0.71) 7750 7750 … … 7873 7873 #momentum = velocity_ua *(stage+depth) 7874 7874 7875 depth_ref = num.zeros((len(permutation), time_step_count), num. Float)7875 depth_ref = num.zeros((len(permutation), time_step_count), num.float) 7876 7876 for i in range(len(permutation)): 7877 7877 depth_ref[i]=gauge_depth_ref[i]+tide+ha_ref[i] … … 7986 7986 #momentum = velocity_ua *(stage+depth) 7987 7987 7988 depth_ref = num.zeros((len(permutation), time_step_count), num. Float)7988 depth_ref = num.zeros((len(permutation), time_step_count), num.float) 7989 7989 for i in range(len(permutation)): 7990 7990 depth_ref[i]=gauge_depth_ref[i]+tide+ha_ref[i] … … 8092 8092 #momentum = velocity_ua *(stage+depth) 8093 8093 8094 depth_ref = num.zeros((len(permutation), time_step_count), num. Float)8094 depth_ref = num.zeros((len(permutation), time_step_count), num.float) 8095 8095 for i in range(len(permutation)): 8096 8096 depth_ref[i]=gauge_depth_ref[i]+tide+ha_ref[i] … … 8161 8161 lat_long_points =bounding_polygon[0:3] 8162 8162 n=len(lat_long_points) 8163 first_tstep=num.ones(n,num. Int)8164 last_tstep=(time_step_count)*num.ones(n,num. Int)8163 first_tstep=num.ones(n,num.int) 8164 last_tstep=(time_step_count)*num.ones(n,num.int) 8165 8165 8166 8166 h = 20 … … 8168 8168 u = 10 8169 8169 v = -10 8170 gauge_depth=h*num.ones(n,num. Float)8171 ha=w*num.ones((n,time_step_count),num. Float)8172 ua=u*num.ones((n,time_step_count),num. Float)8173 va=v*num.ones((n,time_step_count),num. Float)8170 gauge_depth=h*num.ones(n,num.float) 8171 ha=w*num.ones((n,time_step_count),num.float) 8172 ua=u*num.ones((n,time_step_count),num.float) 8173 va=v*num.ones((n,time_step_count),num.float) 8174 8174 base_name, files = self.write_mux2(lat_long_points, 8175 8175 time_step_count, time_step, … … 8224 8224 finaltime=time_step*(time_step_count-1) 8225 8225 yieldstep=time_step 8226 temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num. Float)8226 temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num.float) 8227 8227 8228 8228 for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep, … … 8250 8250 8251 8251 domain_drchlt.set_boundary({'ocean': Bd,'otherocean': Br}) 8252 temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num. Float)8252 temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num.float) 8253 8253 8254 8254 for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep, … … 8305 8305 lat_long_points = bounding_polygon[0:3] 8306 8306 n=len(lat_long_points) 8307 first_tstep=num.ones(n,num. Int)8308 last_tstep=(time_step_count)*num.ones(n,num. Int)8307 first_tstep=num.ones(n,num.int) 8308 last_tstep=(time_step_count)*num.ones(n,num.int) 8309 8309 8310 8310 h = 20 … … 8312 8312 u = 10 8313 8313 v = -10 8314 gauge_depth=h*num.ones(n,num. Float)8315 ha=w*num.ones((n,time_step_count),num. Float)8316 ua=u*num.ones((n,time_step_count),num. Float)8317 va=v*num.ones((n,time_step_count),num. Float)8314 gauge_depth=h*num.ones(n,num.float) 8315 ha=w*num.ones((n,time_step_count),num.float) 8316 ua=u*num.ones((n,time_step_count),num.float) 8317 va=v*num.ones((n,time_step_count),num.float) 8318 8318 base_name, files = self.write_mux2(lat_long_points, 8319 8319 time_step_count, time_step, … … 8377 8377 finaltime = data_finaltime + 10 # Let model time exceed available data 8378 8378 yieldstep = time_step 8379 temp_fbound=num.zeros(int(finaltime/yieldstep)+1, num. Float)8379 temp_fbound=num.zeros(int(finaltime/yieldstep)+1, num.float) 8380 8380 8381 8381 for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep, … … 8409 8409 8410 8410 domain_drchlt.set_boundary({'ocean': Bd,'otherocean': Br}) 8411 temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num. Float)8411 temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num.float) 8412 8412 8413 8413 for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep, … … 8463 8463 lat_long_points = bounding_polygon[0:3] 8464 8464 n=len(lat_long_points) 8465 first_tstep=num.ones(n,num. Int)8466 last_tstep=(time_step_count)*num.ones(n,num. Int)8465 first_tstep=num.ones(n,num.int) 8466 last_tstep=(time_step_count)*num.ones(n,num.int) 8467 8467 8468 8468 h = 20 … … 8470 8470 u = 10 8471 8471 v = -10 8472 gauge_depth=h*num.ones(n,num. Float)8473 ha=w*num.ones((n,time_step_count),num. Float)8474 ua=u*num.ones((n,time_step_count),num. Float)8475 va=v*num.ones((n,time_step_count),num. Float)8472 gauge_depth=h*num.ones(n,num.float) 8473 ha=w*num.ones((n,time_step_count),num.float) 8474 ua=u*num.ones((n,time_step_count),num.float) 8475 va=v*num.ones((n,time_step_count),num.float) 8476 8476 base_name, files = self.write_mux2(lat_long_points, 8477 8477 time_step_count, time_step, … … 8538 8538 finaltime = data_finaltime + 10 # Let model time exceed available data 8539 8539 yieldstep = time_step 8540 temp_fbound=num.zeros(int(finaltime/yieldstep)+1, num. Float)8540 temp_fbound=num.zeros(int(finaltime/yieldstep)+1, num.float) 8541 8541 8542 8542 for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep, … … 8582 8582 lat_long_points.insert(0,[6.0,97.01]) 8583 8583 n=len(lat_long_points) 8584 first_tstep=num.ones(n,num. Int)8585 last_tstep=(time_step_count)*num.ones(n,num. Int)8586 gauge_depth=20*num.ones(n,num. Float)8587 ha=2*num.ones((n,time_step_count),num. Float)8588 ua=10*num.ones((n,time_step_count),num. Float)8589 va=-10*num.ones((n,time_step_count),num. Float)8584 first_tstep=num.ones(n,num.int) 8585 last_tstep=(time_step_count)*num.ones(n,num.int) 8586 gauge_depth=20*num.ones(n,num.float) 8587 ha=2*num.ones((n,time_step_count),num.float) 8588 ua=10*num.ones((n,time_step_count),num.float) 8589 va=-10*num.ones((n,time_step_count),num.float) 8590 8590 base_name, files = self.write_mux2(lat_long_points, 8591 8591 time_step_count, … … 8629 8629 finaltime=time_step*(time_step_count-1) 8630 8630 yieldstep=time_step 8631 temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num. Float)8631 temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num.float) 8632 8632 8633 8633 for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep, … … 8641 8641 Bd = Dirichlet_boundary([2.0+tide,220+10*tide,-220-10*tide]) 8642 8642 domain_drchlt.set_boundary({'ocean': Bd,'otherocean': Br}) 8643 temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num. Float)8643 temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num.float) 8644 8644 8645 8645 for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep, … … 8688 8688 time_step = 2 8689 8689 n=len(lat_long_points) 8690 first_tstep=num.ones(n,num. Int)8691 last_tstep=(time_step_count)*num.ones(n,num. Int)8692 gauge_depth=20*num.ones(n,num. Float)8693 ha=2*num.ones((n,time_step_count),num. Float)8694 ua=10*num.ones((n,time_step_count),num. Float)8695 va=-10*num.ones((n,time_step_count),num. Float)8690 first_tstep=num.ones(n,num.int) 8691 last_tstep=(time_step_count)*num.ones(n,num.int) 8692 gauge_depth=20*num.ones(n,num.float) 8693 ha=2*num.ones((n,time_step_count),num.float) 8694 ua=10*num.ones((n,time_step_count),num.float) 8695 va=-10*num.ones((n,time_step_count),num.float) 8696 8696 base_name, files = self.write_mux2(lat_long_points, 8697 8697 time_step_count, … … 8779 8779 finaltime=time_step*(time_step_count-1) 8780 8780 yieldstep=time_step 8781 temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num. Float)8781 temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num.float) 8782 8782 8783 8783 for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep, … … 8792 8792 Bd = Dirichlet_boundary([2.0+tide,220+10*tide,-220-10*tide]) 8793 8793 domain_drchlt.set_boundary({'ocean': Bd,'otherocean': Br}) 8794 temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num. Float)8794 temp_drchlt=num.zeros(int(finaltime/yieldstep)+1,num.float) 8795 8795 8796 8796 for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep, … … 8854 8854 8855 8855 n=len(lat_long_points) 8856 first_tstep=num.ones(n,num. Int)8857 last_tstep=(time_step_count)*num.ones(n,num. Int)8858 8859 gauge_depth=20*num.ones(n,num. Float)8860 8861 ha1=num.ones((n,time_step_count),num. Float)8862 ua1=3.*num.ones((n,time_step_count),num. Float)8863 va1=2.*num.ones((n,time_step_count),num. Float)8856 first_tstep=num.ones(n,num.int) 8857 last_tstep=(time_step_count)*num.ones(n,num.int) 8858 8859 gauge_depth=20*num.ones(n,num.float) 8860 8861 ha1=num.ones((n,time_step_count),num.float) 8862 ua1=3.*num.ones((n,time_step_count),num.float) 8863 va1=2.*num.ones((n,time_step_count),num.float) 8864 8864 for i in range(n): 8865 8865 ha1[i]=num.sin(times_ref) … … 8976 8976 finaltime=time_step*(time_step_count-1) 8977 8977 yieldstep=time_step 8978 temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num. Float)8978 temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num.float) 8979 8979 8980 8980 for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep, … … 8991 8991 domain_time.set_boundary({'ocean': Bw,'otherocean': Br}) 8992 8992 8993 temp_time=num.zeros(int(finaltime/yieldstep)+1,num. Float)8993 temp_time=num.zeros(int(finaltime/yieldstep)+1,num.float) 8994 8994 for i, t in enumerate(domain_time.evolve(yieldstep=yieldstep, 8995 8995 finaltime=finaltime, … … 9050 9050 9051 9051 n=len(lat_long_points) 9052 first_tstep=num.ones(n,num. Int)9053 last_tstep=(time_step_count)*num.ones(n,num. Int)9054 9055 gauge_depth=20*num.ones(n,num. Float)9056 9057 ha1=num.ones((n,time_step_count),num. Float)9058 ua1=3.*num.ones((n,time_step_count),num. Float)9059 va1=2.*num.ones((n,time_step_count),num. Float)9052 first_tstep=num.ones(n,num.int) 9053 last_tstep=(time_step_count)*num.ones(n,num.int) 9054 9055 gauge_depth=20*num.ones(n,num.float) 9056 9057 ha1=num.ones((n,time_step_count),num.float) 9058 ua1=3.*num.ones((n,time_step_count),num.float) 9059 va1=2.*num.ones((n,time_step_count),num.float) 9060 9060 for i in range(n): 9061 9061 ha1[i]=num.sin(times_ref) … … 10127 10127 sww.store_header(outfile, times, number_of_volumes, 10128 10128 number_of_points, description='fully sick testing', 10129 verbose=self.verbose,sww_precision=n um.Float)10129 verbose=self.verbose,sww_precision=netcdf_float) 10130 10130 sww.store_triangulation(outfile, points_utm, volumes, 10131 10131 elevation, new_origin=new_origin, … … 10159 10159 sww.store_header(outfile, times, number_of_volumes, 10160 10160 number_of_points, description='fully sick testing', 10161 verbose=self.verbose,sww_precision=n um.Float)10161 verbose=self.verbose,sww_precision=netcdf_float) 10162 10162 sww.store_triangulation(outfile, points_utm, volumes, 10163 10163 elevation, new_origin=new_origin, … … 10195 10195 sww.store_header(outfile, times, number_of_volumes, 10196 10196 number_of_points, description='fully sick testing', 10197 verbose=self.verbose,sww_precision=n um.Float)10197 verbose=self.verbose,sww_precision=netcdf_float) 10198 10198 sww.store_triangulation(outfile, points_utm, volumes, 10199 10199 elevation, new_origin=new_origin, … … 10234 10234 sww.store_header(outfile, times, number_of_volumes, 10235 10235 number_of_points, description='fully sick testing', 10236 verbose=self.verbose,sww_precision=n um.Float)10236 verbose=self.verbose,sww_precision=netcdf_float) 10237 10237 sww.store_triangulation(outfile, points_utm, volumes, 10238 10238 elevation, new_origin=new_origin, … … 10270 10270 sww.store_header(outfile, times, number_of_volumes, 10271 10271 number_of_points, description='fully sick testing', 10272 verbose=self.verbose,sww_precision=n um.Float)10272 verbose=self.verbose,sww_precision=netcdf_float) 10273 10273 sww.store_triangulation(outfile, points_utm, volumes, 10274 10274 elevation, new_origin=new_origin, … … 10629 10629 10630 10630 # Check runup restricted to a polygon 10631 p = num.array([[50,1], [99,1], [99,49], [50,49]] , num.Int) + num.array([E, N], num.Int) #array default#10631 p = num.array([[50,1], [99,1], [99,49], [50,49]]) + num.array([E, N]) 10632 10632 10633 10633 runup = get_maximum_inundation_elevation(swwfile, polygon=p) -
branches/numpy/anuga/shallow_water/test_eq.py
r6157 r6304 1 1 import unittest 2 import Numericas num2 import numpy as num 3 3 from eqf import earthquake_tsunami, Okada_func 4 4 -
branches/numpy/anuga/shallow_water/test_most2nc.py
r6157 r6304 1 1 import unittest 2 import Numericas num2 import numpy as num 3 3 from Scientific.IO.NetCDF import NetCDFFile 4 4 import most2nc -
branches/numpy/anuga/shallow_water/test_shallow_water_domain.py
r6244 r6304 7 7 from anuga.config import g, epsilon 8 8 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 9 import Numericas num9 import numpy as num 10 10 from anuga.utilities.numerical_tools import mean 11 11 from anuga.utilities.polygon import is_inside_polygon … … 37 37 assert N == len(y) 38 38 39 z = num.zeros(N, num. Float)39 z = num.zeros(N, num.float) 40 40 for i in range(N): 41 41 z[i] = -x[i]/2 #General slope … … 142 142 assert N == len(y) 143 143 144 z = num.zeros(N, num. Float)144 z = num.zeros(N, num.float) 145 145 for i in range(N): 146 146 z[i] = -x[i] #General slope … … 195 195 def scalar_func(t,x,y): 196 196 """Function that returns a scalar. 197 Used to test error message when Numeric array is expected197 Used to test error message when numeric array is expected 198 198 """ 199 199 … … 254 254 #Check error check 255 255 try: 256 rotate(r, num.array([1,1,1] , num.Int)) #array default#256 rotate(r, num.array([1,1,1])) 257 257 except: 258 258 pass … … 263 263 # Individual flux tests 264 264 def test_flux_zero_case(self): 265 ql = num.zeros( 3, num. Float )266 qr = num.zeros( 3, num. Float )267 normal = num.zeros( 2, num. Float )268 edgeflux = num.zeros( 3, num. Float )265 ql = num.zeros( 3, num.float ) 266 qr = num.zeros( 3, num.float ) 267 normal = num.zeros( 2, num.float ) 268 edgeflux = num.zeros( 3, num.float ) 269 269 zl = zr = 0. 270 270 H0 = 0.0 … … 281 281 ql = num.array([w, 0, 0]) 282 282 qr = num.array([w, 0, 0]) 283 edgeflux = num.zeros(3, num. Float)283 edgeflux = num.zeros(3, num.float) 284 284 zl = zr = 0. 285 285 h = w - (zl+zr)/2 … … 312 312 qr = num.array([-0.2, 2, 3]) 313 313 zl = zr = -0.5 314 edgeflux = num.zeros(3, num. Float)314 edgeflux = num.zeros(3, num.float) 315 315 316 316 H0 = 0.0 … … 329 329 zl = zr = -0.375 330 330 331 edgeflux = num.zeros(3, num. Float)331 edgeflux = num.zeros(3, num.float) 332 332 H0 = 0.0 333 333 max_speed = flux_function(normal, ql, qr, zl, zr, edgeflux, epsilon, g, H0) … … 343 343 zl = zr = -0.375 344 344 345 edgeflux = num.zeros(3, num. Float)345 edgeflux = num.zeros(3, num.float) 346 346 H0 = 0.0 347 347 max_speed = flux_function(normal, ql, qr, zl, zr, edgeflux, epsilon, g, H0) … … 357 357 zl = zr = -0.375 358 358 359 edgeflux = num.zeros(3, num. Float)359 edgeflux = num.zeros(3, num.float) 360 360 H0 = 0.0 361 361 max_speed = flux_function(normal, ql, qr, zl, zr, edgeflux, epsilon, g, H0) … … 433 433 assert domain.quantities.has_key(name) 434 434 435 436 assert domain.get_conserved_quantities(0, edge=1) == 0. 435 assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.) 437 436 438 437 … … 709 708 zl=zr=0. # Assume flat bed 710 709 711 edgeflux = num.zeros(3, num. Float)712 edgeflux0 = num.zeros(3, num. Float)713 edgeflux1 = num.zeros(3, num. Float)714 edgeflux2 = num.zeros(3, num. Float)710 edgeflux = num.zeros(3, num.float) 711 edgeflux0 = num.zeros(3, num.float) 712 edgeflux1 = num.zeros(3, num.float) 713 edgeflux2 = num.zeros(3, num.float) 715 714 H0 = 0.0 716 715 … … 797 796 zl=zr=0. #Assume flat bed 798 797 799 edgeflux = num.zeros(3, num. Float)800 edgeflux0 = num.zeros(3, num. Float)801 edgeflux1 = num.zeros(3, num. Float)802 edgeflux2 = num.zeros(3, num. Float)798 edgeflux = num.zeros(3, num.float) 799 edgeflux0 = num.zeros(3, num.float) 800 edgeflux1 = num.zeros(3, num.float) 801 edgeflux2 = num.zeros(3, num.float) 803 802 H0 = 0.0 804 803 … … 905 904 906 905 zl=zr=0 #Assume flat zero bed 907 edgeflux = num.zeros(3, num. Float)908 edgeflux0 = num.zeros(3, num. Float)909 edgeflux1 = num.zeros(3, num. Float)910 edgeflux2 = num.zeros(3, num. Float)906 edgeflux = num.zeros(3, num.float) 907 edgeflux0 = num.zeros(3, num.float) 908 edgeflux1 = num.zeros(3, num.float) 909 edgeflux2 = num.zeros(3, num.float) 911 910 H0 = 0.0 912 911 913 912 914 domain.set_quantity('elevation', zl*num.ones( (4,3) ))913 domain.set_quantity('elevation', zl*num.ones( (4,3), num.int )) #array default# 915 914 916 915 … … 988 987 989 988 zl=zr=-3.75 #Assume constant bed (must be less than stage) 990 domain.set_quantity('elevation', zl*num.ones( (4,3) ))991 992 993 edgeflux = num.zeros(3, num. Float)994 edgeflux0 = num.zeros(3, num. Float)995 edgeflux1 = num.zeros(3, num. Float)996 edgeflux2 = num.zeros(3, num. Float)989 domain.set_quantity('elevation', zl*num.ones( (4,3), num.int )) #array default# 990 991 992 edgeflux = num.zeros(3, num.float) 993 edgeflux0 = num.zeros(3, num.float) 994 edgeflux1 = num.zeros(3, num.float) 995 edgeflux2 = num.zeros(3, num.float) 997 996 H0 = 0.0 998 997 … … 1071 1070 1072 1071 zl=zr=4 #Too large 1073 domain.set_quantity('elevation', zl*num.ones( (4,3) ))1072 domain.set_quantity('elevation', zl*num.ones( (4,3), num.int )) #array default# 1074 1073 domain.set_quantity('stage', [[val0, val0-1, val0-2], 1075 1074 [val1, val1+1, val1], … … 1105 1104 1106 1105 zl=zr=5 1107 domain.set_quantity('elevation', zl*num.ones( (4,3) ))1106 domain.set_quantity('elevation', zl*num.ones( (4,3), num.int )) #array default# 1108 1107 domain.set_quantity('stage', [[val0, val0-1, val0-2], 1109 1108 [val1, val1+1, val1], … … 2621 2620 def test_time_dependent_rainfall_using_starttime(self): 2622 2621 2623 rainfall_poly = ensure_numeric([[1,1], [2,1], [2,2], [1,2]], num. Float)2622 rainfall_poly = ensure_numeric([[1,1], [2,1], [2,2], [1,2]], num.float) 2624 2623 2625 2624 a = [0.0, 0.0] … … 2692 2691 2693 2692 2694 rainfall_poly = ensure_numeric([[1,1], [2,1], [2,2], [1,2]], num. Float)2693 rainfall_poly = ensure_numeric([[1,1], [2,1], [2,2], [1,2]], num.float) 2695 2694 rainfall_poly += [x0, y0] 2696 2695 … … 3142 3141 3143 3142 zl=zr=-3.75 #Assume constant bed (must be less than stage) 3144 domain.set_quantity('elevation', zl*num.ones( (4,3) ))3143 domain.set_quantity('elevation', zl*num.ones( (4,3), num.int )) #array default# 3145 3144 domain.set_quantity('stage', [[val0, val0-1, val0-2], 3146 3145 [val1, val1+1, val1], … … 4560 4559 if V: 4561 4560 #Set centroids as if system had been evolved 4562 L = num.zeros(2*N*N, num. Float)4561 L = num.zeros(2*N*N, num.float) 4563 4562 L[:32] = [7.21205592e-003, 5.35214298e-002, 1.00910824e-002, 4564 4563 5.35439433e-002, 1.00910824e-002, 5.35439433e-002, … … 4573 4572 0.00000000e+000, 5.57305948e-005] 4574 4573 4575 X = num.zeros(2*N*N, num. Float)4574 X = num.zeros(2*N*N, num.float) 4576 4575 X[:32] = [6.48351607e-003, 3.68571894e-002, 8.50733285e-003, 4577 4576 3.68731327e-002, 8.50733285e-003, 3.68731327e-002, … … 4586 4585 0.00000000e+000, 4.57662812e-005] 4587 4586 4588 Y = num.zeros(2*N*N, num. Float)4587 Y = num.zeros(2*N*N, num.float) 4589 4588 Y[:32]=[-1.39463104e-003, 6.15600298e-004, -6.03637382e-004, 4590 4589 6.18272251e-004, -6.03637382e-004, 6.18272251e-004, … … 5691 5690 5692 5691 #print points[0], points[5], points[10], points[15] 5693 assert num.allclose( num.take(points, [0,5,10,15]), 5694 [[0,0], [1.0/3, 1.0/3], [2.0/3, 2.0/3], [1,1]]) 5692 msg = ('value was %s,\nshould be [[0,0], [1.0/3, 1.0/3], ' 5693 '[2.0/3, 2.0/3], [1,1]]' % str(num.take(points, [0,5,10,15]))) 5694 assert num.allclose(num.take(points, [0,5,10,15]), 5695 [[0,0], [1.0/3, 1.0/3], [2.0/3, 2.0/3], [1,1]]), msg 5695 5696 5696 5697 … … 5872 5873 5873 5874 #print points[0], points[5], points[10], points[15] 5874 assert num.allclose( num.take(points, [0,5,10,15]), 5875 [[0,0], [1.0/3, 1.0/3], [2.0/3, 2.0/3], [1,1]]) 5875 msg = ('values was %s,\nshould be [[0,0], [1.0/3, 1.0/3], ' 5876 '[2.0/3, 2.0/3], [1,1]]' % str(num.take(points, [0,5,10,15]))) 5877 assert num.allclose(num.take(points, [0,5,10,15]), 5878 [[0,0], [1.0/3, 1.0/3], [2.0/3, 2.0/3], [1,1]]), msg 5876 5879 5877 5880 … … 6045 6048 6046 6049 #print points[0], points[5], points[10], points[15] 6047 assert num.allclose( num.take(points, [0,5,10,15]), 6048 [[0,0], [1.0/3, 1.0/3], [2.0/3, 2.0/3], [1,1]]) 6050 msg = ('value was %s,\nshould be [[0,0], [1.0/3, 1.0/3], ' 6051 '[2.0/3, 2.0/3], [1,1]]' % str(num.take(points, [0,5,10,15]))) 6052 assert num.allclose(num.take(points, [0,5,10,15]), 6053 [[0,0], [1.0/3, 1.0/3], [2.0/3, 2.0/3], [1,1]]), msg 6054 6049 6055 6050 6056 … … 6237 6243 6238 6244 bed = domain.quantities['elevation'].vertex_values 6239 stage = num.zeros(bed.shape, num. Float)6245 stage = num.zeros(bed.shape, num.float) 6240 6246 6241 6247 h = 0.3 -
branches/numpy/anuga/shallow_water/test_smf.py
r6157 r6304 1 1 import unittest 2 import Numericas num2 import numpy as num 3 3 from smf import slide_tsunami, slump_tsunami, Double_gaussian 4 4 -
branches/numpy/anuga/shallow_water/test_system.py
r6157 r6304 9 9 10 10 from Scientific.IO.NetCDF import NetCDFFile 11 import Numericas num11 import numpy as num 12 12 13 13 from anuga.shallow_water import Domain … … 34 34 20 13.9773 35 35 """ 36 36 37 tide = 5 37 38 boundary_filename = tempfile.mktemp(".sww") … … 85 86 boundary_filename = self.create_sww_boundary(boundary_starttime) 86 87 filename = tempfile.mktemp(".sww") 87 #print "filename",filename88 88 dir, base = os.path.split(filename) 89 89 senario_name = base[:-4] -
branches/numpy/anuga/shallow_water/test_tsunami_okada.py
r6157 r6304 1 1 import unittest 2 import Numericas num2 import numpy as num 3 3 from tsunami_okada import earthquake_tsunami,Okada_func 4 4 -
branches/numpy/anuga/shallow_water/tsunami_okada.py
r6157 r6304 30 30 """ 31 31 32 import Numericas num32 import numpy as num 33 33 34 34 … … 45 45 zrec=zrec0.get_vertex_values(xy=True) 46 46 47 x0= num.zeros(ns,num. Float)48 y0= num.zeros(ns,num. Float)47 x0= num.zeros(ns,num.float) 48 y0= num.zeros(ns,num.float) 49 49 if ns ==1: 50 50 x0[0]=xi … … 151 151 zrec=self.zrec 152 152 #initialization 153 disp0=num.zeros(3,num. Float)154 strain0=num.zeros(6,num. Float)155 tilt0 = num.zeros(2,num. Float)156 dislocations=num.zeros(ns,num. Float)157 depths=num.zeros(ns,num. Float)158 strikes= num.zeros(ns,num. Float)159 lengths= num.zeros(ns,num. Float)160 slips= num.zeros(ns,num. Float)161 rakes= num.zeros(ns,num. Float)162 widths= num.zeros(ns,num. Float)163 dips= num.zeros(ns,num. Float)164 strikes= num.zeros(ns,num. Float)165 strikes= num.zeros(ns,num. Float)166 strain = num.zeros((N,6),num. Float)167 disp = num.zeros((N,3),num. Float)168 tilt = num.zeros((N,2),num. Float)169 xs =num.zeros(ns,num. Float)170 ys =num.zeros(ns,num. Float)153 disp0=num.zeros(3,num.float) 154 strain0=num.zeros(6,num.float) 155 tilt0 = num.zeros(2,num.float) 156 dislocations=num.zeros(ns,num.float) 157 depths=num.zeros(ns,num.float) 158 strikes= num.zeros(ns,num.float) 159 lengths= num.zeros(ns,num.float) 160 slips= num.zeros(ns,num.float) 161 rakes= num.zeros(ns,num.float) 162 widths= num.zeros(ns,num.float) 163 dips= num.zeros(ns,num.float) 164 strikes= num.zeros(ns,num.float) 165 strikes= num.zeros(ns,num.float) 166 strain = num.zeros((N,6),num.float) 167 disp = num.zeros((N,3),num.float) 168 tilt = num.zeros((N,2),num.float) 169 xs =num.zeros(ns,num.float) 170 ys =num.zeros(ns,num.float) 171 171 z=[] 172 172 if ns==1: … … 378 378 379 379 F0=0.0 380 U=num.zeros((12,1),num. Float)381 DUA=num.zeros((12,1),num. Float)382 DUB=num.zeros((12,1),num. Float)383 DUC=num.zeros((12,1),num. Float)380 U=num.zeros((12,1),num.float) 381 DUA=num.zeros((12,1),num.float) 382 DUB=num.zeros((12,1),num.float) 383 DUC=num.zeros((12,1),num.float) 384 384 385 385 … … 526 526 WZ=self.WZ 527 527 528 DUA=num.zeros((12,1),num. Float)529 DU=num.zeros((12,1),num. Float)530 U=num.zeros((12,1),num. Float)528 DUA=num.zeros((12,1),num.float) 529 DU=num.zeros((12,1),num.float) 530 U=num.zeros((12,1),num.float) 531 531 #----- 532 532 for I in range(0,12): … … 636 636 # DATA PI2/6.283185307179586D0/ 637 637 638 DUB=num.zeros((12,1),num. Float)639 DU=num.zeros((12,1),num. Float)640 U=num.zeros((12,1),num. Float)638 DUB=num.zeros((12,1),num.float) 639 DU=num.zeros((12,1),num.float) 640 U=num.zeros((12,1),num.float) 641 641 642 642 F0=0.0 … … 811 811 812 812 813 DUC=num.zeros((12,1),num. Float)814 DU=num.zeros((12,1),num. Float)815 U=num.zeros((12,1),num. Float)813 DUC=num.zeros((12,1),num.float) 814 DU=num.zeros((12,1),num.float) 815 U=num.zeros((12,1),num.float) 816 816 817 817 F0=0.0 … … 1005 1005 EPS=0.000001 1006 1006 1007 XI=num.zeros(2,num. Float)1008 ET=num.zeros(2,num. Float)1009 KXI=num.zeros(2,num. Float)1010 KET=num.zeros(2,num. Float)1011 U=num.zeros(12,num. Float)1012 DU=num.zeros(12,num. Float)1013 DUA=num.zeros(12,num. Float)1014 DUB=num.zeros(12,num. Float)1015 DUC=num.zeros(12,num. Float)1007 XI=num.zeros(2,num.float) 1008 ET=num.zeros(2,num.float) 1009 KXI=num.zeros(2,num.float) 1010 KET=num.zeros(2,num.float) 1011 U=num.zeros(12,num.float) 1012 DU=num.zeros(12,num.float) 1013 DUA=num.zeros(12,num.float) 1014 DUB=num.zeros(12,num.float) 1015 DUC=num.zeros(12,num.float) 1016 1016 1017 1017 #----- … … 1211 1211 1212 1212 1213 U=num.zeros(12,num. Float)1214 DU=num.zeros(12,num. Float)1215 DUA=num.zeros(12,num. Float)1213 U=num.zeros(12,num.float) 1214 DU=num.zeros(12,num.float) 1215 DUA=num.zeros(12,num.float) 1216 1216 F0 =0.0 1217 1217 F2=2.0 … … 1342 1342 # DATA F0,F1,F2,PI2/0.D0,1.D0,2.D0,6.283185307179586D0/ 1343 1343 1344 DUB=num.zeros(12,num. Float)1345 DU=num.zeros(12,num. Float)1346 U=num.zeros(12,num. Float)1344 DUB=num.zeros(12,num.float) 1345 DU=num.zeros(12,num.float) 1346 U=num.zeros(12,num.float) 1347 1347 1348 1348 F0=0.0 … … 1507 1507 # DATA F0,F1,F2,F3,PI2/0.D0,1.D0,2.D0,3.D0,6.283185307179586D0/ 1508 1508 1509 DUC=num.zeros(12,num. Float)1510 DU=num.zeros(12,num. Float)1511 U=num.zeros(12,num. Float)1509 DUC=num.zeros(12,num.float) 1510 DU=num.zeros(12,num.float) 1511 U=num.zeros(12,num.float) 1512 1512 1513 1513 F0=0.0 -
branches/numpy/anuga/shallow_water/urs_ext.c
r5972 r6304 5 5 6 6 #include "Python.h" 7 #include " Numeric/arrayobject.h"7 #include "numpy/arrayobject.h" 8 8 #include "structure.h" 9 9 #include "math.h" -
branches/numpy/anuga/test_all.py
r6220 r6304 15 15 import time 16 16 import anuga.utilities.system_tools as aust 17 from anuga.utilities.terminal_width import terminal_width 17 18 18 19 … … 35 36 def list_names(names, func=None, col_width=None, page_width=None): 36 37 # set defaults 37 p_width = page_width 38 p_width = page_width - 1 # set page width 38 39 if p_width is None: 39 40 p_width = 132 # default page width … … 46 47 name = func(name) 47 48 c_width = max(c_width, len(name)) 48 c_width += 2 # padding between columns49 c_width += 2 # 2 column padding 49 50 50 51 # calculate number of columns allowed … … 56 57 if func: 57 58 name = func(name) 58 print '%-*s' % (c_width , name),59 print '%-*s' % (c_width-1, name), 59 60 column += 1 60 61 if column >= max_columns: … … 102 103 print 'Testing path: %s' % path 103 104 105 # get the terminal width 106 term_width = terminal_width() 107 104 108 # explain what we are doing 105 109 print 106 110 print "The following directories will be skipped over:" 107 111 exclude_dirs.sort() 108 list_names(exclude_dirs )112 list_names(exclude_dirs, page_width=term_width) 109 113 110 114 # get all test_*.py and enclosing directories … … 116 120 print 117 121 print 'Paths searched:' 118 list_names(path_files, os.path.basename )122 list_names(path_files, os.path.basename, page_width=term_width) 119 123 120 124 print 121 125 print 'Files tested:' 122 list_names(files )126 list_names(files, page_width=term_width) 123 127 print 124 128 -
branches/numpy/anuga/utilities/cg_solve.py
r6158 r6304 3 3 class ConvergenceError(exceptions.Exception): pass 4 4 5 import Numericas num5 import numpy as num 6 6 7 7 import logging, logging.config … … 24 24 25 25 if x0 is None: 26 x0 = num.zeros(b.shape, typecode=num.Float)26 x0 = num.zeros(b.shape, dtype=num.float) 27 27 else: 28 x0 = num.array(x0, typecode=num.Float)28 x0 = num.array(x0, dtype=num.float) 29 29 30 b = num.array(b, typecode=num.Float)30 b = num.array(b, dtype=num.float) 31 31 if len(b.shape) != 1 : 32 32 … … 57 57 58 58 59 b = num.array(b, typecode=num.Float)59 b = num.array(b, dtype=num.float) 60 60 if len(b.shape) != 1 : 61 61 raise VectorShapeError, 'input vector should consist of only one column' 62 62 63 63 if x0 is None: 64 x0 = num.zeros(b.shape, typecode=num.Float)64 x0 = num.zeros(b.shape, dtype=num.float) 65 65 else: 66 x0 = num.array(x0, typecode=num.Float)66 x0 = num.array(x0, dtype=num.float) 67 67 68 68 -
branches/numpy/anuga/utilities/compile.py
r6057 r6304 10 10 Ole Nielsen, Duncan Gray Oct 2001 11 11 """ 12 13 #NumPy ------------------------------------ 14 # Something like these lines recommended in "Converting from NUMARRAY to NUMPY" 15 import numpy 16 I_dirs = '-I"%s" ' % numpy.get_include() 17 #NumPy ------------------------------------ 12 18 13 19 # FIXME (Ole): Although this script says it works with a range of compilers, … … 255 261 else: 256 262 if FN == "triangle.c" or FN == "mesh_engine_c_layer.c": 257 s = '%s -c %s -I"%s" -I"%s" -o "%s.o" -O3 -DTRILIBRARY=1 -DNO_TIMER=1'\258 % (compiler, FN, python_include, utilities_include_dir, root)263 s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -O3 -DTRILIBRARY=1 -DNO_TIMER=1'\ 264 % (compiler, FN, I_dirs, python_include, utilities_include_dir, root) 259 265 elif FN == "polygon_ext.c": 260 266 # gcc 4.3.x screws up in this file if '-O3' is used 261 s = '%s -c %s -I"%s" -I"%s" -o "%s.o" -Wall'\262 %(compiler, FN, python_include, utilities_include_dir, root)267 s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -Wall'\ 268 %(compiler, FN, I_dirs, python_include, utilities_include_dir, root) 263 269 else: 264 s = '%s -c %s -I"%s" -I"%s" -o "%s.o" -Wall -O3'\265 %(compiler, FN, python_include, utilities_include_dir, root)270 s = '%s -c %s %s -I"%s" -I"%s" -o "%s.o" -Wall -O3'\ 271 %(compiler, FN, I_dirs, python_include, utilities_include_dir, root) 266 272 267 273 if os.name == 'posix' and os.uname()[4] in ['x86_64', 'ia64']: -
branches/numpy/anuga/utilities/interp.py
r5897 r6304 75 75 76 76 Positional Input Arguments: 77 * y: Ordinate values of data. Rank 1 Numeric vector. Required.77 * y: Ordinate values of data. Rank 1 numeric vector. Required. 78 78 Can have missing values. Floating or integer type. 79 79 80 * x: Abscissa values of data. Rank 1 Numeric vector. Required.80 * x: Abscissa values of data. Rank 1 numeric vector. Required. 81 81 Can have no missing values. Must be monotonically ascending. 82 82 Floating or integer type. 83 83 84 84 * xinterp: Abscissa values to calculate interpolated ordinate 85 values at. Rank 1 Numeric vector or Numeric scalar. Required.85 values at. Rank 1 numeric vector or numeric scalar. Required. 86 86 Can have no missing values. Can be in any order. Floating or 87 87 integer type. … … 94 94 95 95 Output Result: 96 * Interpolated ordinate values at xinterp. Rank 1 Numeric vector97 of same length as xinterp (if xinterp is a Numeric scalar,98 output is also a Numeric scalar). Missing values are set to the96 * Interpolated ordinate values at xinterp. Rank 1 numeric vector 97 of same length as xinterp (if xinterp is a numeric scalar, 98 output is also a numeric scalar). Missing values are set to the 99 99 value of argument missing. Type is Float, even if argument 100 100 missing and inputs are all integer. … … 111 111 112 112 >>> from interp import interp 113 >>> import Numericas N113 >>> import numpy as N 114 114 >>> x = N.array([1., 2., 3., 4., 5.]) 115 115 >>> y = N.array([3., 6., 2.,-5.,-3.]) … … 138 138 """ 139 139 import arrayfns 140 import MA141 import Numericas N140 import numpy.ma MA 141 import numpy as N 142 142 from where_close import where_close 143 143 … … 216 216 217 217 >>> from interp import interp 218 >>> import Numericas N218 >>> import numpy as N 219 219 >>> x = N.array([1., 2., 3., 4., 5., 6.]) 220 220 >>> y = N.array([3., 1e+20, 2., -5., -3., -4.]) … … 284 284 >>> ['%.7g' % yint[i] for i in range(len(yint))] 285 285 ['3.4', '2.3'] 286 >>> yint. typecode()286 >>> yint.dtype.char 287 287 'd' 288 288 >>> x = N.arange(6) … … 292 292 >>> ['%.7g' % yint[i] for i in range(len(yint))] 293 293 ['3', '2'] 294 >>> yint. typecode()294 >>> yint.dtype.char 295 295 'd' 296 296 """} -
branches/numpy/anuga/utilities/numerical_tools.py
r6174 r6304 7 7 from warnings import warn 8 8 9 import Numericas num9 import numpy as num 10 10 11 11 NAN = (num.array([1])/0.)[0] … … 70 70 """ 71 71 72 # Prepare two Numeric vectors72 # Prepare two numeric vectors 73 73 if v2 is None: 74 74 v2 = [1.0, 0.0] # Unit vector along the x-axis 75 75 76 v1 = ensure_numeric(v1, num. Float)77 v2 = ensure_numeric(v2, num. Float)76 v1 = ensure_numeric(v1, num.float) 77 v2 = ensure_numeric(v2, num.float) 78 78 79 79 # Normalise … … 82 82 83 83 # Compute angle 84 p = num.inner product(v1, v2)85 c = num.inner product(v1, normal_vector(v2)) # Projection onto normal84 p = num.inner(v1, v2) 85 c = num.inner(v1, normal_vector(v2)) # Projection onto normal 86 86 # (negative cross product) 87 87 … … 125 125 """ 126 126 127 return num.array([-v[1], v[0]], num. Float)127 return num.array([-v[1], v[0]], num.float) 128 128 129 129 … … 156 156 cy = y - mean(y) 157 157 158 p = num.inner product(cx,cy)/N158 p = num.inner(cx,cy)/N 159 159 return(p) 160 160 … … 206 206 207 207 y = num.ravel(x) 208 p = num.sqrt(num.inner product(y,y))208 p = num.sqrt(num.inner(y,y)) 209 209 return p 210 210 … … 230 230 231 231 232 233 def ensure_numeric(A, typecode = None): 234 """Ensure that sequence is a Numeric array. 232 233 ## 234 # @brief Ensure that a sequence is a numeric array of the required type. 235 # @param A The sequence object to convert to a numeric array. 236 # @param typecode The required numeric type of object A (a numeric dtype). 237 # @return A numeric array of the required type. 238 def ensure_numeric(A, typecode=None): 239 """Ensure that sequence is a numeric array. 235 240 Inputs: 236 A: Sequence. If A is already a Numeric array it will be returned241 A: Sequence. If A is already a numeric array it will be returned 237 242 unaltered 238 If not, an attempt is made to convert it to a Numeric243 If not, an attempt is made to convert it to a numeric 239 244 array 240 A: Scalar. Return 0-dimensional array of length 1, containing that value 241 A: String. Array of ASCII values 242 typecode: Numeric type. If specified, use this in the conversion. 243 If not, let Numeric decide 245 A: Scalar. Return 0-dimensional array containing that value. Note 246 that a 0-dim array DOES NOT HAVE A LENGTH UNDER numpy. 247 A: String. Array of ASCII values (numpy can't handle this) 248 249 typecode: numeric type. If specified, use this in the conversion. 250 If not, let numeric package decide. 251 numpy assumes float64 if no type in A. 244 252 245 253 This function is necessary as array(A) can cause memory overflow. 246 254 """ 247 255 256 if isinstance(A, basestring): 257 msg = 'Sorry, cannot handle string in ensure_numeric()' 258 raise Exception, msg 259 248 260 if typecode is None: 249 if type(A) == num.ArrayType:261 if isinstance(A, num.ndarray): 250 262 return A 251 263 else: 252 264 return num.array(A) 253 265 else: 254 if type(A) == num.ArrayType:255 if A. typecode == typecode:266 if isinstance(A, num.ndarray): 267 if A.dtype == typecode: 256 268 # return num.array(A) #FIXME: Shouldn't this just return A? 257 269 return A 258 270 else: 259 return num.array(A, typecode)271 return num.array(A, dtype=typecode) 260 272 else: 261 return num.array(A, typecode)273 return num.array(A, dtype=typecode) 262 274 263 275 … … 265 277 266 278 def histogram(a, bins, relative=False): 267 """Standard histogram straight from the Numeric manual279 """Standard histogram straight from the numeric manual 268 280 269 281 If relative is True, values will be normalised againts the total and … … 358 370 return a, b 359 371 372 ################################################################################ 373 # Decision functions for numeric package objects. 374 # It is a little tricky to decide if a numpy thing is of type float. 375 # These functions hide numpy-specific details of how we do this. 376 ################################################################################ 377 378 ## 379 # @brief Decide if an object is a numeric package object with datatype of float. 380 # @param obj The object to decide on. 381 # @return True if 'obj' is a numeric package object, and some sort of float. 382 def is_num_float(obj): 383 '''Is an object a numeric package float object?''' 384 385 try: 386 return obj.dtype.char in num.typecodes['Float'] 387 except AttributeError: 388 return False 389 390 ## 391 # @brief Decide if an object is a numeric package object with datatype of int. 392 # @param obj The object to decide on. 393 # @return True if 'obj' is a numeric package object, and some sort of int. 394 def is_num_int(obj): 395 '''Is an object a numeric package int object?''' 396 397 try: 398 return obj.dtype.char in num.typecodes['Integer'] 399 except AttributeError: 400 return False 401 360 402 361 403 #----------------- -
branches/numpy/anuga/utilities/polygon.py
r6223 r6304 3 3 """ 4 4 5 import Numericas num5 import numpy as num 6 6 7 7 from math import sqrt 8 8 from anuga.utilities.numerical_tools import ensure_numeric 9 9 from anuga.geospatial_data.geospatial_data import ensure_absolute, Geospatial_data 10 from anuga.config import netcdf_float 10 11 11 12 … … 15 16 Input: 16 17 point is given by [x, y] 17 18 the equivalent 2x2 Numeric array with each row corresponding to a point.18 line is given by [x0, y0], [x1, y1]] or 19 the equivalent 2x2 numeric array with each row corresponding to a point. 19 20 20 21 Output: … … 100 101 # FIXME (Ole): Write this in C 101 102 102 line0 = ensure_numeric(line0, num. Float)103 line1 = ensure_numeric(line1, num. Float)103 line0 = ensure_numeric(line0, num.float) 104 line1 = ensure_numeric(line1, num.float) 104 105 105 106 x0 = line0[0,0]; y0 = line0[0,1] … … 176 177 177 178 178 line0 = ensure_numeric(line0, num. Float)179 line1 = ensure_numeric(line1, num. Float)179 line0 = ensure_numeric(line0, num.float) 180 line1 = ensure_numeric(line1, num.float) 180 181 181 182 status, value = _intersection(line0[0,0], line0[0,1], … … 203 204 else: 204 205 msg = 'is_inside_polygon must be invoked with one point only' 205 raise msg206 raise Exception, msg 206 207 207 208 … … 228 229 # If this fails it is going to be because the points can't be 229 230 # converted to a numeric array. 230 msg = 'Points could not be converted to Numeric array'231 raisemsg231 msg = 'Points could not be converted to numeric array' 232 raise Exception, msg 232 233 233 234 try: … … 238 239 # If this fails it is going to be because the points can't be 239 240 # converted to a numeric array. 240 msg = 'Polygon %s could not be converted to Numeric array' %(str(polygon))241 raisemsg241 msg = 'Polygon %s could not be converted to numeric array' %(str(polygon)) 242 raise Exception, msg 242 243 243 244 if len(points.shape) == 1: 244 245 # Only one point was passed in. Convert to array of points 245 246 points = num.reshape(points, (1,2)) 246 247 247 248 indices, count = separate_points_by_polygon(points, polygon, … … 270 271 else: 271 272 msg = 'is_outside_polygon must be invoked with one point only' 272 raise msg273 raise Exception, msg 273 274 274 275 … … 285 286 #if verbose: print 'Checking input to outside_polygon' 286 287 try: 287 points = ensure_numeric(points, num. Float)288 points = ensure_numeric(points, num.float) 288 289 except NameError, e: 289 290 raise NameError, e 290 291 except: 291 msg = 'Points could not be converted to Numeric array'292 raisemsg292 msg = 'Points could not be converted to numeric array' 293 raise Exception, msg 293 294 294 295 try: 295 polygon = ensure_numeric(polygon, num. Float)296 polygon = ensure_numeric(polygon, num.float) 296 297 except NameError, e: 297 298 raise NameError, e 298 299 except: 299 msg = 'Polygon could not be converted to Numeric array'300 raisemsg300 msg = 'Polygon could not be converted to numeric array' 301 raise Exception, msg 301 302 302 303 303 304 if len(points.shape) == 1: 304 305 # Only one point was passed in. Convert to array of points 305 306 points = num.reshape(points, (1,2)) 306 307 307 308 indices, count = separate_points_by_polygon(points, polygon, … … 327 328 #if verbose: print 'Checking input to outside_polygon' 328 329 try: 329 points = ensure_numeric(points, num. Float)330 points = ensure_numeric(points, num.float) 330 331 except NameError, e: 331 332 raise NameError, e 332 333 except: 333 msg = 'Points could not be converted to Numeric array'334 raisemsg334 msg = 'Points could not be converted to numeric array' 335 raise Exception, msg 335 336 336 337 try: 337 polygon = ensure_numeric(polygon, num. Float)338 polygon = ensure_numeric(polygon, num.float) 338 339 except NameError, e: 339 340 raise NameError, e 340 341 except: 341 msg = 'Polygon could not be converted to Numeric array'342 raisemsg342 msg = 'Polygon could not be converted to numeric array' 343 raise Exception, msg 343 344 344 345 if len(points.shape) == 1: 345 346 # Only one point was passed in. Convert to array of points 346 347 points = num.reshape(points, (1,2)) 347 348 348 349 … … 413 414 414 415 416 # points = ensure_numeric(points, num.float) 415 417 try: 416 points = ensure_numeric(points, num. Float)418 points = ensure_numeric(points, num.float) 417 419 except NameError, e: 418 420 raise NameError, e 419 421 except: 420 msg = 'Points could not be converted to Numeric array'421 raisemsg422 msg = 'Points could not be converted to numeric array' 423 raise Exception, msg 422 424 423 425 #if verbose: print 'Checking input to separate_points_by_polygon 2' 424 426 try: 425 polygon = ensure_numeric(polygon, num. Float)427 polygon = ensure_numeric(polygon, num.float) 426 428 except NameError, e: 427 429 raise NameError, e 428 430 except: 429 msg = 'Polygon could not be converted to Numeric array'430 raisemsg431 msg = 'Polygon could not be converted to numeric array' 432 raise Exception, msg 431 433 432 434 msg = 'Polygon array must be a 2d array of vertices' … … 449 451 450 452 msg = 'Point array must have two columns (x,y), ' 451 msg += 'I got points.shape[1] == %d' % points.shape[0]453 msg += 'I got points.shape[1] == %d' % points.shape[1] 452 454 assert points.shape[1] == 2, msg 453 455 … … 464 466 465 467 466 indices = num.zeros( M, num. Int )468 indices = num.zeros( M, num.int ) 467 469 468 470 count = _separate_points_by_polygon(points, polygon, indices, … … 599 601 600 602 try: 601 polygon = ensure_numeric(polygon, num. Float)603 polygon = ensure_numeric(polygon, num.float) 602 604 except NameError, e: 603 605 raise NameError, e 604 606 except: 605 msg = 'Polygon %s could not be converted to Numeric array' %(str(polygon))606 raise msg607 msg = 'Polygon %s could not be converted to numeric array' %(str(polygon)) 608 raise Exception, msg 607 609 608 610 x = polygon[:,0] … … 666 668 geo_reference=None): 667 669 668 669 670 670 try: 671 len(regions) 672 except: 671 673 msg = 'Polygon_function takes a list of pairs (polygon, value).' 672 674 msg += 'Got %s' %regions 673 raise msg675 raise Exception, msg 674 676 675 677 … … 682 684 raise Exception, msg 683 685 684 686 try: 685 687 a = len(T) 686 688 except: 687 689 msg = 'Polygon_function takes a list of pairs (polygon, value).' 688 690 msg += 'Got %s' %str(T) 689 raise msg691 raise Exception, msg 690 692 691 693 msg = 'Each entry in regions have two components: (polygon, value).' 692 694 msg +='I got %s' %str(T) 693 695 assert a == 2, msg 694 696 695 697 … … 711 713 712 714 def __call__(self, x, y): 713 x = num.array(x, num.Float) 714 y = num.array(y, num.Float) 715 716 N = len(x) 717 assert len(y) == N 718 719 points = num.concatenate((num.reshape(x, (N, 1)), 720 num.reshape(y, (N, 1))), axis=1) 721 722 if callable(self.default): 723 z = self.default(x,y) 724 else: 725 z = num.ones(N, num.Float) * self.default 726 727 for polygon, value in self.regions: 728 indices = inside_polygon(points, polygon) 729 730 # FIXME: This needs to be vectorised 731 if callable(value): 732 for i in indices: 733 xx = num.array([x[i]]) 734 yy = num.array([y[i]]) 715 x = num.array(x, num.float) 716 y = num.array(y, num.float) 717 718 # x and y must be one-dimensional and same length 719 assert len(x.shape) == 1 and len(y.shape) == 1 720 N = x.shape[0] 721 assert y.shape[0] == N 722 723 points = num.ascontiguousarray(num.concatenate((x[:,num.newaxis], 724 y[:,num.newaxis]), 725 axis=1 )) 726 727 if callable(self.default): 728 z = self.default(x,y) 729 else: 730 z = num.ones(N, num.float) * self.default 731 732 for polygon, value in self.regions: 733 indices = inside_polygon(points, polygon) 734 735 # FIXME: This needs to be vectorised 736 if callable(value): 737 for i in indices: 738 xx = num.array([x[i]]) 739 yy = num.array([y[i]]) 735 740 z[i] = value(xx, yy)[0] 736 737 738 741 else: 742 for i in indices: 743 z[i] = value 739 744 740 745 if len(z) == 0: … … 998 1003 interpolation_points: Interpolate polyline data to these positions. 999 1004 List of coordinate pairs [x, y] of 1000 data points or an nx2 Numeric array or a Geospatial_data object1005 data points or an nx2 numeric array or a Geospatial_data object 1001 1006 rtol, atol: Used to determine whether a point is on the polyline or not. See point_on_line. 1002 1007 … … 1008 1013 interpolation_points = interpolation_points.get_data_points(absolute=True) 1009 1014 1010 interpolated_values = num.zeros(len(interpolation_points), num. Float)1011 1012 data = ensure_numeric(data, num. Float)1013 polyline_nodes = ensure_numeric(polyline_nodes, num. Float)1014 interpolation_points = ensure_numeric(interpolation_points, num. Float)1015 gauge_neighbour_id = ensure_numeric(gauge_neighbour_id, num. Int)1015 interpolated_values = num.zeros(len(interpolation_points), num.float) 1016 1017 data = ensure_numeric(data, num.float) 1018 polyline_nodes = ensure_numeric(polyline_nodes, num.float) 1019 interpolation_points = ensure_numeric(interpolation_points, num.float) 1020 gauge_neighbour_id = ensure_numeric(gauge_neighbour_id, num.int) 1016 1021 1017 1022 n = polyline_nodes.shape[0] # Number of nodes in polyline -
branches/numpy/anuga/utilities/polygon_ext.c
r6189 r6304 10 10 // Ole Nielsen, GA 2004 11 11 // 12 // NOTE: We use long* instead of int* for Numeric arrays as this will work both12 // NOTE: We use long* instead of int* for numeric arrays as this will work both 13 13 // for 64 as well as 32 bit systems 14 14 15 15 16 16 #include "Python.h" 17 #include " Numeric/arrayobject.h"17 #include "numpy/arrayobject.h" 18 18 #include "math.h" 19 19 -
branches/numpy/anuga/utilities/sparse.py
r6162 r6304 2 2 """ 3 3 4 import Numericas num4 import numpy as num 5 5 6 6 … … 22 22 A = num.array(args[0]) 23 23 except: 24 raise 'Input must be convertable to a Numeric array'24 raise 'Input must be convertable to a numeric array' 25 25 26 26 assert len(A.shape) == 2, 'Input must be a 2d matrix' … … 93 93 94 94 def todense(self): 95 D = num.zeros( (self.M, self.N), num. Float)95 D = num.zeros( (self.M, self.N), num.float) 96 96 97 97 for i in range(self.M): … … 105 105 def __mul__(self, other): 106 106 """Multiply this matrix onto 'other' which can either be 107 a Numeric vector, a Numeric matrix or another sparse matrix.107 a numeric vector, a numeric matrix or another sparse matrix. 108 108 """ 109 109 … … 111 111 B = num.array(other) 112 112 except: 113 msg = 'FIXME: Only Numeric types implemented so far'113 msg = 'FIXME: Only numeric types implemented so far' 114 114 raise msg 115 115 … … 127 127 assert B.shape[0] == self.N, msg 128 128 129 R = num.zeros(self.M, num. Float) #Result129 R = num.zeros(self.M, num.float) #Result 130 130 131 131 # Multiply nonzero elements … … 137 137 138 138 139 R = num.zeros((self.M, B.shape[1]), num. Float) #Result matrix139 R = num.zeros((self.M, B.shape[1]), num.float) #Result matrix 140 140 141 141 # Multiply nonzero elements … … 190 190 def trans_mult(self, other): 191 191 """Multiply the transpose of matrix with 'other' which can be 192 a Numeric vector.192 a numeric vector. 193 193 """ 194 194 … … 196 196 B = num.array(other) 197 197 except: 198 print 'FIXME: Only Numeric types implemented so far'198 print 'FIXME: Only numeric types implemented so far' 199 199 200 200 … … 205 205 assert B.shape[0] == self.M, 'Mismatching dimensions' 206 206 207 R = num.zeros((self.N,), num. Float) #Result207 R = num.zeros((self.N,), num.float) #Result 208 208 209 209 #Multiply nonzero elements … … 247 247 keys.sort() 248 248 nnz = len(keys) 249 data = num.zeros ( (nnz,), num. Float)250 colind = num.zeros ( (nnz,), num. Int)251 row_ptr = num.zeros ( (A.M+1,), num. Int)249 data = num.zeros ( (nnz,), num.float) 250 colind = num.zeros ( (nnz,), num.int) 251 row_ptr = num.zeros ( (A.M+1,), num.int) 252 252 current_row = -1 253 253 k = 0 … … 287 287 288 288 def todense(self): 289 D = num.zeros( (self.M, self.N), num. Float)289 D = num.zeros( (self.M, self.N), num.float) 290 290 291 291 for i in range(self.M): … … 297 297 def __mul__(self, other): 298 298 """Multiply this matrix onto 'other' which can either be 299 a Numeric vector, a Numeric matrix or another sparse matrix.299 a numeric vector, a numeric matrix or another sparse matrix. 300 300 """ 301 301 … … 303 303 B = num.array(other) 304 304 except: 305 print 'FIXME: Only Numeric types implemented so far'305 print 'FIXME: Only numeric types implemented so far' 306 306 307 307 return csr_mv(self,B) … … 355 355 356 356 #Right hand side column 357 v = num.array([[2,4],[3,4],[4,4]] , num.Int) #array default#357 v = num.array([[2,4],[3,4],[4,4]]) 358 358 359 359 u = A*v[:,0] -
branches/numpy/anuga/utilities/sparse_ext.c
r5897 r6304 11 11 12 12 #include "Python.h" 13 #include " Numeric/arrayobject.h"13 #include "numpy/arrayobject.h" 14 14 #include "math.h" 15 15 #include "stdio.h" -
branches/numpy/anuga/utilities/test_cg_solve.py
r6158 r6304 6 6 7 7 8 import Numericas num8 import numpy as num 9 9 from anuga.utilities.cg_solve import * 10 10 from anuga.utilities.cg_solve import _conjugate_gradient … … 68 68 A[i,i+1] = -0.5 69 69 70 xe = num.ones( (n,), num. Float)70 xe = num.ones( (n,), num.float) 71 71 72 72 b = A*xe … … 96 96 A[I,I+1] = -1.0 97 97 98 xe = num.ones( (n*m,), num. Float)98 xe = num.ones( (n*m,), num.float) 99 99 100 100 b = A*xe … … 125 125 A[I,I+1] = -1.0 126 126 127 xe = num.ones( (n*m,), num. Float)127 xe = num.ones( (n*m,), num.float) 128 128 129 129 # Convert to csr format … … 158 158 A[I,I+1] = -1.0 159 159 160 xe = num.ones( (n*m,), num. Float)160 xe = num.ones( (n*m,), num.float) 161 161 162 162 b = A*xe -
branches/numpy/anuga/utilities/test_numerical_tools.py
r6174 r6304 3 3 4 4 import unittest 5 import Numericas num5 import numpy as num 6 6 7 7 from math import sqrt, pi … … 68 68 A = [1,2,3,4] 69 69 B = ensure_numeric(A) 70 assert type(B) == num.ArrayType71 assert B. typecode()== 'l'70 assert isinstance(B, num.ndarray) 71 assert B.dtype.char == 'l' 72 72 assert B[0] == 1 and B[1] == 2 and B[2] == 3 and B[3] == 4 73 73 74 74 A = [1,2,3.14,4] 75 75 B = ensure_numeric(A) 76 assert type(B) == num.ArrayType77 assert B. typecode()== 'd'76 assert isinstance(B, num.ndarray) 77 assert B.dtype.char == 'd' 78 78 assert B[0] == 1 and B[1] == 2 and B[2] == 3.14 and B[3] == 4 79 79 80 80 A = [1,2,3,4] 81 B = ensure_numeric(A, num. Float)82 assert type(B) == num.ArrayType83 assert B. typecode()== 'd'81 B = ensure_numeric(A, num.float) 82 assert isinstance(B, num.ndarray) 83 assert B.dtype.char == 'd' 84 84 assert B[0] == 1.0 and B[1] == 2.0 and B[2] == 3.0 and B[3] == 4.0 85 85 86 86 A = [1,2,3,4] 87 B = ensure_numeric(A, num. Float)88 assert type(B) == num.ArrayType89 assert B. typecode()== 'd'87 B = ensure_numeric(A, num.float) 88 assert isinstance(B, num.ndarray) 89 assert B.dtype.char == 'd' 90 90 assert B[0] == 1.0 and B[1] == 2.0 and B[2] == 3.0 and B[3] == 4.0 91 91 92 A = num.array([1,2,3,4] , num.Int) #array default#92 A = num.array([1,2,3,4]) 93 93 B = ensure_numeric(A) 94 assert type(B) == num.ArrayType95 assert B. typecode()== 'l'94 assert isinstance(B, num.ndarray) 95 assert B.dtype.char == 'l' 96 96 assert num.alltrue(A == B) 97 97 assert A is B #Same object 98 98 99 A = num.array([1,2,3,4], num.Int) #array default# 100 B = ensure_numeric(A, num.Float) 101 assert type(B) == num.ArrayType 102 assert B.typecode() == 'd' 99 # THIS FAILS! ASSUMED TYPE IS num.int!? 100 # # check default num.array type, which is supposed to be num.float 101 # A = num.array((1,2,3,4)) 102 # assert isinstance(A, num.ndarray) 103 # assert A.dtype.char == 'd', \ 104 # "Expected dtype='d', got '%s'" % A.dtype.char 105 106 A = num.array([1,2,3,4]) 107 B = ensure_numeric(A, num.float) 108 assert isinstance(B, num.ndarray) 109 assert A.dtype.char == 'l' 110 assert B.dtype.char == 'd' 103 111 assert num.alltrue(A == B) 104 assert A is not B # Not the same object112 assert A is not B # Not the same object 105 113 106 114 # Check scalars 107 115 A = 1 108 B = ensure_numeric(A, num.Float) 109 #print A, B[0], len(B), type(B) 110 #print B.shape 116 B = ensure_numeric(A, num.float) 111 117 assert num.alltrue(A == B) 112 113 B = ensure_numeric(A, num.Int) 114 #print A, B 115 #print B.shape118 # print 'A=%s' % str(A) 119 # print 'B=%s, B.shape=%s' % (str(B), str(B.shape)) 120 121 B = ensure_numeric(A, num.int) 116 122 assert num.alltrue(A == B) 117 123 124 # try to simulate getting (x,0) shape 125 data_points = [[ 413634. ],] 126 array_data_points = ensure_numeric(data_points) 127 #if not (0,) == array_data_points.shape: 128 # assert len(array_data_points.shape) == 2 129 # assert array_data_points.shape[1] == 2 130 131 132 def NO_test_ensure_numeric_char(self): 133 '''numpy can't handle this''' 134 118 135 # Error situation 119 120 B = ensure_numeric('hello', num.Int) 136 B = ensure_numeric('hello', num.int) 121 137 assert num.allclose(B, [104, 101, 108, 108, 111]) 122 138 … … 343 359 assert x == 5. 344 360 345 361 362 ################################################################################ 363 # Test the is_num_????() functions. 364 ################################################################################ 365 366 def test_is_float(self): 367 def t(val, expected): 368 if expected == True: 369 msg = 'should be num.float?' 370 else: 371 msg = 'should not be num.float?' 372 msg = '%s (%s) %s' % (str(val), type(val), msg) 373 assert is_num_float(val) == expected, msg 374 375 t(1, False) 376 t(1.0, False) 377 t('abc', False) 378 t(None, False) 379 t(num.array(None), False) 380 # can't create array(None, num.int) 381 # t(num.array(None, num.int), False) 382 t(num.array(None, num.float), True) 383 t(num.array(()), True) 384 t(num.array((), num.int), False) 385 t(num.array((), num.float), True) 386 t(num.array((1), num.int), False) 387 t(num.array((1), num.float), True) 388 389 t(num.array((1,2)), False) 390 t(num.array((1,2), num.int), False) 391 t(num.array((1,2), num.float), True) 392 t(num.array([1,2]), False) 393 t(num.array([1,2], num.int), False) 394 t(num.array([1,2], num.float), True) 395 396 t(num.array((1.0,2.0)), True) 397 t(num.array((1.0,2.0), num.int), False) 398 t(num.array((1.0,2.0), num.float), True) 399 t(num.array([1.0,2.0]), True) 400 t(num.array([1.0,2.0], num.int), False) 401 t(num.array([1.0,2.0], num.float), True) 402 403 t(num.array(((1.0,2.0),(3.0,4.0))), True) 404 t(num.array(((1.0,2.0),(3.0,4.0)), num.int), False) 405 t(num.array(((1.0,2.0),(3.0,4.0)), num.float), True) 406 t(num.array([[1.0,2.0],[3.0,4.0]]), True) 407 t(num.array([1.0,2.0], num.int), False) 408 t(num.array([1.0,2.0], num.float), True) 409 410 t(num.array('abc'), False) 411 t(num.array('abc', num.character), False) 412 # can't create array as int from string 413 # t(num.array('abc', num.int), False) 414 # can't create array as float from string 415 # t(num.array('abc', num.float), True) 416 417 def test_is_int(self): 418 def t(val, expected): 419 if expected == True: 420 msg = 'should be num.int?' 421 else: 422 msg = 'should not be num.int?' 423 msg = '%s (%s) %s' % (str(val), type(val), msg) 424 assert is_num_int(val) == expected, msg 425 426 t(1, False) 427 t(1.0, False) 428 t('abc', False) 429 t(None, False) 430 t(num.array(None), False) 431 # can't create array(None, num.int) 432 # t(num.array(None, num.int), True) 433 t(num.array(None, num.float), False) 434 t(num.array((), num.int), True) 435 t(num.array(()), False) 436 t(num.array((), num.float), False) 437 t(num.array((1), num.int), True) 438 t(num.array((1), num.float), False) 439 440 t(num.array((1,2)), True) 441 t(num.array((1,2), num.int), True) 442 t(num.array((1,2), num.float), False) 443 t(num.array([1,2]), True) 444 t(num.array([1,2], num.int), True) 445 t(num.array([1,2], num.float), False) 446 447 t(num.array((1.0,2.0)), False) 448 t(num.array((1.0,2.0), num.int), True) 449 t(num.array((1.0,2.0), num.float), False) 450 t(num.array([1.0,2.0]), False) 451 t(num.array([1.0,2.0], num.int), True) 452 t(num.array([1.0,2.0], num.float), False) 453 454 t(num.array(((1.0,2.0),(3.0,4.0))), False) 455 t(num.array(((1.0,2.0),(3.0,4.0)), num.int), True) 456 t(num.array(((1.0,2.0),(3.0,4.0)), num.float), False) 457 t(num.array([[1.0,2.0],[3.0,4.0]]), False) 458 t(num.array([1.0,2.0], num.int), True) 459 t(num.array([1.0,2.0], num.float), False) 460 461 t(num.array('abc'), False) 462 t(num.array('abc', num.character), False) 463 # can't create array as int from string 464 # t(num.array('abc', num.int), True) 465 # can't create array as float from string 466 # t(num.array('abc', num.float), False) 467 346 468 347 469 #------------------------------------------------------------- 348 470 if __name__ == "__main__": 349 suite = unittest.makeSuite(Test_Numerical_Tools,'test')350 #suite = unittest.makeSuite(Test_Numerical_Tools,'test_err')471 #suite = unittest.makeSuite(Test_Numerical_Tools,'test') 472 suite = unittest.makeSuite(Test_Numerical_Tools,'test_is_') 351 473 runner = unittest.TextTestRunner() 352 474 runner.run(suite) -
branches/numpy/anuga/utilities/test_polygon.py
r6215 r6304 1 1 #!/usr/bin/env python 2 2 3 4 3 import unittest 5 import Numericas num4 import numpy as num 6 5 from math import sqrt, pi 7 6 from anuga.utilities.numerical_tools import ensure_numeric … … 12 11 from anuga.geospatial_data.geospatial_data import Geospatial_data 13 12 13 14 14 def test_function(x, y): 15 15 return x+y 16 16 17 17 18 class Test_Polygon(unittest.TestCase): … … 21 22 def tearDown(self): 22 23 pass 23 24 24 25 25 def test_that_C_extension_compiles(self): … … 33 33 compile(FN) 34 34 except: 35 raise 'Could not compile %s' %FN35 raise Exception, 'Could not compile %s' %FN 36 36 else: 37 37 import polygon_ext 38 39 38 40 39 # Polygon stuff … … 43 42 p2 = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]] 44 43 45 f = Polygon_function( [(p1, 1.0)] ) 46 z = f([5, 5, 27, 35], [5, 9, 8, -5]) #Two first inside p1 47 assert num.allclose(z, [1,1,0,0]) 48 49 50 f = Polygon_function( [(p2, 2.0)] ) 51 z = f([5, 5, 27, 35], [5, 9, 8, -5]) # First and last inside p2 52 assert num.allclose(z, [2,0,0,2]) 53 54 55 #Combined 56 f = Polygon_function( [(p1, 1.0), (p2, 2.0)] ) 57 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 58 assert num.allclose(z, [2,1,0,2]) 44 f = Polygon_function([(p1, 1.0)]) 45 z = f([5, 5, 27, 35], [5, 9, 8, -5]) # Two first inside p1 46 assert num.allclose(z, [1, 1, 0, 0]) 47 48 f = Polygon_function([(p2, 2.0)]) 49 z = f([5, 5, 27, 35], [5, 9, 8, -5]) # First and last inside p2 50 assert num.allclose(z, [2, 0, 0, 2]) 51 52 # Combined 53 f = Polygon_function([(p1, 1.0), (p2, 2.0)]) 54 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 55 assert num.allclose(z, [2, 1, 0, 2]) 59 56 60 57 def test_polygon_function_csvfile(self): 61 58 from os import sep, getenv 62 59 63 64 60 # Get path where this test is run 65 61 path = get_pathname_from_package('anuga.utilities') 66 62 67 63 # Form absolute filename and read 68 filename = path + sep + 69 p1 = read_polygon(filename) 70 71 f = Polygon_function( [(p1, 10.0)])72 z = f([430000, 480000], [490000,7720000]) # first outside, second inside73 74 assert num.allclose(z, [0, 10])64 filename = path + sep + 'mainland_only.csv' 65 p1 = read_polygon(filename) 66 67 f = Polygon_function([(p1, 10.0)]) 68 z = f([430000, 480000], [490000, 7720000]) # 1st outside, 2nd inside 69 70 assert num.allclose(z, [0, 10]) 75 71 76 72 def test_polygon_function_georef(self): 77 """Check that georeferencing works 78 """ 73 """Check that georeferencing works""" 79 74 80 75 from anuga.coordinate_transforms.geo_reference import Geo_reference … … 87 82 [230,1010], [240,990]] 88 83 89 f = Polygon_function( [(p1, 1.0)], geo_reference=geo) 90 z = f([5, 5, 27, 35], [5, 9, 8, -5]) #Two first inside p1 91 92 assert num.allclose(z, [1,1,0,0]) 93 94 95 f = Polygon_function( [(p2, 2.0)], geo_reference=geo) 96 z = f([5, 5, 27, 35], [5, 9, 8, -5]) #First and last inside p2 97 assert num.allclose(z, [2,0,0,2]) 98 99 100 # Combined 101 f = Polygon_function( [(p1, 1.0), (p2, 2.0)], geo_reference=geo) 102 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 103 assert num.allclose(z, [2,1,0,2]) 104 105 106 # Check that it would fail without geo 107 f = Polygon_function( [(p1, 1.0), (p2, 2.0)]) 108 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 109 assert not num.allclose(z, [2,1,0,2]) 110 111 84 f = Polygon_function([(p1, 1.0)], geo_reference=geo) 85 z = f([5, 5, 27, 35], [5, 9, 8, -5]) # Two first inside p1 86 87 assert num.allclose(z, [1, 1, 0, 0]) 88 89 f = Polygon_function([(p2, 2.0)], geo_reference=geo) 90 z = f([5, 5, 27, 35], [5, 9, 8, -5]) # First and last inside p2 91 assert num.allclose(z, [2, 0, 0, 2]) 92 93 # Combined 94 f = Polygon_function([(p1, 1.0), (p2, 2.0)], geo_reference=geo) 95 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 96 assert num.allclose(z, [2, 1, 0, 2]) 97 98 # Check that it would fail without geo 99 f = Polygon_function([(p1, 1.0), (p2, 2.0)]) 100 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 101 assert not num.allclose(z, [2, 1, 0, 2]) 112 102 113 103 def test_polygon_function_callable(self): 114 """Check that values passed into Polygon_function can be callable 115 themselves. 116 """ 104 """Check that values passed into Polygon_function can be callable.""" 105 117 106 p1 = [[0,0], [10,0], [10,10], [0,10]] 118 107 p2 = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]] 119 108 120 f = Polygon_function( [(p1, test_function)] ) 121 z = f([5, 5, 27, 35], [5, 9, 8, -5]) #Two first inside p1 122 assert num.allclose(z, [10,14,0,0]) 123 124 # Combined 125 f = Polygon_function( [(p1, test_function), (p2, 2.0)] ) 126 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 127 assert num.allclose(z, [2,14,0,2]) 128 129 130 # Combined w default 131 f = Polygon_function( [(p1, test_function), (p2, 2.0)], default = 3.14) 132 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 133 assert num.allclose(z, [2,14,3.14,2]) 134 135 136 # Combined w default func 137 f = Polygon_function( [(p1, test_function), (p2, 2.0)], 138 default = test_function) 139 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 140 assert num.allclose(z, [2,14,35,2]) 141 142 109 f = Polygon_function([(p1, test_function)]) 110 z = f([5, 5, 27, 35], [5, 9, 8, -5]) # Two first inside p1 111 assert num.allclose(z, [10, 14, 0, 0]) 112 113 # Combined 114 f = Polygon_function([(p1, test_function), (p2, 2.0)]) 115 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 116 assert num.allclose(z, [2, 14, 0, 2]) 117 118 # Combined w default 119 f = Polygon_function([(p1, test_function), (p2, 2.0)], default = 3.14) 120 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 121 assert num.allclose(z, [2, 14, 3.14, 2]) 122 123 # Combined w default func 124 f = Polygon_function([(p1, test_function), (p2, 2.0)], 125 default=test_function) 126 z = f([5, 5, 27, 35], [5, 9, 8, -5]) 127 assert num.allclose(z, [2, 14, 35, 2]) 143 128 144 129 def test_point_on_line(self): 145 146 # Endpoints first 147 assert point_on_line( [0, 0], [[0,0], [1,0]] ) 148 assert point_on_line( [1, 0], [[0,0], [1,0]] ) 149 150 # Then points on line 151 assert point_on_line( [0.5, 0], [[0,0], [1,0]] ) 152 assert point_on_line( [0, 0.5], [[0,1], [0,0]] ) 153 assert point_on_line( [1, 0.5], [[1,1], [1,0]] ) 154 assert point_on_line( [0.5, 0.5], [[0,0], [1,1]] ) 155 156 # Then points not on line 157 assert not point_on_line( [0.5, 0], [[0,1], [1,1]] ) 158 assert not point_on_line( [0, 0.5], [[0,0], [1,1]] ) 159 160 # From real example that failed 161 assert not point_on_line( [40,50], [[40,20], [40,40]] ) 162 163 164 # From real example that failed 165 assert not point_on_line( [40,19], [[40,20], [40,40]] ) 130 # Endpoints first 131 assert point_on_line([0,0], [[0,0], [1,0]]) 132 assert point_on_line([1,0], [[0,0], [1,0]]) 133 134 # Endpoints first - non-simple 135 assert point_on_line([-0.1,0.0], [[-0.1,0.0], [1.5,0.6]]) 136 assert point_on_line([1.5,0.6], [[-0.1,0.0], [1.5,0.6]]) 137 138 # Then points on line 139 assert point_on_line([0.5,0], [[0,0], [1,0]]) 140 assert point_on_line([0,0.5], [[0,1], [0,0]]) 141 assert point_on_line([1,0.5], [[1,1], [1,0]]) 142 assert point_on_line([0.5,0.5], [[0,0], [1,1]]) 143 144 # Then points not on line 145 assert not point_on_line([0.5,0], [[0,1], [1,1]]) 146 assert not point_on_line([0,0.5], [[0,0], [1,1]]) 147 148 # From real example that failed 149 assert not point_on_line([40,50], [[40,20], [40,40]]) 150 151 # From real example that failed 152 assert not point_on_line([40,19], [[40,20], [40,40]]) 166 153 167 154 # Degenerate line 168 assert point_on_line( [40,19], [[40,19], [40,19]] ) 169 assert not point_on_line( [40,19], [[40,40], [40,40]] ) 170 171 155 assert point_on_line([40,19], [[40,19], [40,19]]) 156 assert not point_on_line([40,19], [[40,40], [40,40]]) 172 157 173 158 def test_is_inside_polygon_main(self): 174 175 176 159 # Simplest case: Polygon is the unit square 177 160 polygon = [[0,0], [1,0], [1,1], [0,1]] 178 161 179 assert is_inside_polygon( (0.5, 0.5), polygon ) 180 assert not is_inside_polygon( (0.5, 1.5), polygon ) 181 assert not is_inside_polygon( (0.5, -0.5), polygon ) 182 assert not is_inside_polygon( (-0.5, 0.5), polygon ) 183 assert not is_inside_polygon( (1.5, 0.5), polygon ) 184 185 # Try point on borders 186 assert is_inside_polygon( (1., 0.5), polygon, closed=True) 187 assert is_inside_polygon( (0.5, 1), polygon, closed=True) 188 assert is_inside_polygon( (0., 0.5), polygon, closed=True) 189 assert is_inside_polygon( (0.5, 0.), polygon, closed=True) 190 191 assert not is_inside_polygon( (0.5, 1), polygon, closed=False) 192 assert not is_inside_polygon( (0., 0.5), polygon, closed=False) 193 assert not is_inside_polygon( (0.5, 0.), polygon, closed=False) 194 assert not is_inside_polygon( (1., 0.5), polygon, closed=False) 195 162 assert is_inside_polygon((0.5, 0.5), polygon) 163 assert not is_inside_polygon((0.5, 1.5), polygon) 164 assert not is_inside_polygon((0.5, -0.5), polygon) 165 assert not is_inside_polygon((-0.5, 0.5), polygon) 166 assert not is_inside_polygon((1.5, 0.5), polygon) 167 168 # Try point on borders 169 assert is_inside_polygon((1., 0.5), polygon, closed=True) 170 assert is_inside_polygon((0.5, 1.), polygon, closed=True) 171 assert is_inside_polygon((0., 0.5), polygon, closed=True) 172 assert is_inside_polygon((0.5, 0.), polygon, closed=True) 173 174 assert not is_inside_polygon((0.5, 1.), polygon, closed=False) 175 assert not is_inside_polygon((0., 0.5), polygon, closed=False) 176 assert not is_inside_polygon((0.5, 0.), polygon, closed=False) 177 assert not is_inside_polygon((1., 0.5), polygon, closed=False) 196 178 197 179 def test_inside_polygon_main(self): 198 199 180 # Simplest case: Polygon is the unit square 200 polygon = [[0,0], [1,0], [1,1], [0,1]] 181 polygon = [[0,0], [1,0], [1,1], [0,1]] 201 182 202 183 # From real example (that failed) 203 polygon = [[20,20], [40,20], [40,40], [20,40]] 204 points = [ [40, 50] ] 205 res = inside_polygon(points, polygon) 206 assert len(res) == 0 207 208 polygon = [[20,20], [40,20], [40,40], [20,40]] 209 points = [ [25, 25], [30, 20], [40, 50], [90, 20], [40, 90] ] 210 res = inside_polygon(points, polygon) 211 assert len(res) == 2 212 assert num.allclose(res, [0,1]) 213 214 215 216 # More convoluted and non convex polygon 184 polygon = [[20,20], [40,20], [40,40], [20,40]] 185 points = [[40, 50]] 186 res = inside_polygon(points, polygon) 187 assert len(res) == 0 188 189 polygon = [[20,20], [40,20], [40,40], [20,40]] 190 points = [[25, 25], [30, 20], [40, 50], [90, 20], [40, 90]] 191 res = inside_polygon(points, polygon) 192 assert len(res) == 2 193 assert num.allclose(res, [0,1]) 194 195 # More convoluted and non convex polygon 217 196 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 218 assert is_inside_polygon( (0.5, 0.5), polygon ) 219 assert is_inside_polygon( (1, -0.5), polygon ) 220 assert is_inside_polygon( (1.5, 0), polygon ) 221 222 assert not is_inside_polygon( (0.5, 1.5), polygon ) 223 assert not is_inside_polygon( (0.5, -0.5), polygon ) 224 225 226 # Very convoluted polygon 197 assert is_inside_polygon((0.5, 0.5), polygon) 198 assert is_inside_polygon((1, -0.5), polygon) 199 assert is_inside_polygon((1.5, 0), polygon) 200 201 assert not is_inside_polygon((0.5, 1.5), polygon) 202 assert not is_inside_polygon((0.5, -0.5), polygon) 203 204 # Very convoluted polygon 227 205 polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]] 228 assert is_inside_polygon( (5, 5), polygon ) 229 assert is_inside_polygon( (17, 7), polygon ) 230 assert is_inside_polygon( (27, 2), polygon ) 231 assert is_inside_polygon( (35, -5), polygon ) 232 assert not is_inside_polygon( (15, 7), polygon ) 233 assert not is_inside_polygon( (24, 3), polygon ) 234 assert not is_inside_polygon( (25, -10), polygon ) 235 236 237 238 # Another combination (that failed) 206 assert is_inside_polygon((5, 5), polygon) 207 assert is_inside_polygon((17, 7), polygon) 208 assert is_inside_polygon((27, 2), polygon) 209 assert is_inside_polygon((35, -5), polygon) 210 assert not is_inside_polygon((15, 7), polygon) 211 assert not is_inside_polygon((24, 3), polygon) 212 assert not is_inside_polygon((25, -10), polygon) 213 214 # Another combination (that failed) 239 215 polygon = [[0,0], [10,0], [10,10], [0,10]] 240 assert is_inside_polygon( (5, 5), polygon ) 241 assert is_inside_polygon( (7, 7), polygon ) 242 assert not is_inside_polygon( (-17, 7), polygon ) 243 assert not is_inside_polygon( (7, 17), polygon ) 244 assert not is_inside_polygon( (17, 7), polygon ) 245 assert not is_inside_polygon( (27, 8), polygon ) 246 assert not is_inside_polygon( (35, -5), polygon ) 247 248 249 250 251 # Multiple polygons 252 253 polygon = [[0,0], [1,0], [1,1], [0,1], [0,0], 254 [10,10], [11,10], [11,11], [10,11], [10,10]] 255 assert is_inside_polygon( (0.5, 0.5), polygon ) 256 assert is_inside_polygon( (10.5, 10.5), polygon ) 257 258 #FIXME: Fails if point is 5.5, 5.5 259 assert not is_inside_polygon( (0, 5.5), polygon ) 260 261 # Polygon with a hole 216 assert is_inside_polygon((5, 5), polygon) 217 assert is_inside_polygon((7, 7), polygon) 218 assert not is_inside_polygon((-17, 7), polygon) 219 assert not is_inside_polygon((7, 17), polygon) 220 assert not is_inside_polygon((17, 7), polygon) 221 assert not is_inside_polygon((27, 8), polygon) 222 assert not is_inside_polygon((35, -5), polygon) 223 224 # Multiple polygons 225 polygon = [[0,0], [1,0], [1,1], [0,1], [0,0], [10,10], 226 [11,10], [11,11], [10,11], [10,10]] 227 assert is_inside_polygon((0.5, 0.5), polygon) 228 assert is_inside_polygon((10.5, 10.5), polygon) 229 230 # FIXME: Fails if point is 5.5, 5.5 231 assert not is_inside_polygon((0, 5.5), polygon) 232 233 # Polygon with a hole 262 234 polygon = [[-1,-1], [2,-1], [2,2], [-1,2], [-1,-1], 263 [0,0], [1,0], [1,1], [0,1], [0,0]] 264 265 assert is_inside_polygon( (0, -0.5), polygon ) 266 assert not is_inside_polygon( (0.5, 0.5), polygon ) 267 268 235 [0,0], [1,0], [1,1], [0,1], [0,0]] 236 237 assert is_inside_polygon((0, -0.5), polygon) 238 assert not is_inside_polygon((0.5, 0.5), polygon) 269 239 270 240 def test_duplicate_points_being_ok(self): 271 272 273 241 # Simplest case: Polygon is the unit square 274 242 polygon = [[0,0], [1,0], [1,0], [1,0], [1,1], [0,1], [0,0]] 275 243 276 assert is_inside_polygon( (0.5, 0.5), polygon)277 assert not is_inside_polygon( (0.5, 1.5), polygon)278 assert not is_inside_polygon( (0.5, -0.5), polygon)279 assert not is_inside_polygon( (-0.5, 0.5), polygon)280 assert not is_inside_polygon( (1.5, 0.5), polygon)281 282 283 assert is_inside_polygon((1., 0.5), polygon, closed=True)284 assert is_inside_polygon((0.5, 1), polygon, closed=True)285 assert is_inside_polygon((0., 0.5), polygon, closed=True)286 assert is_inside_polygon((0.5, 0.), polygon, closed=True)287 288 assert not is_inside_polygon((0.5, 1), polygon, closed=False)289 assert not is_inside_polygon((0., 0.5), polygon, closed=False)290 assert not is_inside_polygon((0.5, 0.), polygon, closed=False)291 assert not is_inside_polygon((1., 0.5), polygon, closed=False)244 assert is_inside_polygon((0.5, 0.5), polygon) 245 assert not is_inside_polygon((0.5, 1.5), polygon) 246 assert not is_inside_polygon((0.5, -0.5), polygon) 247 assert not is_inside_polygon((-0.5, 0.5), polygon) 248 assert not is_inside_polygon((1.5, 0.5), polygon) 249 250 # Try point on borders 251 assert is_inside_polygon((1., 0.5), polygon, closed=True) 252 assert is_inside_polygon((0.5, 1), polygon, closed=True) 253 assert is_inside_polygon((0., 0.5), polygon, closed=True) 254 assert is_inside_polygon((0.5, 0.), polygon, closed=True) 255 256 assert not is_inside_polygon((0.5, 1), polygon, closed=False) 257 assert not is_inside_polygon((0., 0.5), polygon, closed=False) 258 assert not is_inside_polygon((0.5, 0.), polygon, closed=False) 259 assert not is_inside_polygon((1., 0.5), polygon, closed=False) 292 260 293 261 # From real example 294 polygon = [[20,20], [40,20], [40,40], [20,40]] 295 points = [ [40, 50] ] 296 res = inside_polygon(points, polygon) 297 assert len(res) == 0 298 299 262 polygon = [[20,20], [40,20], [40,40], [20,40]] 263 points = [[40, 50]] 264 res = inside_polygon(points, polygon) 265 assert len(res) == 0 300 266 301 267 def test_inside_polygon_vector_version(self): 302 268 # Now try the vector formulation returning indices 303 269 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 304 points = [ [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 305 res = inside_polygon( points, polygon, verbose=False ) 306 307 assert num.allclose( res, [0,1,2] ) 270 points = [[0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 271 res = inside_polygon( points, polygon, verbose=False ) 272 assert num.allclose( res, [0,1,2] ) 308 273 309 274 def test_outside_polygon(self): 310 U = [[0,0], [1,0], [1,1], [0,1]] #Unit square311 312 assert not is_outside_polygon( [0.5, 0.5], U ) 275 # unit square 276 U = [[0,0], [1,0], [1,1], [0,1]] 277 313 278 # evaluate to False as the point 0.5, 0.5 is inside the unit square 314 315 assert is_outside_polygon( [1.5, 0.5], U ) 279 assert not is_outside_polygon([0.5, 0.5], U) 280 316 281 # evaluate to True as the point 1.5, 0.5 is outside the unit square 317 318 indices = outside_polygon( [[0.5, 0.5], [1, -0.5], [0.3, 0.2]], U ) 319 assert num.allclose( indices, [1] ) 320 282 assert is_outside_polygon([1.5, 0.5], U) 283 284 indices = outside_polygon([[0.5, 0.5], [1, -0.5], [0.3, 0.2]], U) 285 assert num.allclose(indices, [1]) 286 321 287 # One more test of vector formulation returning indices 322 288 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 323 points = [ [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 324 res = outside_polygon( points, polygon ) 325 326 assert num.allclose( res, [3, 4] ) 327 328 289 points = [[0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 290 res = outside_polygon(points, polygon) 291 assert num.allclose(res, [3, 4]) 329 292 330 293 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 331 points = [ [0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 332 res = outside_polygon( points, polygon ) 333 334 assert num.allclose( res, [0, 4, 5] ) 335 294 points = [[0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], 295 [0.5, 1.5], [0.5, -0.5]] 296 res = outside_polygon(points, polygon) 297 298 assert num.allclose(res, [0, 4, 5]) 299 336 300 def test_outside_polygon2(self): 337 U = [[0,0], [1,0], [1,1], [0,1]] #Unit square338 339 assert not outside_polygon( [0.5, 1.0], U, closed = True ) 301 # unit square 302 U = [[0,0], [1,0], [1,1], [0,1]] 303 340 304 # evaluate to False as the point 0.5, 1.0 is inside the unit square 341 342 assert is_outside_polygon( [0.5, 1.0], U, closed = False ) 305 assert not outside_polygon([0.5, 1.0], U, closed = True) 306 343 307 # evaluate to True as the point 0.5, 1.0 is outside the unit square 308 assert is_outside_polygon([0.5, 1.0], U, closed = False) 344 309 345 310 def test_all_outside_polygon(self): 346 """Test case where all points are outside poly 347 """ 348 349 U = [[0,0], [1,0], [1,1], [0,1]] #Unit square 350 351 points = [[2,2], [1,3], [-1,1], [0,2]] #All outside 352 311 """Test case where all points are outside poly""" 312 313 # unit square 314 U = [[0,0], [1,0], [1,1], [0,1]] 315 316 points = [[2,2], [1,3], [-1,1], [0,2]] # All outside 353 317 354 318 indices, count = separate_points_by_polygon(points, U) 355 #print indices, count 356 assert count == 0 #None inside 357 assert num.allclose(indices, [3,2,1,0]) 319 assert count == 0 # None inside 320 assert num.allclose(indices, [3, 2, 1, 0]) 358 321 359 322 indices = outside_polygon(points, U, closed = True) 360 assert num.allclose(indices, [0, 1,2,3])323 assert num.allclose(indices, [0, 1, 2, 3]) 361 324 362 325 indices = inside_polygon(points, U, closed = True) 363 assert num.allclose(indices, []) 364 326 assert num.allclose(indices, []) 365 327 366 328 def test_all_inside_polygon(self): 367 """Test case where all points are inside poly 368 """ 369 370 U = [[0,0], [1,0], [1,1], [0,1]] #Unit square 371 372 points = [[0.5,0.5], [0.2,0.3], [0,0.5]] #All inside (or on edge) 373 329 """Test case where all points are inside poly""" 330 331 # unit square 332 U = [[0,0], [1,0], [1,1], [0,1]] 333 334 points = [[0.5,0.5], [0.2,0.3], [0,0.5]] # All inside (or on edge) 374 335 375 336 indices, count = separate_points_by_polygon(points, U) 376 assert count == 3 #All inside377 assert num.allclose(indices, [0, 1,2])378 379 indices = outside_polygon(points, U, closed =True)337 assert count == 3 # All inside 338 assert num.allclose(indices, [0, 1, 2]) 339 340 indices = outside_polygon(points, U, closed=True) 380 341 assert num.allclose(indices, []) 381 342 382 indices = inside_polygon(points, U, closed =True)383 assert num.allclose(indices, [0, 1,2])384 343 indices = inside_polygon(points, U, closed=True) 344 assert num.allclose(indices, [0, 1, 2]) 345 385 346 386 347 def test_separate_points_by_polygon(self): 387 U = [[0,0], [1,0], [1,1], [0,1]] #Unit square 388 389 indices, count = separate_points_by_polygon( [[0.5, 0.5], [1, -0.5], [0.3, 0.2]], U ) 390 assert num.allclose( indices, [0,2,1] ) 348 # unit square 349 U = [[0,0], [1,0], [1,1], [0,1]] 350 351 indices, count = separate_points_by_polygon([[0.5, 0.5], 352 [1, -0.5], 353 [0.3, 0.2]], 354 U) 355 assert num.allclose( indices, [0, 2, 1] ) 391 356 assert count == 2 392 393 # One more test of vector formulation returning indices357 358 # One more test of vector formulation returning indices 394 359 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 395 points = [ [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 396 res, count = separate_points_by_polygon( points, polygon ) 397 398 assert num.allclose( res, [0,1,2,4,3] ) 399 assert count == 3 400 360 points = [[0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 361 res, count = separate_points_by_polygon(points, polygon) 362 363 assert num.allclose(res, [0, 1, 2, 4, 3]) 364 assert count == 3 401 365 402 366 polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]] 403 points = [ [0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]] 404 res, count = separate_points_by_polygon( points, polygon ) 405 406 assert num.allclose( res, [1,2,3,5,4,0] ) 407 assert count == 3408 367 points = [[0.5, 1.4], [0.5, 0.5], [1, -0.5], [1.5, 0], 368 [0.5, 1.5], [0.5, -0.5]] 369 res, count = separate_points_by_polygon(points, polygon) 370 371 assert num.allclose( res, [1, 2, 3, 5, 4, 0] ) 372 assert count == 3 409 373 410 374 def test_populate_polygon(self): 411 412 375 polygon = [[0,0], [1,0], [1,1], [0,1]] 413 376 points = populate_polygon(polygon, 5) … … 417 380 assert is_inside_polygon(point, polygon) 418 381 419 420 #Very convoluted polygon 382 # Very convoluted polygon 421 383 polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]] 422 423 384 points = populate_polygon(polygon, 5) 424 425 385 assert len(points) == 5 426 386 for point in points: 427 387 assert is_inside_polygon(point, polygon) 428 388 429 430 389 def test_populate_polygon_with_exclude(self): 431 432 433 390 polygon = [[0,0], [1,0], [1,1], [0,1]] 434 ex_poly = [[0,0], [0.5,0], [0.5, 0.5], [0,0.5]] #SW quarter435 points = populate_polygon(polygon, 5, exclude =[ex_poly])391 ex_poly = [[0,0], [0.5,0], [0.5, 0.5], [0,0.5]] # SW quarter 392 points = populate_polygon(polygon, 5, exclude=[ex_poly]) 436 393 437 394 assert len(points) == 5 438 395 for point in points: 439 396 assert is_inside_polygon(point, polygon) 440 assert not is_inside_polygon(point, ex_poly) 441 442 443 #overlap 397 assert not is_inside_polygon(point, ex_poly) 398 399 # overlap 444 400 polygon = [[0,0], [1,0], [1,1], [0,1]] 445 401 ex_poly = [[-1,-1], [0.5,0], [0.5, 0.5], [-1,0.5]] 446 points = populate_polygon(polygon, 5, exclude =[ex_poly])402 points = populate_polygon(polygon, 5, exclude=[ex_poly]) 447 403 448 404 assert len(points) == 5 449 405 for point in points: 450 406 assert is_inside_polygon(point, polygon) 451 assert not is_inside_polygon(point, ex_poly) 452 453 # Multiple407 assert not is_inside_polygon(point, ex_poly) 408 409 # Multiple 454 410 polygon = [[0,0], [1,0], [1,1], [0,1]] 455 ex_poly1 = [[0,0], [0.5,0], [0.5, 0.5], [0,0.5]] #SW quarter456 ex_poly2 = [[0.5,0.5], [0.5,1], [1, 1], [1,0.5]] #NE quarter457 458 points = populate_polygon(polygon, 20, exclude =[ex_poly1, ex_poly2])411 ex_poly1 = [[0,0], [0.5,0], [0.5, 0.5], [0,0.5]] # SW quarter 412 ex_poly2 = [[0.5,0.5], [0.5,1], [1, 1], [1,0.5]] # NE quarter 413 414 points = populate_polygon(polygon, 20, exclude=[ex_poly1, ex_poly2]) 459 415 460 416 assert len(points) == 20 … … 462 418 assert is_inside_polygon(point, polygon) 463 419 assert not is_inside_polygon(point, ex_poly1) 464 assert not is_inside_polygon(point, ex_poly2) 465 466 467 #Very convoluted polygon 420 assert not is_inside_polygon(point, ex_poly2) 421 422 # Very convoluted polygon 468 423 polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]] 469 424 ex_poly = [[-1,-1], [5,0], [5, 5], [-1,5]] 470 points = populate_polygon(polygon, 20, exclude =[ex_poly])471 425 points = populate_polygon(polygon, 20, exclude=[ex_poly]) 426 472 427 assert len(points) == 20 473 428 for point in points: 474 429 assert is_inside_polygon(point, polygon) 475 assert not is_inside_polygon(point, ex_poly), '%s' %str(point) 476 430 assert not is_inside_polygon(point, ex_poly), '%s' % str(point) 477 431 478 432 def test_populate_polygon_with_exclude2(self): 479 480 481 min_outer = 0 433 min_outer = 0 482 434 max_outer = 1000 483 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer],484 [max_outer,max_outer],[min_outer,max_outer]]435 polygon_outer = [[min_outer,min_outer], [max_outer,min_outer], 436 [max_outer,max_outer], [min_outer,max_outer]] 485 437 486 438 delta = 10 487 439 min_inner1 = min_outer + delta 488 440 max_inner1 = max_outer - delta 489 inner1_polygon = [[min_inner1,min_inner1], [max_inner1,min_inner1],490 [max_inner1,max_inner1],[min_inner1,max_inner1]]491 492 493 density_inner2 = 1000494 m in_inner2 = min_outer +2*delta495 max_inner2 = max_outer - 2*delta496 inner2_polygon = [[min_inner2,min_inner2],[max_inner2,min_inner2],497 [max_inner2,max_inner2],[min_inner2,max_inner2]] 498 499 points = populate_polygon(polygon_outer, 20, exclude =[inner1_polygon, inner2_polygon])441 inner1_polygon = [[min_inner1,min_inner1], [max_inner1,min_inner1], 442 [max_inner1,max_inner1], [min_inner1,max_inner1]] 443 444 density_inner2 = 1000 445 min_inner2 = min_outer + 2*delta 446 max_inner2 = max_outer - 2*delta 447 inner2_polygon = [[min_inner2,min_inner2], [max_inner2,min_inner2], 448 [max_inner2,max_inner2], [min_inner2,max_inner2]] 449 450 points = populate_polygon(polygon_outer, 20, 451 exclude=[inner1_polygon, inner2_polygon]) 500 452 501 453 assert len(points) == 20 … … 503 455 assert is_inside_polygon(point, polygon_outer) 504 456 assert not is_inside_polygon(point, inner1_polygon) 505 assert not is_inside_polygon(point, inner2_polygon) 506 507 508 #Very convoluted polygon 457 assert not is_inside_polygon(point, inner2_polygon) 458 459 # Very convoluted polygon 509 460 polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]] 510 461 ex_poly = [[-1,-1], [5,0], [5, 5], [-1,5]] 511 points = populate_polygon(polygon, 20, exclude =[ex_poly])512 462 points = populate_polygon(polygon, 20, exclude=[ex_poly]) 463 513 464 assert len(points) == 20 514 465 for point in points: 515 466 assert is_inside_polygon(point, polygon) 516 assert not is_inside_polygon(point, ex_poly), '%s' % str(point)467 assert not is_inside_polygon(point, ex_poly), '%s' % str(point) 517 468 518 469 def test_point_in_polygon(self): … … 521 472 assert is_inside_polygon(point, polygon) 522 473 523 # this may get into a vicious loop524 # polygon = [[1e32,1e54], [1,0], [1,1], [0,1]]525 474 # this may get into a vicious loop 475 # polygon = [[1e32,1e54], [1,0], [1,1], [0,1]] 476 526 477 polygon = [[1e15,1e7], [1,0], [1,1], [0,1]] 527 478 point = point_in_polygon(polygon) 528 479 assert is_inside_polygon(point, polygon) 529 480 530 531 481 polygon = [[0,0], [1,0], [1,1], [1e8,1e8]] 532 482 point = point_in_polygon(polygon) 533 483 assert is_inside_polygon(point, polygon) 534 484 535 536 485 polygon = [[1e32,1e54], [-1e32,1e54], [1e32,-1e54]] 537 486 point = point_in_polygon(polygon) 538 487 assert is_inside_polygon(point, polygon) 539 488 540 541 489 polygon = [[1e18,1e15], [1,0], [0,1]] 542 490 point = point_in_polygon(polygon) … … 544 492 545 493 def test_in_and_outside_polygon_main(self): 546 547 548 #Simplest case: Polygon is the unit square 494 # Simplest case: Polygon is the unit square 549 495 polygon = [[0,0], [1,0], [1,1], [0,1]] 550 496 551 inside, outside = in_and_outside_polygon( (0.5, 0.5), polygon)552 553 554 555 inside, outside = in_and_outside_polygon( (1., 0.5), polygon, closed=True)556 assert inside[0] == 0 557 assert len(outside)== 0558 559 inside, outside = in_and_outside_polygon( (1., 0.5), polygon, closed=False) 560 assert len(inside) == 0 561 assert outside[0] == 0 562 563 points = [(1., 0.25),(1., 0.75) ]564 inside, outside = in_and_outside_polygon( points, polygon, closed=True) 565 assert (inside, [0,1]) 566 assert len(outside) == 0 567 568 inside, outside = in_and_outside_polygon( points, polygon, closed=False)569 assert len(inside) == 0 570 assert (outside, [0,1])571 572 573 points = [(100., 0.25),(0.5, 0.5) ] 574 inside, outside = in_and_outside_polygon( points, polygon)575 assert (inside, [1])576 assert outside[0] == 0 577 578 points = [(100., 0.25),(0.5, 0.5), (39,20), (0.6,0.7),(56,43),(67,90) ] 579 inside, outside = in_and_outside_polygon( points, polygon)580 assert (inside, [1,3])581 assert (outside, [0,2,4,5])582 497 inside, outside = in_and_outside_polygon((0.5, 0.5), polygon) 498 assert inside[0] == 0 499 assert len(outside) == 0 500 501 inside, outside = in_and_outside_polygon((1., 0.5), polygon, 502 closed=True) 503 assert inside[0] == 0 504 assert len(outside) == 0 505 506 inside, outside = in_and_outside_polygon((1., 0.5), polygon, 507 closed=False) 508 assert len(inside) == 0 509 assert outside[0] == 0 510 511 points = [(1., 0.25),(1., 0.75)] 512 inside, outside = in_and_outside_polygon(points, polygon, closed=True) 513 assert (inside, [0,1]) 514 assert len(outside) == 0 515 516 inside, outside = in_and_outside_polygon(points, polygon, closed=False) 517 assert len(inside) == 0 518 assert (outside, [0,1]) 519 520 points = [(100., 0.25), (0.5, 0.5) ] 521 inside, outside = in_and_outside_polygon(points, polygon) 522 assert (inside, [1]) 523 assert outside[0] == 0 524 525 points = [(100., 0.25),(0.5, 0.5), (39,20), (0.6,0.7),(56,43),(67,90)] 526 inside, outside = in_and_outside_polygon(points, polygon) 527 assert (inside, [1, 3]) 528 assert (outside, [0, 2, 4, 5]) 583 529 584 530 def test_intersection1(self): … … 608 554 status, value = intersection(line1, line0) 609 555 assert status == 1 610 assert num.allclose(value, [12.0, 6.0]) 611 556 assert num.allclose(value, [12.0, 6.0]) 557 612 558 def test_intersection3(self): 613 559 line0 = [[0,0], [24,12]] … … 623 569 status, value = intersection(line0, line1) 624 570 assert status == 1 625 assert num.allclose(value, [14.068965517, 7.0344827586]) 571 assert num.allclose(value, [14.068965517, 7.0344827586]) 626 572 627 573 # Swap order of lines 628 574 status, value = intersection(line1, line0) 629 assert status == 1 630 assert num.allclose(value, [14.068965517, 7.0344827586]) 631 575 assert status == 1 576 assert num.allclose(value, [14.068965517, 7.0344827586]) 632 577 633 578 def test_intersection_endpoints(self): … … 636 581 Test that coinciding endpoints are picked up 637 582 """ 583 638 584 line0 = [[0,0], [1,1]] 639 585 line1 = [[1,1], [2,1]] … … 643 589 assert num.allclose(value, [1.0, 1.0]) 644 590 645 646 591 line0 = [[1,1], [2,0]] 647 592 line1 = [[1,1], [2,1]] … … 649 594 status, value = intersection(line0, line1) 650 595 assert status == 1 651 assert num.allclose(value, [1.0, 1.0]) 652 596 assert num.allclose(value, [1.0, 1.0]) 653 597 654 598 # This function is a helper function for … … 660 604 # 0: ---->---- 661 605 # 1: --------->----------- 662 line0 = [P1, P2]663 line1 = [P3, P4]606 line0 = [P1, P2] 607 line1 = [P3, P4] 664 608 status, value = intersection(line0, line1) 665 609 self.failIf(status!=3, 'Expected status 3, got status=%s, value=%s' % … … 671 615 # 0: ----<---- 672 616 # 1: ---------<----------- 673 line0 = [P2, P1]674 line1 = [P4, P3]617 line0 = [P2, P1] 618 line1 = [P4, P3] 675 619 status, value = intersection(line0, line1) 676 620 self.failIf(status!=3, 'Expected status 3, got status=%s, value=%s' % … … 682 626 # 0: ----<---- 683 627 # 1: --------->----------- 684 line0 = [P2, P1]685 line1 = [P3, P4]628 line0 = [P2, P1] 629 line1 = [P3, P4] 686 630 status, value = intersection(line0, line1) 687 631 self.failIf(status!=3, 'Expected status 3, got status=%s, value=%s' % … … 693 637 # 0: ---->---- 694 638 # 1: ---------<----------- 695 line0 = [P1, P2]696 line1 = [P4, P3]639 line0 = [P1, P2] 640 line1 = [P4, P3] 697 641 status, value = intersection(line0, line1) 698 642 self.failIf(status!=3, 'Expected status 3, got status=%s, value=%s' % … … 701 645 str(value)) 702 646 703 # ----------------------------------------------------------------------647 # ---------------------------------------------------------------------- 704 648 705 649 # line0 fully within line1, same direction … … 708 652 # value should be line0: 709 653 # ---->---- 710 line0 = [P2, P3]711 line1 = [P1, P4]654 line0 = [P2, P3] 655 line1 = [P1, P4] 712 656 status, value = intersection(line0, line1) 713 657 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 720 664 # value should be line0: 721 665 # ----<---- 722 line0 = [P3, P2]723 line1 = [P4, P1]666 line0 = [P3, P2] 667 line1 = [P4, P1] 724 668 status, value = intersection(line0, line1) 725 669 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 732 676 # value should be line0: 733 677 # ----<---- 734 line0 = [P3, P2]735 line1 = [P1, P4]678 line0 = [P3, P2] 679 line1 = [P1, P4] 736 680 status, value = intersection(line0, line1) 737 681 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 744 688 # value should be line0: 745 689 # ---->---- 746 line0 = [P2, P3]747 line1 = [P4, P1]690 line0 = [P2, P3] 691 line1 = [P4, P1] 748 692 status, value = intersection(line0, line1) 749 693 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 751 695 self.failUnless(num.allclose(value, line0)) 752 696 753 # ----------------------------------------------------------------------697 # ---------------------------------------------------------------------- 754 698 755 699 # line1 fully within line0, same direction … … 758 702 # value should be line1: 759 703 # ---->---- 760 line0 = [P1, P4]761 line1 = [P2, P3]704 line0 = [P1, P4] 705 line1 = [P2, P3] 762 706 status, value = intersection(line0, line1) 763 707 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 770 714 # value should be line1: 771 715 # ----<---- 772 line0 = [P4, P1]773 line1 = [P3, P2]716 line0 = [P4, P1] 717 line1 = [P3, P2] 774 718 status, value = intersection(line0, line1) 775 719 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 782 726 # value should be line1: 783 727 # ---->---- 784 line0 = [P4, P1]785 line1 = [P2, P3]728 line0 = [P4, P1] 729 line1 = [P2, P3] 786 730 status, value = intersection(line0, line1) 787 731 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 794 738 # value should be line1: 795 739 # ----<---- 796 line0 = [P1, P4]797 line1 = [P3, P2]740 line0 = [P1, P4] 741 line1 = [P3, P2] 798 742 status, value = intersection(line0, line1) 799 743 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 801 745 self.failUnless(num.allclose(value, line1)) 802 746 803 # ----------------------------------------------------------------------747 # ---------------------------------------------------------------------- 804 748 805 749 # line in same direction, partial overlap … … 808 752 # value should be segment line1_start->line0_end: 809 753 # --->---- 810 line0 = [P1, P3]811 line1 = [P2, P4]754 line0 = [P1, P3] 755 line1 = [P2, P4] 812 756 status, value = intersection(line0, line1) 813 757 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 820 764 # value should be segment line0_start->line1_end: 821 765 # ---<---- 822 line0 = [P3, P1]823 line1 = [P4, P2]766 line0 = [P3, P1] 767 line1 = [P4, P2] 824 768 status, value = intersection(line0, line1) 825 769 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 832 776 # value should be segment line0_start->line1_start: 833 777 # ---<---- 834 line0 = [P3, P1]835 line1 = [P2, P4]778 line0 = [P3, P1] 779 line1 = [P2, P4] 836 780 status, value = intersection(line0, line1) 837 781 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 844 788 # value should be segment line1_end->line0_end: 845 789 # --->---- 846 line0 = [P1, P3]847 line1 = [P4, P2]790 line0 = [P1, P3] 791 line1 = [P4, P2] 848 792 status, value = intersection(line0, line1) 849 793 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 851 795 self.failUnless(num.allclose(value, [line1[1],line0[1]])) 852 796 853 # ----------------------------------------------------------------------797 # ---------------------------------------------------------------------- 854 798 855 799 # line in same direction, partial overlap … … 858 802 # value should be segment line0_start->line1_end: 859 803 # --->---- 860 line0 = [P2, P4]861 line1 = [P1, P3]804 line0 = [P2, P4] 805 line1 = [P1, P3] 862 806 status, value = intersection(line0, line1) 863 807 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 870 814 # value should be segment line1_start->line0_end: 871 815 # ----<----- 872 line0 = [P4, P2]873 line1 = [P3, P1]816 line0 = [P4, P2] 817 line1 = [P3, P1] 874 818 status, value = intersection(line0, line1) 875 819 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 882 826 # value should be segment line1_end->line0_end: 883 827 # --->---- 884 line0 = [P4, P2]885 line1 = [P1, P3]828 line0 = [P4, P2] 829 line1 = [P1, P3] 886 830 status, value = intersection(line0, line1) 887 831 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 894 838 # value should be segment line0_start->line1_start: 895 839 # ---<---- 896 line0 = [P2, P4]897 line1 = [P3, P1]840 line0 = [P2, P4] 841 line1 = [P3, P1] 898 842 status, value = intersection(line0, line1) 899 843 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 901 845 self.failUnless(num.allclose(value, [line0[0],line1[0]])) 902 846 903 # ----------------------------------------------------------------------847 # ---------------------------------------------------------------------- 904 848 905 849 # line in same direction, same left point, line1 longer … … 908 852 # value should be line0: 909 853 # ----->------ 910 line0 = [P1, P3]911 line1 = [P1, P4]854 line0 = [P1, P3] 855 line1 = [P1, P4] 912 856 status, value = intersection(line0, line1) 913 857 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 920 864 # value should be line0: 921 865 # -----<------ 922 line0 = [P3, P1]923 line1 = [P4, P1]866 line0 = [P3, P1] 867 line1 = [P4, P1] 924 868 status, value = intersection(line0, line1) 925 869 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 932 876 # value should be line0: 933 877 # ----->------ 934 line0 = [P1, P3]935 line1 = [P4, P1]878 line0 = [P1, P3] 879 line1 = [P4, P1] 936 880 status, value = intersection(line0, line1) 937 881 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 944 888 # value should be line0: 945 889 # -----<------ 946 line0 = [P3, P1]947 line1 = [P1, P4]890 line0 = [P3, P1] 891 line1 = [P1, P4] 948 892 status, value = intersection(line0, line1) 949 893 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 951 895 self.failUnless(num.allclose(value, line0)) 952 896 953 # ----------------------------------------------------------------------897 # ---------------------------------------------------------------------- 954 898 955 899 # line in same direction, same left point, same right point … … 958 902 # value should be line0 or line1: 959 903 # ------->-------- 960 line0 = [P1, P3]961 line1 = [P1, P3]904 line0 = [P1, P3] 905 line1 = [P1, P3] 962 906 status, value = intersection(line0, line1) 963 907 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 970 914 # value should be line0 (or line1): 971 915 # -------<-------- 972 line0 = [P3, P1]973 line1 = [P3, P1]916 line0 = [P3, P1] 917 line1 = [P3, P1] 974 918 status, value = intersection(line0, line1) 975 919 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 982 926 # value should be line0: 983 927 # ------->-------- 984 line0 = [P1, P3]985 line1 = [P3, P1]928 line0 = [P1, P3] 929 line1 = [P3, P1] 986 930 status, value = intersection(line0, line1) 987 931 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 994 938 # value should be line0: 995 939 # -------<-------- 996 line0 = [P3, P1]997 line1 = [P1, P3]940 line0 = [P3, P1] 941 line1 = [P1, P3] 998 942 status, value = intersection(line0, line1) 999 943 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1001 945 self.failUnless(num.allclose(value, line0)) 1002 946 1003 # ----------------------------------------------------------------------947 # ---------------------------------------------------------------------- 1004 948 1005 949 # line in same direction, same right point, line1 longer … … 1008 952 # value should be line0: 1009 953 # ----->------ 1010 line0 = [P2, P4]1011 line1 = [P1, P4]954 line0 = [P2, P4] 955 line1 = [P1, P4] 1012 956 status, value = intersection(line0, line1) 1013 957 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1020 964 # value should be line0: 1021 965 # -----<------ 1022 line0 = [P4, P2]1023 line1 = [P4, P1]966 line0 = [P4, P2] 967 line1 = [P4, P1] 1024 968 status, value = intersection(line0, line1) 1025 969 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1032 976 # value should be line0: 1033 977 # ----->------ 1034 line0 = [P2, P4]1035 line1 = [P4, P1]978 line0 = [P2, P4] 979 line1 = [P4, P1] 1036 980 status, value = intersection(line0, line1) 1037 981 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1044 988 # value should be line0: 1045 989 # -----<------ 1046 line0 = [P4, P2]1047 line1 = [P1, P4]990 line0 = [P4, P2] 991 line1 = [P1, P4] 1048 992 status, value = intersection(line0, line1) 1049 993 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1051 995 self.failUnless(num.allclose(value, line0)) 1052 996 1053 # ----------------------------------------------------------------------997 # ---------------------------------------------------------------------- 1054 998 1055 999 # line in same direction, same left point, line0 longer … … 1058 1002 # value should be line1: 1059 1003 # ----->------ 1060 line0 = [P1, P4]1061 line1 = [P1, P3]1004 line0 = [P1, P4] 1005 line1 = [P1, P3] 1062 1006 status, value = intersection(line0, line1) 1063 1007 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1070 1014 # value should be line1: 1071 1015 # -----<------ 1072 line0 = [P4, P1]1073 line1 = [P3, P1]1016 line0 = [P4, P1] 1017 line1 = [P3, P1] 1074 1018 status, value = intersection(line0, line1) 1075 1019 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1082 1026 # value should be line1: 1083 1027 # -----<------ 1084 line0 = [P1, P4]1085 line1 = [P3, P1]1028 line0 = [P1, P4] 1029 line1 = [P3, P1] 1086 1030 status, value = intersection(line0, line1) 1087 1031 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1094 1038 # value should be line1: 1095 1039 # ----->------ 1096 line0 = [P4, P1]1097 line1 = [P1, P3]1040 line0 = [P4, P1] 1041 line1 = [P1, P3] 1098 1042 status, value = intersection(line0, line1) 1099 1043 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1101 1045 self.failUnless(num.allclose(value, line1)) 1102 1046 1103 # ----------------------------------------------------------------------1047 # ---------------------------------------------------------------------- 1104 1048 1105 1049 # line in same direction, same right point, line0 longer … … 1108 1052 # value should be line1: 1109 1053 # ----->------ 1110 line0 = [P1, P4]1111 line1 = [P2, P4]1054 line0 = [P1, P4] 1055 line1 = [P2, P4] 1112 1056 status, value = intersection(line0, line1) 1113 1057 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1120 1064 # value should be line1: 1121 1065 # -----<------ 1122 line0 = [P4, P1]1123 line1 = [P4, P2]1066 line0 = [P4, P1] 1067 line1 = [P4, P2] 1124 1068 status, value = intersection(line0, line1) 1125 1069 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1132 1076 # value should be line1: 1133 1077 # -----<------ 1134 line0 = [P1, P4]1135 line1 = [P4, P2]1078 line0 = [P1, P4] 1079 line1 = [P4, P2] 1136 1080 status, value = intersection(line0, line1) 1137 1081 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1144 1088 # value should be line1: 1145 1089 # ----->------ 1146 line0 = [P4, P1]1147 line1 = [P2, P4]1090 line0 = [P4, P1] 1091 line1 = [P2, P4] 1148 1092 status, value = intersection(line0, line1) 1149 1093 self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' % … … 1151 1095 self.failUnless(num.allclose(value, line1)) 1152 1096 1153 1097 1154 1098 def test_intersection_bug_20081110_TR(self): 1155 1099 """test_intersection_bug_20081110(self) … … 1164 1108 P3 = [3.0, 3.0] 1165 1109 P4 = [4.0, 4.0] 1166 1110 1167 1111 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1168 1112 P1 = [1.0, 1.0+1.0e-9] 1169 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1113 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1170 1114 P1 = [1.0, 1.0] 1171 1115 P2 = [2.0, 2.0+1.0e-9] 1172 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1116 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1173 1117 P2 = [2.0, 2.0] 1174 1118 P3 = [3.0, 3.0+1.0e-9] 1175 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1119 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1176 1120 P3 = [3.0, 3.0] 1177 1121 P4 = [4.0, 4.0+1.0e-9] 1178 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1122 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1179 1123 1180 1124 def test_intersection_bug_20081110_TL(self): … … 1190 1134 P3 = [-3.0, 3.0] 1191 1135 P4 = [-4.0, 4.0] 1192 1136 1193 1137 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1194 1138 P1 = [-1.0, 1.0+1.0e-9] 1195 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1139 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1196 1140 P1 = [-1.0, 1.0] 1197 1141 P2 = [-2.0, 2.0+1.0e-9] 1198 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1142 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1199 1143 P2 = [-2.0, 2.0] 1200 1144 P3 = [-3.0, 3.0+1.0e-9] 1201 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1145 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1202 1146 P3 = [-3.0, 3.0] 1203 1147 P4 = [-4.0, 4.0+1.0e-9] 1204 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1148 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1205 1149 1206 1150 def test_intersection_bug_20081110_BL(self): … … 1216 1160 P3 = [-3.0, -3.0] 1217 1161 P4 = [-4.0, -4.0] 1218 1162 1219 1163 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1220 1164 P1 = [-1.0, -1.0+1.0e-9] 1221 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1165 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1222 1166 P1 = [-1.0, -1.0] 1223 1167 P2 = [-2.0, -2.0+1.0e-9] 1224 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1168 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1225 1169 P2 = [-2.0, -2.0] 1226 1170 P3 = [-3.0, -3.0+1.0e-9] 1227 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1171 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1228 1172 P3 = [-3.0, -3.0] 1229 1173 P4 = [-4.0, -4.0+1.0e-9] 1230 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1174 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1231 1175 1232 1176 def test_intersection_bug_20081110_BR(self): … … 1242 1186 P3 = [3.0, -3.0] 1243 1187 P4 = [4.0, -4.0] 1244 1188 1245 1189 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1246 1190 P1 = [1.0, -1.0+1.0e-9] 1247 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1191 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1248 1192 P1 = [1.0, -1.0] 1249 1193 P2 = [2.0, -2.0+1.0e-9] 1250 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1194 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1251 1195 P2 = [2.0, -2.0] 1252 1196 P3 = [3.0, -3.0+1.0e-9] 1253 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1197 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1254 1198 P3 = [3.0, -3.0] 1255 1199 P4 = [4.0, -4.0+1.0e-9] 1256 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1200 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1257 1201 1258 1202 def test_intersection_bug_20081110_TR_TL(self): … … 1263 1207 1264 1208 # define 4 collinear points, 1 in TL, 3 in TR 1265 # P1- --P2---P3---P41209 # P1-+-P2---P3---P4 1266 1210 P1 = [-3.0, 1.0] 1267 1211 P2 = [ 1.0, 5.0] … … 1271 1215 1272 1216 # define 4 collinear points, 2 in TL, 2 in TR 1273 # P1---P2- --P3---P41217 # P1---P2-+-P3---P4 1274 1218 P1 = [-3.0, 1.0] 1275 1219 P2 = [-2.0, 2.0] … … 1278 1222 self.helper_test_parallel_intersection_code(P1, P2, P3, P4) 1279 1223 1280 # define 4 collinear points, 2in TL, 1 in TR1281 # P1---P2---P3- --P41224 # define 4 collinear points, 3 in TL, 1 in TR 1225 # P1---P2---P3-+-P4 1282 1226 P1 = [-3.0, 1.0] 1283 1227 P2 = [-2.0, 2.0] … … 1293 1237 1294 1238 # define 4 collinear points, 1 in BL, 3 in TR 1295 # P1- --P2---P3---P41239 # P1-+-P2---P3---P4 1296 1240 P1 = [-4.0, -3.0] 1297 1241 P2 = [ 1.0, 2.0] … … 1301 1245 1302 1246 # define 4 collinear points, 2 in TL, 2 in TR 1303 # P1---P2- --P3---P41247 # P1---P2-+-P3---P4 1304 1248 P1 = [-4.0, -3.0] 1305 1249 P2 = [-3.0, -2.0] … … 1309 1253 1310 1254 # define 4 collinear points, 3 in TL, 1 in TR 1311 # P1---P2---P3- --P41255 # P1---P2---P3-+-P4 1312 1256 P1 = [-4.0, -3.0] 1313 1257 P2 = [-3.0, -2.0] … … 1323 1267 1324 1268 # define 4 collinear points, 1 in BR, 3 in TR 1325 # P1- --P2---P3---P41269 # P1-+-P2---P3---P4 1326 1270 P1 = [ 1.0, -3.0] 1327 1271 P2 = [ 5.0, 1.0] … … 1331 1275 1332 1276 # define 4 collinear points, 2 in BR, 2 in TR 1333 # P1---P2- --P3---P41277 # P1---P2-+-P3---P4 1334 1278 P1 = [ 1.0, -3.0] 1335 1279 P2 = [ 2.0, -2.0] … … 1339 1283 1340 1284 # define 4 collinear points, 3 in BR, 1 in TR 1341 # P1---P2---P3- --P41285 # P1---P2---P3-+-P4 1342 1286 P1 = [ 1.0, -3.0] 1343 1287 P2 = [ 2.0, -2.0] … … 1348 1292 1349 1293 def test_intersection_direction_invariance(self): 1350 """This runs through a number of examples and checks that direction of lines don't matter. 1294 """This runs through a number of examples and checks that 1295 direction of lines don't matter. 1351 1296 """ 1352 1297 1353 1298 line0 = [[0,0], [100,100]] 1354 1299 1355 1300 common_end_point = [20, 150] 1356 1301 1357 1302 for i in range(100): 1358 1303 x = 20 + i * 1.0/100 … … 1362 1307 assert status == 1 1363 1308 1364 1365 1309 # Swap direction of line1 1366 line1 = [common_end_point, [x,0]] 1310 line1 = [common_end_point, [x,0]] 1367 1311 status, p2 = intersection(line0, line1) 1368 assert status == 1 1369 1370 msg = 'Orientation of line shouldn not matter.\n' 1371 msg += 'However, segment [%f,%f], [%f, %f]' %(x, 1372 0, 1373 common_end_point[0], 1374 common_end_point[1]) 1375 msg += ' gave %s, \nbut when reversed we got %s' %(p1, p2) 1312 assert status == 1 1313 1314 msg = ('Orientation of line shouldn not matter.\n' 1315 'However, segment [%f,%f], [%f, %f]' % 1316 (x, 0, common_end_point[0], common_end_point[1])) 1317 msg += ' gave %s, \nbut when reversed we got %s' % (p1, p2) 1376 1318 assert num.allclose(p1, p2), msg 1377 1319 1378 1320 # Swap order of lines 1379 1321 status, p3 = intersection(line1, line0) 1380 assert status == 1 1322 assert status == 1 1381 1323 msg = 'Order of lines gave different results' 1382 1324 assert num.allclose(p1, p3), msg 1383 1384 1325 1385 1326 def test_no_intersection(self): … … 1390 1331 assert status == 0 1391 1332 assert value is None 1392 1393 1333 1394 1334 def test_intersection_parallel(self): … … 1397 1337 1398 1338 status, value = intersection(line0, line1) 1399 assert status == 4 1339 assert status == 4 1400 1340 assert value is None 1401 1402 1341 1403 1342 line0 = [[0,0], [10,100]] … … 1405 1344 1406 1345 status, value = intersection(line0, line1) 1407 assert status == 4 1408 assert value is None 1409 1346 assert status == 4 1347 assert value is None 1410 1348 1411 1349 def test_intersection_coincide(self): 1412 """def test_intersection_coincide(self): 1413 Test what happens whe two lines partly coincide 1414 """ 1350 """Test what happens when two lines partly coincide""" 1415 1351 1416 1352 # Overlap 1 … … 1428 1364 status, value = intersection(line0, line1) 1429 1365 assert status == 2 1430 assert num.allclose(value, [[-3, 0], [5,0]]) 1366 assert num.allclose(value, [[-3, 0], [5,0]]) 1431 1367 1432 1368 # Inclusion 1 … … 1435 1371 1436 1372 status, value = intersection(line0, line1) 1437 assert status == 2 1373 assert status == 2 1438 1374 assert num.allclose(value, line1) 1439 1375 … … 1443 1379 1444 1380 status, value = intersection(line0, line1) 1445 assert status == 2 1446 assert num.allclose(value, line0) 1447 1381 assert status == 2 1382 assert num.allclose(value, line0) 1448 1383 1449 1384 # Exclusion (no intersection) … … 1452 1387 1453 1388 status, value = intersection(line0, line1) 1454 assert status == 3 1389 assert status == 3 1455 1390 assert value is None 1456 1457 1391 1458 1392 # Try examples with some slope (y=2*x+5) … … 1462 1396 line1 = [[1,7], [10,25]] 1463 1397 status, value = intersection(line0, line1) 1464 assert status == 2 1398 assert status == 2 1465 1399 assert num.allclose(value, [[1, 7], [7, 19]]) 1466 1400 … … 1480 1414 status, value = intersection(line0, line1) 1481 1415 assert status == 2 1482 assert num.allclose(value, [[1, 7], [7, 19]]) 1483 1416 assert num.allclose(value, [[1, 7], [7, 19]]) 1484 1417 1485 1418 # Inclusion … … 1487 1420 line1 = [[0,5], [10,25]] 1488 1421 status, value = intersection(line0, line1) 1489 assert status == 2 1490 assert num.allclose(value, [[1,7], [7, 19]]) 1422 assert status == 2 1423 assert num.allclose(value, [[1,7], [7, 19]]) 1491 1424 1492 1425 line0 = [[0,5], [10,25]] 1493 1426 line1 = [[1,7], [7,19]] 1494 1427 status, value = intersection(line0, line1) 1495 assert status == 2 1428 assert status == 2 1496 1429 assert num.allclose(value, [[1,7], [7, 19]]) 1497 1498 1430 1499 1431 line0 = [[0,5], [10,25]] 1500 1432 line1 = [[7,19], [1,7]] 1501 1433 status, value = intersection(line0, line1) 1502 assert status == 2 1503 assert num.allclose(value, [[7, 19], [1, 7]]) 1504 1505 1506 def zzztest_inside_polygon_main(self): \ 1507 1508 #FIXME (Ole): Why is this disabled? 1434 assert status == 2 1435 assert num.allclose(value, [[7, 19], [1, 7]]) 1436 1437 1438 def zzztest_inside_polygon_main(self): 1439 # FIXME (Ole): Why is this disabled? 1509 1440 print "inside",inside 1510 1441 print "outside",outside 1511 1512 assert not inside_polygon( (0.5, 1.5), polygon ) 1513 assert not inside_polygon( (0.5, -0.5), polygon ) 1514 assert not inside_polygon( (-0.5, 0.5), polygon ) 1515 assert not inside_polygon( (1.5, 0.5), polygon ) 1516 1517 #Try point on borders 1518 assert inside_polygon( (1., 0.5), polygon, closed=True) 1519 assert inside_polygon( (0.5, 1), polygon, closed=True) 1520 assert inside_polygon( (0., 0.5), polygon, closed=True) 1521 assert inside_polygon( (0.5, 0.), polygon, closed=True) 1522 1523 assert not inside_polygon( (0.5, 1), polygon, closed=False) 1524 assert not inside_polygon( (0., 0.5), polygon, closed=False) 1525 assert not inside_polygon( (0.5, 0.), polygon, closed=False) 1526 assert not inside_polygon( (1., 0.5), polygon, closed=False) 1527 1528 1529 1530 #From real example (that failed) 1531 polygon = [[20,20], [40,20], [40,40], [20,40]] 1532 points = [ [40, 50] ] 1533 res = inside_polygon(points, polygon) 1534 assert len(res) == 0 1535 1536 polygon = [[20,20], [40,20], [40,40], [20,40]] 1537 points = [ [25, 25], [30, 20], [40, 50], [90, 20], [40, 90] ] 1538 res = inside_polygon(points, polygon) 1539 assert len(res) == 2 1540 assert num.allclose(res, [0,1]) 1442 1443 assert not inside_polygon((0.5, 1.5), polygon) 1444 assert not inside_polygon((0.5, -0.5), polygon) 1445 assert not inside_polygon((-0.5, 0.5), polygon) 1446 assert not inside_polygon((1.5, 0.5), polygon) 1447 1448 # Try point on borders 1449 assert inside_polygon((1., 0.5), polygon, closed=True) 1450 assert inside_polygon((0.5, 1), polygon, closed=True) 1451 assert inside_polygon((0., 0.5), polygon, closed=True) 1452 assert inside_polygon((0.5, 0.), polygon, closed=True) 1453 1454 assert not inside_polygon((0.5, 1), polygon, closed=False) 1455 assert not inside_polygon((0., 0.5), polygon, closed=False) 1456 assert not inside_polygon((0.5, 0.), polygon, closed=False) 1457 assert not inside_polygon((1., 0.5), polygon, closed=False) 1458 1459 # From real example (that failed) 1460 polygon = [[20,20], [40,20], [40,40], [20,40]] 1461 points = [[40, 50]] 1462 res = inside_polygon(points, polygon) 1463 assert len(res) == 0 1464 1465 polygon = [[20,20], [40,20], [40,40], [20,40]] 1466 points = [[25, 25], [30, 20], [40, 50], [90, 20], [40, 90]] 1467 res = inside_polygon(points, polygon) 1468 assert len(res) == 2 1469 assert num.allclose(res, [0,1]) 1541 1470 1542 1471 def test_polygon_area(self): 1543 1544 #Simplest case: Polygon is the unit square 1472 # Simplest case: Polygon is the unit square 1545 1473 polygon = [[0,0], [1,0], [1,1], [0,1]] 1546 1547 1548 #Simple case: Polygon is a rectangle1474 assert polygon_area(polygon) == 1 1475 1476 # Simple case: Polygon is a rectangle 1549 1477 polygon = [[0,0], [1,0], [1,4], [0,4]] 1550 1551 1552 #Simple case: Polygon is a unit triangle1478 assert polygon_area(polygon) == 4 1479 1480 # Simple case: Polygon is a unit triangle 1553 1481 polygon = [[0,0], [1,0], [0,1]] 1554 1555 1556 #Simple case: Polygon is a diamond1482 assert polygon_area(polygon) == 0.5 1483 1484 # Simple case: Polygon is a diamond 1557 1485 polygon = [[0,0], [1,1], [2,0], [1, -1]] 1558 1559 1486 assert polygon_area(polygon) == 2.0 1487 1560 1488 # Complex case where numerical errors might occur 1561 1489 polygon = [[314037.58727982, 6224952.2960092], 1562 [314038.58727982, 6224952.2960092], 1490 [314038.58727982, 6224952.2960092], 1563 1491 [314038.58727982, 6224953.2960092], 1564 1492 [314037.58727982, 6224953.2960092]] 1565 assert polygon_area(polygon) == 1.0 1566 1493 assert polygon_area(polygon) == 1.0 1567 1494 1568 1495 def test_poly_xy(self): 1569 1570 #Simplest case: Polygon is the unit square 1496 # Simplest case: Polygon is the unit square 1571 1497 polygon = [[0,0], [1,0], [1,1], [0,1]] 1572 1498 x, y = poly_xy(polygon) 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 #Arbitrary polygon1499 assert len(x) == len(polygon)+1 1500 assert len(y) == len(polygon)+1 1501 assert x[0] == 0 1502 assert x[1] == 1 1503 assert x[2] == 1 1504 assert x[3] == 0 1505 assert y[0] == 0 1506 assert y[1] == 0 1507 assert y[2] == 1 1508 assert y[3] == 1 1509 1510 # Arbitrary polygon 1585 1511 polygon = [[1,5], [1,1], [100,10], [1,10], [3,6]] 1586 1512 x, y = poly_xy(polygon) 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 # Disabled 1513 assert len(x) == len(polygon)+1 1514 assert len(y) == len(polygon)+1 1515 assert x[0] == 1 1516 assert x[1] == 1 1517 assert x[2] == 100 1518 assert x[3] == 1 1519 assert x[4] == 3 1520 assert y[0] == 5 1521 assert y[1] == 1 1522 assert y[2] == 10 1523 assert y[3] == 10 1524 assert y[4] == 6 1525 1526 # Disabled 1601 1527 def xtest_plot_polygons(self): 1602 1603 1528 import os 1604 1605 # Simplest case: Polygon is the unit square1529 1530 # Simplest case: Polygon is the unit square 1606 1531 polygon1 = [[0,0], [1,0], [1,1], [0,1]] 1607 1532 polygon2 = [[1,1], [2,1], [3,2], [2,2]] 1608 v = plot_polygons([polygon1, polygon2], 'test1')1609 1610 1611 1612 1613 1614 1615 #Another case1533 v = plot_polygons([polygon1, polygon2], 'test1') 1534 assert len(v) == 4 1535 assert v[0] == 0 1536 assert v[1] == 3 1537 assert v[2] == 0 1538 assert v[3] == 2 1539 1540 # Another case 1616 1541 polygon3 = [[1,5], [10,1], [100,10], [50,10], [3,6]] 1617 v = plot_polygons([polygon2,polygon3],'test2') 1618 assert len(v) == 4 1619 assert v[0] == 1 1620 assert v[1] == 100 1621 assert v[2] == 1 1622 assert v[3] == 10 1623 1624 os.remove('test1.png') 1625 os.remove('test2.png') 1626 1627 1542 v = plot_polygons([polygon2,polygon3], 'test2') 1543 assert len(v) == 4 1544 assert v[0] == 1 1545 assert v[1] == 100 1546 assert v[2] == 1 1547 assert v[3] == 10 1548 1549 os.remove('test1.png') 1550 os.remove('test2.png') 1551 1628 1552 def test_inside_polygon_geospatial(self): 1629 1630 1553 # Simplest case: Polygon is the unit square 1631 1554 polygon_absolute = [[0,0], [1,0], [1,1], [0,1]] 1632 poly_geo_ref = Geo_reference(57,100,100) 1633 1634 1635 1636 1637 #Simplest case: Polygon is the unit square 1638 polygon_absolute = [[0,0], [1,0], [1,1], [0,1]] 1639 poly_geo_ref = Geo_reference(57,100,100) 1555 poly_geo_ref = Geo_reference(57, 100, 100) 1640 1556 polygon = poly_geo_ref.change_points_geo_ref(polygon_absolute) 1641 poly_spatial = Geospatial_data(polygon, 1642 geo_reference=poly_geo_ref) 1643 1644 points_absolute = (0.5, 0.5) 1645 points_geo_ref = Geo_reference(57,78,-56) 1646 points = points_geo_ref.change_points_geo_ref(points_absolute) 1647 points_spatial = Geospatial_data(points, 1648 geo_reference=points_geo_ref) 1649 1650 assert is_inside_polygon(points_absolute, polygon_absolute) 1651 assert is_inside_polygon(ensure_numeric(points_absolute), 1557 poly_spatial = Geospatial_data(polygon, geo_reference=poly_geo_ref) 1558 point_absolute = (0.5, 0.5) 1559 points_geo_ref = Geo_reference(57, 78, -56) 1560 point = points_geo_ref.change_points_geo_ref(point_absolute) 1561 point_spatial = Geospatial_data(point, geo_reference=points_geo_ref) 1562 1563 assert is_inside_polygon(point_absolute, polygon_absolute) 1564 assert is_inside_polygon(ensure_numeric(point_absolute), 1652 1565 ensure_numeric(polygon_absolute)) 1653 assert is_inside_polygon(points_absolute, poly_spatial) 1654 assert is_inside_polygon(points_spatial, poly_spatial)1655 assert is_inside_polygon(points_spatial, polygon_absolute) 1656 1657 assert is_inside_polygon(points_absolute, polygon_absolute)1658 1566 msg = ('point_absolute %s is not inside poly_spatial %s' 1567 % (str(point_absolute), str(poly_spatial))) 1568 assert is_inside_polygon(point_absolute, poly_spatial), msg 1569 assert is_inside_polygon(point_spatial, poly_spatial) 1570 assert is_inside_polygon(point_spatial, polygon_absolute) 1571 assert is_inside_polygon(point_absolute, polygon_absolute) 1659 1572 1660 1573 def NOtest_decimate_polygon(self): 1661 1662 1574 polygon = [[0,0], [10,10], [15,5], [20, 10], 1663 1575 [25,0], [30,10], [40,-10], [35, -5]] 1664 1576 1665 #plot_polygons([polygon], figname='test')1666 1667 1577 dpoly = decimate_polygon(polygon, factor=2) 1668 1578 1669 1579 print dpoly 1670 1580 1671 1581 assert len(dpoly)*2==len(polygon) 1672 1582 … … 1675 1585 for point in polygon[1:]: 1676 1586 x, y = point 1677 1587 1678 1588 if x < minx: minx = x 1679 1589 if x > maxx: maxx = x 1680 1590 if y < miny: miny = y 1681 1591 if y > maxy: maxy = y 1682 1683 1592 1684 1593 assert [minx, miny] in polygon … … 1686 1595 assert [minx, maxy] in polygon 1687 1596 assert [maxx, miny] in polygon 1688 assert [maxx, maxy] in polygon 1689 1690 1691 1597 assert [maxx, maxy] in polygon 1598 1692 1599 def test_interpolate_polyline(self): 1693 1600 """test_interpolate_polyline(self): 1694 1695 This test is added under the assumption that the function interpolate_polyline implemented by 1696 John Jakeman works. It has been exercised somewhat by tests of sts boundary, but never before separately. 1601 1602 This test is added under the assumption that the function 1603 interpolate_polyline implemented by John Jakeman works. 1604 It has been exercised somewhat by tests of sts boundary, 1605 but never before separately. 1697 1606 """ 1698 1607 1699 1608 f = num.array([58.06150614, 58.06150614, 58.06150614]) 1700 1609 vertex_coordinates = num.array([[0., 0., ], … … 1709 1618 [5.11996623e+02, -1.85956061e+00], 1710 1619 [2.02046270e+00, 5.53055373e+02]]) 1711 1620 1712 1621 z_ref = [0., 0., 0., 58.06150614, 0., 0., 58.06150614] 1713 1714 z = interpolate_polyline(f, vertex_coordinates, gauge_neighbour_id, point_coordinates) 1622 1623 z = interpolate_polyline(f, vertex_coordinates, 1624 gauge_neighbour_id, point_coordinates) 1715 1625 assert num.allclose(z, z_ref) 1716 1626 1717 1627 # Another f 1718 1628 f = num.array([58.06150614, 158.06150614, 258.06150614]) 1719 z_ref = [0., 0., 0., 208.06150645, 0., 0., 108.0615061] 1720 z = interpolate_polyline(f, vertex_coordinates, gauge_neighbour_id, point_coordinates)1721 assert num.allclose(z, z_ref)1722 1629 z_ref = [0., 0., 0., 208.06150645, 0., 0., 108.0615061] 1630 z = interpolate_polyline(f, vertex_coordinates, 1631 gauge_neighbour_id, point_coordinates) 1632 assert num.allclose(z, z_ref) 1723 1633 1724 1634 # Other and simpler numbers 1725 f = num.array([1, 5, 13]) 1635 f = num.array([1, 5, 13]) 1726 1636 vertex_coordinates = num.array([[0., 0., ], 1727 1637 [4., 4.], 1728 [8., 8.]]) 1638 [8., 8.]]) 1729 1639 point_coordinates = num.array([[0.1, 0.1], 1730 1640 [3.5, 3.5], … … 1734 1644 [8.3, 8.3]]) 1735 1645 gauge_neighbour_id = [1, 2, -1] 1736 1737 z = interpolate_polyline(f, vertex_coordinates, gauge_neighbour_id, point_coordinates) 1646 1647 z = interpolate_polyline(f, vertex_coordinates, 1648 gauge_neighbour_id, point_coordinates) 1738 1649 z_ref = [1.1, 4.5, 5., 7.4, 11., 0.] 1739 #print z 1740 assert num.allclose(z, z_ref) 1741 1650 assert num.allclose(z, z_ref) 1651 1742 1652 # Test exception thrown for one point 1743 f = num.array([5]) 1744 vertex_coordinates = num.array([[4., 4.]]) 1745 try: 1746 z = interpolate_polyline(f, vertex_coordinates, gauge_neighbour_id, point_coordinates) 1653 f = num.array([5]) 1654 vertex_coordinates = num.array([[4., 4.]]) 1655 try: 1656 z = interpolate_polyline(f, vertex_coordinates, 1657 gauge_neighbour_id, point_coordinates) 1747 1658 except Exception: 1748 1659 pass 1749 1660 else: 1750 1661 raise Exception, 'One point should have raised exception' 1751 1752 1662 1753 1663 # More polyline nodes 1754 data = num.array([1, 5, 13, 12, 6, 29]) 1664 data = num.array([1, 5, 13, 12, 6, 29]) 1755 1665 polyline_nodes = num.array([[0., 0.], 1756 1666 [4., 4.], … … 1759 1669 [10., 5.], 1760 1670 [10., 0.]]) 1761 1762 1671 point_coordinates = num.array([[0.1, 0.1], 1763 1672 [3.5, 3.5], … … 1771 1680 [10., 4.3], 1772 1681 [10., 1.0]]) 1773 1774 1682 gauge_neighbour_id = [1, 2, 3, 4, 5, -1] 1775 1776 z = interpolate_polyline(data, polyline_nodes,gauge_neighbour_id, point_coordinates)1683 z = interpolate_polyline(data, polyline_nodes, 1684 gauge_neighbour_id, point_coordinates) 1777 1685 z_ref = [1.1, 4.5, 5., 7.4, 11., 12.85, 12., 10.8, 8.52, 9.22, 24.4] 1778 assert num.allclose(z, z_ref) 1779 1780 1781 1782 #------------------------------------------------------------- 1686 assert num.allclose(z, z_ref) 1687 1688 1689 # ------------------------------------------------------------- 1783 1690 if __name__ == "__main__": 1784 suite = unittest.makeSuite(Test_Polygon,'test') 1691 #suite = unittest.makeSuite(Test_Polygon,'test') 1692 suite = unittest.makeSuite(Test_Polygon,'test_inside_polygon_geospatial') 1785 1693 runner = unittest.TextTestRunner() 1786 1694 runner.run(suite) 1787 1788 1789 1790 -
branches/numpy/anuga/utilities/test_quad.py
r6158 r6304 1 1 import unittest 2 import Numericas num2 import numpy as num 3 3 4 4 from quad import Cell, build_quadtree -
branches/numpy/anuga/utilities/test_sparse.py
r6174 r6304 5 5 6 6 from sparse import * 7 import Numericas num7 import numpy as num 8 8 9 9 … … 86 86 87 87 #Right hand side column 88 v = num.array([[2,4],[3,4],[4,4]] , num.Int) #array default#88 v = num.array([[2,4],[3,4],[4,4]]) 89 89 90 90 u = A*v[:,0] … … 104 104 105 105 #Right hand side matrix 106 v = num.array([[2,4],[3,4],[4,4]] , num.Int) #array default#106 v = num.array([[2,4],[3,4],[4,4]]) 107 107 108 108 u = A*v -
branches/numpy/anuga/utilities/test_system_tools.py
r6158 r6304 3 3 4 4 import unittest 5 import Numericas num5 import numpy as num 6 6 import zlib 7 7 from os.path import join, split, sep 8 8 from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a 9 from anuga.config import netcdf_float 9 10 10 11 … … 82 83 pass 83 84 else: 84 test_array = num.array([[7.0, 3.14], [-31.333, 0.0]]) 85 test_array = num.array([[7.0, 3.14], [-31.333, 0.0]], 86 dtype=num.float) 85 87 86 88 # First file … … 88 90 fid = NetCDFFile(filename1, netcdf_mode_w) 89 91 fid.createDimension('two', 2) 90 fid.createVariable('test_array', n um.Float,92 fid.createVariable('test_array', netcdf_float, 91 93 ('two', 'two')) 92 94 fid.variables['test_array'][:] = test_array … … 97 99 fid = NetCDFFile(filename2, netcdf_mode_w) 98 100 fid.createDimension('two', 2) 99 fid.createVariable('test_array', n um.Float,101 fid.createVariable('test_array', netcdf_float, 100 102 ('two', 'two')) 101 103 fid.variables['test_array'][:] = test_array -
branches/numpy/anuga/utilities/util_ext.c
r5897 r6304 10 10 // Ole Nielsen, GA 2004 11 11 // 12 //NOTE: On 64 bit systems use long* instead of int* for Numeric arrays12 //NOTE: On 64 bit systems use long* instead of int* for numeric arrays 13 13 //this will also work on 32 bit systems 14 14 … … 16 16 17 17 #include "Python.h" 18 #include " Numeric/arrayobject.h"18 #include "numpy/arrayobject.h" 19 19 #include "math.h" 20 20 -
branches/numpy/anuga/utilities/util_ext.h
r5897 r6304 11 11 12 12 #include "Python.h" 13 #include " Numeric/arrayobject.h"13 #include "numpy/arrayobject.h" 14 14 #include "math.h" 15 15 -
branches/numpy/anuga/utilities/where_close.py
r5681 r6304 62 62 y are "equal", and 0 otherwise. If x or y are floating point, 63 63 "equal" means where abs(x-y) <= atol + rtol * abs(y). This is 64 essentially the same algorithm used in the Numeric function64 essentially the same algorithm used in the numeric function 65 65 allclose. If x and y are integer, "equal" means strict equality. 66 66 Shape and size of output is the same as x and y; if one is an 67 67 array and the other is scalar, shape and size of the output is the 68 same as the array. Output is a Numeric array, unless both inputs68 same as the array. Output is a numeric array, unless both inputs 69 69 are scalar in which the output is a Python integer scalar. 70 70 71 71 Positional Input Arguments: 72 * x: Scalar or Numeric array, Python list/tuple of any size and72 * x: Scalar or numeric array, Python list/tuple of any size and 73 73 shape. Floating or integer type. 74 * y: Scalar or Numeric array, Python list/tuple of any size and74 * y: Scalar or numeric array, Python list/tuple of any size and 75 75 shape. Floating or integer type. 76 76 … … 84 84 85 85 Examples: 86 >>> import Numericas N86 >>> import numpy as N 87 87 >>> from where_close import where_close 88 88 >>> x = [20., -32., -1., 2. , 5., 29.] … … 98 98 ['1', '0', '0', '1', '0'] 99 99 """ 100 import Numericas N100 import numpy as N 101 101 abs = N.absolute 102 102 103 103 104 #- Make sure input is Numeric type:104 #- Make sure input is numeric type: 105 105 106 106 xN = N.array(x) … … 111 111 # type returns an error: 112 112 113 if (xN. typecode()in N.typecodes['Float']) or \114 (yN. typecode()in N.typecodes['Float']):113 if (xN.dtype.char in N.typecodes['Float']) or \ 114 (yN.dtype.char in N.typecodes['Float']): 115 115 return N.less_equal(abs(xN-yN), atol+rtol*abs(yN)) 116 116 117 elif (xN. typecode()in N.typecodes['Integer']) and \118 (yN. typecode()in N.typecodes['Integer']):117 elif (xN.dtype.char in N.typecodes['Integer']) and \ 118 (yN.dtype.char in N.typecodes['Integer']): 119 119 return N.equal(xN, yN) 120 120 … … 132 132 """ 133 133 >>> from where_close import where_close 134 >>> import Numericas N134 >>> import numpy as N 135 135 >>> x = [20., -32., -1., 2. , 5., 29.] 136 136 >>> y = [20.1, -31., -1., 2.000000000001, 3., 28.99] … … 144 144 >>> ind.shape 145 145 (2, 3) 146 >>> ind. typecode()147 ' l'146 >>> ind.dtype.char 147 '?' 148 148 >>> type(ind) 149 <type ' array'>149 <type 'numpy.ndarray'> 150 150 151 151 >>> x = [20., -32., -1., 2. , 5., 29.] … … 179 179 0 180 180 >>> type(ind) 181 <type ' int'>181 <type 'numpy.bool_'> 182 182 >>> x = -33 183 183 >>> y = -33. -
branches/numpy/anuga/visualiser/commandline_viewer.py
r3963 r6304 41 41 o.colour_height_quantity('stage', (lambda q: q['stage'], 0, 10)) 42 42 # Or with the magnitude of the momentum at that point: 43 # Needs the sqrt function from Numeric. Again, 0 and 1043 # Needs the sqrt function from numeric. Again, 0 and 10 44 44 # define the colour range. 45 45 # o.colour_height_quantity('stage',
Note: See TracChangeset
for help on using the changeset viewer.