Changeset 6304 for branches/numpy/anuga


Ignore:
Timestamp:
Feb 10, 2009, 11:11:04 AM (16 years ago)
Author:
rwilson
Message:

Initial commit of numpy changes. Still a long way to go.

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  
    3131from quantity import Quantity
    3232
    33 import Numeric as num
     33import numpy as num
    3434
    3535
     
    185185            buffer_shape = self.full_send_dict[key][0].shape[0]
    186186            self.full_send_dict[key].append(num.zeros((buffer_shape, self.nsys),
    187                                                       num.Float))
     187                                                      num.float))
    188188
    189189        for key in self.ghost_recv_dict:
    190190            buffer_shape = self.ghost_recv_dict[key][0].shape[0]
    191191            self.ghost_recv_dict[key].append(num.zeros((buffer_shape, self.nsys),
    192                                              num.Float))
     192                                             num.float))
    193193
    194194        # Setup cell full flag
     
    197197        N = len(self) #number_of_elements
    198198        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)
    200200        for i in self.ghost_recv_dict.keys():
    201201            for id in self.ghost_recv_dict[i][0]:
     
    258258        # (boolean) array, to be used during the flux calculation.
    259259        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)
    261261
    262262        # Storage for maximal speeds computed for each triangle by
    263263        # compute_fluxes.
    264264        # 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)
    266266
    267267        if mesh_filename is not None:
     
    375375            raise Exception, msg
    376376
    377         q = num.zeros(len(self.conserved_quantities), num.Float)
     377        q = num.zeros(len(self.conserved_quantities), num.float)
    378378
    379379        for i, name in enumerate(self.conserved_quantities):
     
    447447
    448448        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)
    450450
    451451        The values will be stored in elements following their internal ordering.
     
    879879
    880880            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))
    883883            msg += '  Histogram:\n'
    884884
     
    892892                else:
    893893                    # Closed upper interval
    894                     hi = max(self.max_speed)
     894                    hi = max(self.max_speed.flat)
    895895                    msg += '    [%f, %f]: %d\n' % (lo, hi, count)
    896896
    897             N = len(self.max_speed)
     897            N = len(self.max_speed.flat)
    898898            if N > 10:
    899899                msg += '  Percentiles (10%):\n'
     
    13571357                self.number_of_steps = 0
    13581358                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)
    13601360
    13611361    ##
     
    16261626        # momentum
    16271627        if self.protect_against_isolated_degenerate_timesteps is True and \
    1628                self.max_speed > 10.0: # FIXME (Ole): Make this configurable
     1628               num.max(self.max_speed) > 10.0: # FIXME (Ole): Make this configurable
    16291629
    16301630            # Setup 10 bins for speed histogram
     
    16411641
    16421642                    # Find triangles in last bin
    1643                     # FIXME - speed up using Numeric
     1643                    # FIXME - speed up using numeric package
    16441644                    d = 0
    16451645                    for i in range(self.number_of_full_triangles):
  • branches/numpy/anuga/abstract_2d_finite_volumes/ermapper_grids.py

    r6161 r6304  
    22
    33# from os import open, write, read
    4 import Numeric as num
    5 
    6 celltype_map = {'IEEE4ByteReal': num.Float32, 'IEEE8ByteReal': num.Float64}
     4import numpy as num
     5
     6celltype_map = {'IEEE4ByteReal': num.float32, 'IEEE8ByteReal': num.float64}
    77
    88
     
    1111    write_ermapper_grid(ofile, data, header = {}):
    1212   
    13     Function to write a 2D Numeric array to an ERMapper grid.  There are a series of conventions adopted within
     13    Function to write a 2D numeric array to an ERMapper grid.  There are a series of conventions adopted within
    1414    this code, specifically:
    1515    1)  The registration coordinate for the data is the SW (or lower-left) corner of the data
    1616    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)
    1818        where N is the last line and M is the last column
    1919    4)  There has been no testng of the use of a rotated grid.  Best to keep data in an NS orientation
     
    163163    return header                     
    164164
    165 def write_ermapper_data(grid, ofile, data_format = num.Float32):
     165def write_ermapper_data(grid, ofile, data_format=num.float32):
    166166
    167167
     
    193193
    194194
    195 def read_ermapper_data(ifile, data_format = num.Float32):
     195def read_ermapper_data(ifile, data_format = num.float32):
    196196    # open input file in a binary format and read the input string
    197197    fid = open(ifile,'rb')
     
    199199    fid.close()
    200200
    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)
    202202    grid_as_float = num.fromstring(input_string,data_format)
    203203    return grid_as_float
  • branches/numpy/anuga/abstract_2d_finite_volumes/general_mesh.py

    r6191 r6304  
    1 import Numeric as num
     1import numpy as num
    22
    33from anuga.coordinate_transforms.geo_reference import Geo_reference
     
    1010    which is represented as a coordinate set (x,y).
    1111    Vertices from different triangles can point to the same node.
    12     The nodes are implemented as an Nx2 Numeric array containing the
     12    The nodes are implemented as an Nx2 numeric array containing the
    1313    x and y coordinates.
    1414
     
    1919    where
    2020
    21       nodes is either a list of 2-tuples or an Nx2 Numeric array of
     21      nodes is either a list of 2-tuples or an Nx2 numeric array of
    2222      floats representing all x, y coordinates in the mesh.
    2323
    24       triangles is either a list of 3-tuples or an Mx3 Numeric array of
     24      triangles is either a list of 3-tuples or an Mx3 numeric array of
    2525      integers representing indices of all vertices in the mesh.
    2626      Each vertex is identified by its index i in [0, N-1].
     
    6868       
    6969          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.
    7171                 
    72           triangles: sequence of 3-tuples or Mx3 Numeric array of
     72          triangles: sequence of 3-tuples or Mx3 numeric array of
    7373                     non-negative integers representing indices into
    7474                     the nodes array.
     
    8888        if verbose: print 'General_mesh: Building basic mesh structure in ANUGA domain'
    8989
    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)
    9292
    9393
     
    125125
    126126        # 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. '
    128128        msg += 'The supplied array has the shape: %s'\
    129129               %str(self.triangles.shape)
    130130        assert len(self.triangles.shape) == 2, msg
    131131
    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'
    133133        msg += 'The supplied array has the shape: %s'\
    134134               %str(self.nodes.shape)
     
    144144                      max(self.nodes[:,0]), max(self.nodes[:,1]) ]
    145145
    146         self.xy_extent = num.array(xy_extent, num.Float)
     146        self.xy_extent = num.array(xy_extent, num.float)
    147147
    148148
    149149        # 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)
    153153
    154154        # Get x,y coordinates for all triangles and store
     
    185185            #   - Stored as six floats n0x,n0y,n1x,n1y,n2x,n2y per triangle
    186186
    187             n0 = num.array([x2 - x1, y2 - y1], num.Float)
     187            n0 = num.array([x2 - x1, y2 - y1], num.float)
    188188            l0 = num.sqrt(num.sum(n0**2))
    189189
    190             n1 = num.array([x0 - x2, y0 - y2], num.Float)
     190            n1 = num.array([x0 - x2, y0 - y2], num.float)
    191191            l1 = num.sqrt(num.sum(n1**2))
    192192
    193             n2 = num.array([x1 - x0, y1 - y0], num.Float)
     193            n2 = num.array([x1 - x0, y1 - y0], num.float)
    194194            l2 = num.sqrt(num.sum(n2**2))
    195195
     
    275275            if not self.geo_reference.is_absolute():
    276276                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)
    278278            else:
    279279                return V
     
    317317            if absolute is True and not self.geo_reference.is_absolute():
    318318                offset=num.array([self.geo_reference.get_xllcorner(),
    319                                   self.geo_reference.get_yllcorner()], num.Float)
     319                                  self.geo_reference.get_yllcorner()], num.float)
    320320                return num.array([V[i3,:]+offset,
    321321                                  V[i3+1,:]+offset,
    322                                   V[i3+2,:]+offset], num.Float)
     322                                  V[i3+2,:]+offset], num.float)
    323323            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)
    325325               
    326326
     
    349349
    350350        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)
    352352
    353353        for i in range(M):
     
    409409        K = 3*M       # Total number of unique vertices
    410410       
    411         T = num.reshape(num.arange(K, typecode=num.Int), (M,3))
     411        T = num.reshape(num.arange(K, dtype=num.int), (M,3))
    412412       
    413413        return T     
     
    416416
    417417    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
    420420        triangles = self.get_triangles(indices=indices)
    421421        unique_verts = {}
    422422        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
    426427        return unique_verts.keys()
    427428
     
    452453                triangle_list.append( (volume_id, vertex_id) )
    453454
    454             triangle_list = num.array(triangle_list, num.Int)    #array default#
     455            triangle_list = num.array(triangle_list, num.int)    #array default#
    455456        else:
    456457            # Get info for all nodes recursively.
     
    529530
    530531        # 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#
    532534        for volume_id, triangle in enumerate(self.get_triangles()):
    533535            for vertex_id in triangle:
     
    536538        # Allocate space for inverted structure
    537539        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#
    539541
    540542        # Register (triangle, vertex) indices for each node
  • branches/numpy/anuga/abstract_2d_finite_volumes/generic_boundary_conditions.py

    r6174 r6304  
    88from anuga.fit_interpolate.interpolate import Modeltime_too_early
    99
    10 import Numeric as num
     10import numpy as num
    1111
    1212
     
    6969            raise Exception, msg
    7070
    71         self.conserved_quantities=num.array(conserved_quantities, num.Float)
     71        self.conserved_quantities=num.array(conserved_quantities, num.float)
    7272
    7373    def __repr__(self):
     
    9999
    100100        try:
    101             q = num.array(q, num.Float)
     101            q = num.array(q, num.float)
    102102        except:
    103103            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'
    105105            msg += 'Specified function should return either list or array.\n'
    106106            msg += 'I got %s' %str(q)
     
    180180
    181181        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)
    183183        boundary_keys = domain.boundary.keys()
    184184
     
    200200           
    201201            # 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)
    205205
    206206            # Convert to absolute UTM coordinates
     
    309309                        # See http://docs.python.org/lib/warning-filter.html
    310310                        self.default_boundary_invoked = True
    311                    
    312 
    313             if res == NAN:
     311           
     312            if num.any(res == NAN):
    314313                x,y=self.midpoint_coordinates[i,:]
    315314                msg = 'NAN value found in file_boundary at '
  • branches/numpy/anuga/abstract_2d_finite_volumes/mesh_factory.py

    r6145 r6304  
    33"""
    44
    5 import Numeric as num
     5import numpy as num
    66
    77
     
    9494    index = Index(n,m)
    9595
    96     points = num.zeros((Np, 2), num.Float)
     96    points = num.zeros((Np, 2), num.float)
    9797
    9898    for i in range(m+1):
     
    106106
    107107
    108     elements = num.zeros((Nt, 3), num.Int)
     108    elements = num.zeros((Nt, 3), num.int)
    109109    boundary = {}
    110110    nt = -1
  • branches/numpy/anuga/abstract_2d_finite_volumes/neighbour_mesh.py

    r6191 r6304  
    1212from math import pi, sqrt
    1313
    14 import Numeric as num
     14import numpy as num
    1515       
    1616
     
    2424    coordinate set.
    2525
    26     Coordinate sets are implemented as an N x 2 Numeric array containing
     26    Coordinate sets are implemented as an N x 2 numeric array containing
    2727    x and y coordinates.
    2828
     
    3333    where
    3434
    35       coordinates is either a list of 2-tuples or an Mx2 Numeric array of
     35      coordinates is either a list of 2-tuples or an Mx2 numeric array of
    3636      floats representing all x, y coordinates in the mesh.
    3737
    38       triangles is either a list of 3-tuples or an Nx3 Numeric array of
     38      triangles is either a list of 3-tuples or an Nx3 numeric array of
    3939      integers representing indices of all vertices in the mesh.
    4040      Each vertex is identified by its index i in [0, M-1].
     
    7676        """
    7777        Build triangles from x,y coordinates (sequence of 2-tuples or
    78         Mx2 Numeric array of floats) and triangles (sequence of 3-tuples
    79         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).
    8080        """
    8181
     
    9898
    9999        #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)
    108108
    109109        #Get x,y coordinates for all triangles and store
     
    124124
    125125            #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)
    127127            self.centroid_coordinates[i] = centroid
    128128
     
    133133
    134134                #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)
    138138
    139139                #The radius is the distance from the centroid of
     
    394394            #Check that all keys in given boundary exist
    395395            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)
    397397
    398398                msg = 'Not all elements exist. '
     
    506506            # Sanity check
    507507            if p0 is None:
    508                 raise Exception('Impossible')
    509 
     508                msg = 'Impossible: p0 is None!?'
     509                raise Exception, msg
    510510
    511511            # Register potential paths from A to B
     
    613613                point_registry[tuple(p1)] = len(point_registry)
    614614           
    615             polygon.append(list(p1)) # De-Numeric each point :-)
     615            polygon.append(list(p1)) # De-numeric each point :-)
    616616            p0 = p1
    617617
     
    11391139
    11401140            # 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)
    11431143            d0 = num.sqrt(num.sum(z0**2))
    11441144            d1 = num.sqrt(num.sum(z1**2))
     
    11551155            # Normal direction:
    11561156            # Right hand side relative to line direction
    1157             vector = num.array([x1 - x0, y1 - y0], num.Float) # Segment vector
     1157            vector = num.array([x1 - x0, y1 - y0], num.float) # Segment vector
    11581158            length = num.sqrt(num.sum(vector**2))      # Segment length
    1159             normal = num.array([vector[1], -vector[0]], num.Float)/length
     1159            normal = num.array([vector[1], -vector[0]], num.float)/length
    11601160
    11611161
     
    12371237        assert isinstance(segment, Triangle_intersection), msg
    12381238       
    1239         midpoint = num.sum(num.array(segment.segment, num.Float))/2
     1239        midpoint = num.sum(num.array(segment.segment, num.float))/2
    12401240        midpoints.append(midpoint)
    12411241
  • branches/numpy/anuga/abstract_2d_finite_volumes/pmesh2domain.py

    r6145 r6304  
    1 """Class pmesh2domain - Converting .tsh files to doamains
     1"""Class pmesh2domain - Converting .tsh files to domains
    22
    33
     
    88
    99import 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)
     10import 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).
     18def 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.
     59def 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.
     86def _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)
    2594
    2695    # NOTE(Ole): This import cannot be at the module level due to mutual
     
    2897    from anuga.abstract_2d_finite_volumes.domain import Domain
    2998
    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))
    35102    assert issubclass(DomainClass, Domain), msg
    36 
    37103
    38104    domain = DomainClass(coordinates = vertex_coordinates,
     
    42108                         geo_reference = geo_reference )
    43109
    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.
    116115
    117116    # This doesn't work on the domain instance.
    118117    # This is still needed so -ve elevations don't cuase 'lakes'
    119118    # The fixme we discussed was to only create a quantity when its values
    120     #are set.
     119    # are set.
    121120    # I think that's the way to go still
    122121
    123122    # 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')):
    125125        vertex_quantity_dict['stage'] = vertex_quantity_dict['elevation']
    126 
    127126    domain.set_quantity_vertices_dict(vertex_quantity_dict)
    128     #print "vertex_quantity_dict",vertex_quantity_dict
     127
    129128    return domain
    130129
    131130
    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 ??
     138def pmesh_to_domain(file_name=None, mesh_instance=None, use_cache=False,
    135139                    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
    138141    that can be used to instanciate a domain object.
    139142
     
    144147        from caching import cache
    145148        result = cache(_pmesh_to_domain, (file_name, mesh_instance),
    146                        dependencies = [file_name],                     
    147                        verbose = verbose)
     149                       dependencies=[file_name], verbose=verbose)
    148150
    149151    else:
     
    153155
    154156
    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 ??
     164def _pmesh_to_domain(file_name=None, mesh_instance=None, use_cache=False,
    158165                     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
    161167    that can be used to instanciate a domain object.
    162168    """
     
    164170    from load_mesh.loadASCII import import_mesh_file
    165171
     172    # get data from mesh instance or file
    166173    if file_name is None:
    167174        mesh_dict = mesh_instance.Mesh2IODict()
    168175    else:
    169176        mesh_dict = import_mesh_file(file_name)
    170     #print "mesh_dict",mesh_dict
     177
     178    # extract required data from the mesh dictionary
    171179    vertex_coordinates = mesh_dict['vertices']
    172180    volumes = mesh_dict['triangles']
    173181    vertex_quantity_dict = {}
    174     point_atts = num.transpose(mesh_dict['vertex_attributes'])
     182    point_atts = mesh_dict['vertex_attributes']
    175183    point_titles  = mesh_dict['vertex_attribute_titles']
    176184    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):
    179188            vertex_quantity_dict[quantity] = value_vector
    180189    tag_dict = pmesh_dict_to_tag_dict(mesh_dict)
    181190    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)
    184194
    185195
    186196def build_tagged_elements_dictionary(mesh_dict):
    187197    """Build the dictionary of element tags.
     198
    188199    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
    192203    tri_atts = mesh_dict['triangle_tags']
    193204    tagged_elements = {}
     
    198209            tagged_elements.setdefault(tri_atts[tri_att_index],
    199210                                       []).append(tri_att_index)
     211
    200212    return tagged_elements
     213
    201214
    202215def pmesh_dict_to_tag_dict(mesh_dict):
     
    204217    to a dictionary of tags, indexed with volume id and face number.
    205218    """
     219
    206220    triangles = mesh_dict['triangles']
    207221    sides = calc_sides(triangles)
    208222    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']):
    211224        v1 = int(seg[0])
    212225        v2 = int(seg[1])
     
    222235
    223236def 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
    226241    sides = {}
     242
    227243    for id, triangle in enumerate(triangles):
    228244        a = int(triangle[0])
    229245        b = int(triangle[1])
    230246        c = int(triangle[2])
     247
    231248        sides[a,b] = (id, 2) #(id, face)
    232249        sides[b,c] = (id, 0) #(id, face)
    233250        sides[c,a] = (id, 1) #(id, face)
     251
    234252    return sides
     253
  • branches/numpy/anuga/abstract_2d_finite_volumes/quantity.py

    r6244 r6304  
    2323from anuga.caching import cache
    2424
    25 import Numeric as num
     25import anuga.utilities.numerical_tools as aunt
     26
     27import numpy as num
    2628
    2729
     
    4345        if vertex_values is None:
    4446            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)
    4648        else:
    47             self.vertex_values = num.array(vertex_values, num.Float)
     49            self.vertex_values = num.array(vertex_values, num.float)
    4850
    4951            N, V = self.vertex_values.shape
     
    5759
    5860        # 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)
    6163
    6264        # 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)
    6567
    6668        # Allocate space for Limiter Phi
    67         self.phi = num.zeros(N, num.Float)
     69        self.phi = num.zeros(N, num.float)
    6870
    6971        # Intialise centroid and edge_values
     
    7274        # Allocate space for boundary values
    7375        L = len(domain.boundary)
    74         self.boundary_values = num.zeros(L, num.Float)
     76        self.boundary_values = num.zeros(L, num.float)
    7577
    7678        # Allocate space for updates of conserved quantities by
     
    7880
    7981        # 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)
    8385
    8486        self.set_beta(1.0)
     
    316318
    317319        numeric:
    318           Compatible list, Numeric array (see below) or constant.
     320          Compatible list, numeric array (see below) or constant.
    319321          If callable it will treated as a function (see below)
    320322          If instance of another Quantity it will be treated as such.
     
    357359
    358360                  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,
    360362                  N being the number of elements.
    361363                  Otherwise it must be of dimension Nx3
     
    458460
    459461        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
    461464
    462465        # Determine which 'set_values_from_...' to use
    463466        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):
    468468                self.set_values_from_array(numeric, location, indices,
    469469                                           use_cache=use_cache, verbose=verbose)
     
    479479                                                     indices, verbose=verbose,
    480480                                                     use_cache=use_cache)
     481#            if (isinstance(numeric, float) or isinstance(numeric, int)
     482#                or isinstance(numeric, long)):
    481483            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
    484513        elif quantity is not None:
    485514            self.set_values_from_quantity(quantity, location, indices, verbose)
     
    583612        """Set values for quantity
    584613
    585         values: Numeric array
     614        values: numeric array
    586615        location: Where values are to be stored.
    587616        Permissible options are: vertices, centroid, unique vertices
     
    593622
    594623        In case of location == 'centroid' the dimension values must
    595         be a list of a Numerical array of length N, N being the number
     624        be a list of a numerical array of length N, N being the number
    596625        of elements.
    597626
     
    607636        """
    608637
    609         values = num.array(values, num.Float)
     638        values = num.array(values, num.float)
    610639
    611640        if indices is not None:
    612             indices = num.array(indices, num.Int)
     641            indices = num.array(indices, num.int)
    613642            msg = ('Number of values must match number of indices: You '
    614643                   'specified %d values and %d indices'
     
    637666                    'Values array must be 1d')
    638667
    639             self.set_vertex_values(values.flat, indices=indices,
     668            self.set_vertex_values(values.flatten(), indices=indices,
    640669                                   use_cache=use_cache, verbose=verbose)
    641670        else:
     
    788817        from anuga.coordinate_transforms.geo_reference import Geo_reference
    789818
    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)
    792821
    793822        if location != 'vertices':
     
    10801109
    10811110        # Ensure that interpolation points is either a list of
    1082         # points, Nx2 array, or geospatial and convert to Numeric array
     1111        # points, Nx2 array, or geospatial and convert to numeric array
    10831112        if isinstance(interpolation_points, Geospatial_data):
    10841113            # Ensure interpolation points are in absolute UTM coordinates
     
    11191148        """Get values for quantity
    11201149
    1121         Extract values for quantity as a Numeric array.
     1150        Extract values for quantity as a numeric array.
    11221151
    11231152        Inputs:
     
    11371166
    11381167        In case of location == 'centroids' the dimension of returned
    1139         values will be a list or a Numerical array of length N, N being
     1168        values will be a list or a numerical array of length N, N being
    11401169        the number of elements.
    11411170
     
    11731202                            'edges', 'unique vertices']:
    11741203            msg = 'Invalid location: %s' % location
    1175             raise msg
     1204            raise Exception, msg
    11761205
    11771206        import types
    11781207
    11791208        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'     #??#
    11821211
    11831212        if location == 'centroids':
     
    12101239                    sum += self.vertex_values[triangle_id, vertex_id]
    12111240                vert_values.append(sum / len(triangles))
    1212             return num.array(vert_values, num.Float)
     1241            return num.array(vert_values, num.float)
    12131242        else:
    12141243            if (indices is None):
     
    12361265
    12371266        # 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)
    12391268        assert len(A.shape) == 1
    12401269
     
    13361365
    13371366        if precision is None:
    1338             precision = num.Float
     1367            precision = num.float
    13391368
    13401369        if smooth is True:
     
    13421371            V = self.domain.get_triangles()
    13431372            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)
    13451374            points = self.domain.get_nodes()
    13461375
     
    13601389                    if current_node == N:
    13611390                        msg = 'Current node exceeding number of nodes (%d) ' % N
    1362                         raise msg
     1391                        raise Exception, msg
    13631392
    13641393                    k += 1
     
    13811410            V = self.domain.get_disconnected_triangles()
    13821411            points = self.domain.get_vertex_coordinates()
    1383             A = self.vertex_values.flat.astype(precision)
     1412            A = self.vertex_values.flatten().astype(precision)
    13841413
    13851414        # Return
  • branches/numpy/anuga/abstract_2d_finite_volumes/quantity_ext.c

    r5897 r6304  
    1111
    1212#include "Python.h"
    13 #include "Numeric/arrayobject.h"
     13#include "numpy/arrayobject.h"
    1414#include "math.h"
    1515
  • branches/numpy/anuga/abstract_2d_finite_volumes/region.py

    r6145 r6304  
    88# FIXME (DSG-DSG) add better comments
    99
    10 import Numeric as num
     10import numpy as num
    1111
    1212
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_domain.py

    r6195 r6304  
    77from anuga.config import epsilon
    88
    9 import Numeric as num
     9import numpy as num
    1010
    1111
     
    6565
    6666
    67         assert domain.get_conserved_quantities(0, edge=1) == 0.
     67        assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.)
    6868
    6969
     
    345345
    346346
    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)
    349349       
    350350        #print A
     
    613613
    614614        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
    615         denom = num.ones(4, num.Float)-domain.timestep*sem
     615        denom = num.ones(4, num.float)-domain.timestep*sem
    616616
    617617#        x = array([1, 2, 3, 4]) + array( [.4,.3,.2,.1] )
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_ermapper.py

    r6145 r6304  
    77from os import remove
    88
    9 import Numeric as num
     9import numpy as num
    1010
    1111
     
    4545
    4646        # 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)
    4848
    4949        # 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)
    5151
    5252        # 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  
    1010from anuga.coordinate_transforms.geo_reference import Geo_reference
    1111
    12 import Numeric as num
     12import numpy as num
    1313
    1414
     
    5959       
    6060        #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)
    6262
    6363        domain = General_mesh(nodes, triangles,
     
    277277                       geo_reference = geo)
    278278        node = domain.get_node(2)       
    279         self.assertEqual(c, node)
     279        #self.assertEqual(c, node)
     280        self.failUnless(num.alltrue(c == node))
    280281       
    281282        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))
    283285       
    284286        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))
    286289       
    287290
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_generic_boundary_conditions.py

    r6195 r6304  
    88from anuga.config import epsilon
    99
    10 import Numeric as num
     10import numpy as num
    1111
    1212
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_ghost.py

    r6195 r6304  
    66from anuga.abstract_2d_finite_volumes.domain import *
    77from anuga.config import epsilon
     8
     9import numpy as num
    810
    911
     
    4042
    4143
    42         assert domain.get_conserved_quantities(0, edge=1) == 0.
     44        assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.)
    4345
    4446
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_neighbour_mesh.py

    r6174 r6304  
    1818from anuga.utilities.numerical_tools import ensure_numeric
    1919
    20 import Numeric as num
     20import numpy as num
    2121
    2222
     
    988988                  [  75735.4765625 ,  23762.00585938],
    989989                  [  52341.70703125,  38563.39453125]]
    990 
    991         ##points = ensure_numeric(points, Int)/1000  # Simplify for ease of interpretation       
    992990
    993991        triangles = [[19, 0,15],
     
    10921090                  [  35406.3359375 ,  79332.9140625 ]]
    10931091
    1094         scaled_points = ensure_numeric(points, num.Int)/1000  # Simplify for ease of interpretation
     1092        scaled_points = ensure_numeric(points, num.int)/1000  # Simplify for ease of interpretation
    10951093
    10961094        triangles = [[ 0, 1, 2],
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_pmesh2domain.py

    r6191 r6304  
    1414from anuga.pmesh.mesh import importMeshFromFile
    1515
    16 import Numeric as num
     16import numpy as num
    1717
    1818
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_quantity.py

    r6195 r6304  
    1515from anuga.utilities.polygon import *
    1616
    17 import Numeric as num
     17import numpy as num
    1818
    1919
     
    17651765        quantity = Quantity(self.mesh4)
    17661766
    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)
    17681768
    17691769        quantity.interpolate_from_vertices_to_edges()
     
    17811781                                          [3., 2.5, 1.5],
    17821782                                          [3.5, 4.5, 3.],
    1783                                           [2.5, 3.5, 2]], num.Float)
     1783                                          [2.5, 3.5, 2]], num.float)
    17841784
    17851785        quantity.interpolate_from_edges_to_vertices()
     
    18351835
    18361836        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
    1837         denom = num.ones(4, num.Float)-timestep*sem
     1837        denom = num.ones(4, num.float)-timestep*sem
    18381838
    18391839        x = num.array([1, 2, 3, 4])/denom
     
    18591859
    18601860        sem = num.array([1.,1.,1.,1.])/num.array([1, 2, 3, 4])
    1861         denom = num.ones(4, num.Float)-timestep*sem
     1861        denom = num.ones(4, num.float)-timestep*sem
    18621862
    18631863        x = num.array([1., 2., 3., 4.])
     
    19011901
    19021902        bed = domain.quantities['elevation'].vertex_values
    1903         stage = num.zeros(bed.shape, num.Float)
     1903        stage = num.zeros(bed.shape, num.float)
    19041904
    19051905        h = 0.03
     
    19851985
    19861986        bed = domain.quantities['elevation'].vertex_values
    1987         stage = num.zeros(bed.shape, num.Float)
     1987        stage = num.zeros(bed.shape, num.float)
    19881988
    19891989        h = 0.03
     
    19991999        stage = domain.quantities['stage']
    20002000        A, V = stage.get_vertex_values(xy=False, smooth=False)
    2001         Q = stage.vertex_values.flat
     2001        Q = stage.vertex_values.flatten()
    20022002
    20032003        for k in range(8):
     
    25112511    suite = unittest.makeSuite(Test_Quantity, 'test')   
    25122512    #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')
    25172513    runner = unittest.TextTestRunner()
    25182514    runner.run(suite)
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_region.py

    r6145 r6304  
    88#from anuga.config import epsilon
    99
    10 import Numeric as num
     10import numpy as num
    1111
    1212
     
    4242
    4343    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]})
    5957
    6058        #Set friction
     
    6563        b = Set_region('top', 'friction', 1.0)
    6664        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
    7577
    7678        #c = Add_Value_To_region('all', 'friction', 10.0)
     
    126128       
    127129    def test_unique_vertices(self):
    128         """
    129         get values based on triangle lists.
    130         """
     130        """get values based on triangle lists."""
     131
    131132        from mesh_factory import rectangular
    132133        from shallow_water import Domain
     
    147148        a = Set_region('bottom', 'friction', 0.09, location = 'unique vertices')
    148149        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(),
    151151                            [[ 0.09,  0.09,  0.09],
    152152                             [ 0.09,  0.09,  0.09],
     
    217217        #print domain.quantities['friction'].get_values()
    218218        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
    223226 
    224227    def test_unique_vertices_average_loc_unique_vert(self):
     
    262265#-------------------------------------------------------------
    263266if __name__ == "__main__":
    264     suite = unittest.makeSuite(Test_Region,'test')
     267    suite = unittest.makeSuite(Test_Region, 'test')   
    265268    runner = unittest.TextTestRunner()
    266269    runner.run(suite)
  • branches/numpy/anuga/abstract_2d_finite_volumes/test_util.py

    r6175 r6304  
    2222import string
    2323
    24 import Numeric as num
     24import numpy as num
    2525
    2626
     
    630630                    q1 = F(t+60, point_id=id)
    631631
    632                 if q0 == NAN:
     632                if num.alltrue(q0 == NAN):
    633633                    actual = q0
    634634                else:
     
    641641                #print "actual", actual
    642642                #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!')
    645645                else:
    646646                    assert num.allclose(q, actual)
     
    11811181        #FIXME: Division is not expected to work for integers.
    11821182        #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)                 
    11861186
    11871187        D = {'X': foo, 'Y': bar}
     
    12011201
    12021202        # make an error for zero on zero
    1203         # this is really an error in Numeric, SciPy core can handle it
     1203        # this is really an error in numeric, SciPy core can handle it
    12041204        # Z = apply_expression_to_dictionary('0/Y', D)
    12051205
  • branches/numpy/anuga/abstract_2d_finite_volumes/util.py

    r6194 r6304  
    2727from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
    2828
    29 import Numeric as num
     29import numpy as num
    3030
    3131
     
    554554                expression e.g. by overloading
    555555
    556     Due to a limitation with Numeric, this can not evaluate 0/0
     556    Due to a limitation with numeric, this can not evaluate 0/0
    557557    In general, the user can fix by adding 1e-30 to the numerator.
    558558    SciPy core can handle this situation.
     
    789789                        - easting, northing, name , elevation?
    790790                    - 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,
    792792                          such as a geospatial data object
    793793                     
     
    12551255    n0 = int(n0)
    12561256    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)
    12691269    min_stages = []
    12701270    max_stages = []
     
    12781278    min_speeds = []   
    12791279    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)
    12831283    if time_unit is 'mins': scale = 60.0
    12841284    if time_unit is 'hours': scale = 3600.0
     
    18321832    """
    18331833       
    1834     xc = num.zeros(triangles.shape[0], num.Float) # Space for centroid info
     1834    xc = num.zeros(triangles.shape[0], num.float) # Space for centroid info
    18351835   
    18361836    for k in range(triangles.shape[0]):
     
    21192119                #add tide to stage if provided
    21202120                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) \
    21222122                                                          + directory_add_tide
    21232123
     
    24692469       
    24702470    #convert to array for file_function
    2471     points_array = num.array(points,num.Float)
     2471    points_array = num.array(points,num.float)
    24722472       
    24732473    points_array = ensure_absolute(points_array)
  • branches/numpy/anuga/advection/advection.py

    r6146 r6304  
    3333from anuga.abstract_2d_finite_volumes.domain import *
    3434
    35 import Numeric as num
     35import numpy as num
    3636
    3737
     
    252252        stage_bdry = Stage.boundary_values
    253253
    254         flux = num.zeros(1, num.Float) #Work array for summing up fluxes
     254        flux = num.zeros(1, num.float) #Work array for summing up fluxes
    255255
    256256        #Loop
  • branches/numpy/anuga/advection/advection_ext.c

    r5162 r6304  
    1010
    1111#include "Python.h"
    12 #include "Numeric/arrayobject.h"
     12#include "numpy/arrayobject.h"
    1313#include "math.h"
    1414#include "stdio.h"
  • branches/numpy/anuga/advection/test_advection.py

    r6146 r6304  
    88from anuga.advection.advection import Domain, Transmissive_boundary, Dirichlet_boundary
    99
    10 import Numeric as num
     10import numpy as num
    1111
    1212
     
    142142
    143143        X = domain.quantities['stage'].explicit_update
     144        #        print 'X=%s' % str(X)
    144145        assert X[0] == -X[1]
    145146
  • branches/numpy/anuga/alpha_shape/alpha_shape.py

    r6174 r6304  
    2525from anuga.geospatial_data.geospatial_data import Geospatial_data
    2626
    27 import Numeric as num
     27import numpy as num
    2828
    2929
     
    8888                raise PointError, "Three points on a straight line"
    8989       
    90         #Convert input to Numeric arrays
    91         self.points = num.array(points, num.Float)
     90        #Convert input to numeric arrays
     91        self.points = num.array(points, num.float)
    9292
    9393   
     
    288288            zeroind = [k for k in range(len(denom)) if \
    289289                       (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
    296297        self.triradius = 0.5*num.sqrt(dx*dx + dy*dy)
    297298        #print "triangle radii", self.triradius
  • branches/numpy/anuga/alpha_shape/test_alpha_shape.py

    r6147 r6304  
    55import unittest
    66
    7 import Numeric as num
     7import numpy as num
    88
    99try:
  • branches/numpy/anuga/caching/caching.py

    r6232 r6304  
    5151  unix = True
    5252
    53 import Numeric as num
     53import numpy as num
    5454
    5555
     
    13901390      I.sort()   
    13911391      val = myhash(I, ids)
    1392   elif type(T) == num.ArrayType:
     1392  elif isinstance(T, num.ndarray):
    13931393      T = num.array(T) # Ensure array is contiguous
    13941394
     
    14611461            identical = compare(a, b, ids)
    14621462           
    1463     elif type(A) == num.ArrayType:
     1463    elif isinstance(A, num.ndarray):
    14641464        # Use element by element comparison
    14651465        identical = num.alltrue(A==B)
     
    24352435      argstr = argstr + "'"+str(args)+"'"
    24362436    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):
    24392439#        if len(args.flat) > textwidth: 
    24402440#        Changed by Duncan and Nick 21/2/07 .flat has problems with
  • branches/numpy/anuga/caching/test_caching.py

    r6232 r6304  
    77from anuga.caching.dummy_classes_for_testing import Dummy, Dummy_memorytest
    88
    9 import Numeric as num
     9import numpy as num
    1010
    1111
     
    2626 
    2727def f_numeric(A, B):
    28   """Operation on Numeric arrays
     28  """Operation on numeric arrays
    2929  """
    3030 
     
    123123        """test_caching_of_numeric_arrays
    124124       
    125         Test that Numeric arrays can be recognised by caching even if their id's are different
     125        Test that numeric arrays can be recognised by caching even if their id's are different
    126126        """
    127127       
     
    160160
    161161
    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'
    164164           
    165165
    166166    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"""
    171168       
    172169        verbose = False
     
    202199            T2 = cache(f_numeric, (A1, A1),
    203200                       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
    214209    def test_caching_of_dictionaries(self):
    215210        """test_caching_of_dictionaries
     
    412407
    413408       
    414         x = num.arange(10).astype(num.Float)
     409        x = num.arange(10).astype(num.float)
    415410       
    416411        ref1 = f1(x)
  • branches/numpy/anuga/config.py

    r6108 r6304  
    44import os
    55import sys
    6 
    7 ################################################################################
    8 # Numerical constants
     6import numpy as num
     7
     8
     9################################################################################
     10# numerical constants
    911################################################################################
    1012
     
    160162                             # Too large (100) creates 'flopping' water
    161163                             # Too small (0) creates 'creep'
    162                            
     164
    163165maximum_froude_number = 100.0 # To be used in limiters.
    164166
     
    181183
    182184################################################################################
     185# NetCDF-specific type constants.  Used when defining NetCDF file variables.
     186################################################################################
     187
     188netcdf_char = 'c'
     189netcdf_byte = 'b'
     190netcdf_int = 'i'
     191netcdf_float = 'd'
     192netcdf_float64 = 'd'
     193netcdf_float32 = 'f'
     194
     195################################################################################
    183196# Dynamically-defined constants.
    184197################################################################################
     
    191204# Code to set the write mode depending on
    192205# whether Scientific.IO supports large NetCDF files
    193 s = """from Scientific.IO.NetCDF import NetCDFFile; fid = NetCDFFile('tmpfilenamexx', 'wl')"""
     206s = """
     207from Scientific.IO.NetCDF import NetCDFFile
     208fid = NetCDFFile('tmpfilenamexx', 'wl')
     209"""
    194210
    195211# Need to run in a separate process due an
  • branches/numpy/anuga/coordinate_transforms/geo_reference.py

    r6149 r6304  
    1111from anuga.utilities.anuga_exceptions import ANUGAError, TitleError, ParsingError, \
    1212     ShapeError
    13 
    14 import Numeric as num
     13from anuga.config import netcdf_float, netcdf_int, netcdf_float32
     14
     15import numpy as num
    1516
    1617
     
    6465        self.xllcorner = xllcorner
    6566        self.yllcorner = yllcorner       
     67        #self.is_absolute = num.allclose([self.xllcorner, self.yllcorner], 0)
    6668           
    6769        if NetCDFObject is not None:
     
    99101       
    100102        # Fix some assertion failures
    101         if type(self.zone) == num.ArrayType and self.zone.shape == ():
     103        if isinstance(self.zone, num.ndarray) and self.zone.shape == ():
    102104            self.zone = self.zone[0]
    103         if type(self.xllcorner) == num.ArrayType and self.xllcorner.shape == ():
     105        if isinstance(self.xllcorner, num.ndarray) and self.xllcorner.shape == ():
    104106            self.xllcorner = self.xllcorner[0]
    105         if type(self.yllcorner) == num.ArrayType and self.yllcorner.shape == ():
     107        if isinstance(self.yllcorner, num.ndarray) and self.yllcorner.shape == ():
    106108            self.yllcorner = self.yllcorner[0]
    107109
    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'])
    113115       
    114116        try:
     
    173175           
    174176        # 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 == ():
    176178            self.zone = self.zone[0]
    177         if type(self.xllcorner) == num.ArrayType and self.xllcorner.shape == ():
     179        if isinstance(self.xllcorner, num.ndarray) and self.xllcorner.shape == ():
    178180            self.xllcorner = self.xllcorner[0]
    179         if type(self.yllcorner) == num.ArrayType and self.yllcorner.shape == ():
     181        if isinstance(self.yllcorner, num.ndarray) and self.yllcorner.shape == ():
    180182            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
    186189       
    187190    def change_points_geo_ref(self, points,
    188191                              points_geo_ref=None):
    189192        """
    190         Change the geo reference of a list or Numeric array of points to
     193        Change the geo reference of a list or numeric array of points to
    191194        be this reference.(The reference used for this object)
    192195        If the points do not have a geo ref, assume 'absolute' values
     
    197200            is_list = True
    198201
    199         points = ensure_numeric(points, num.Float)
     202        points = ensure_numeric(points, num.float)
    200203       
    201204        if len(points.shape) == 1:
     
    243246
    244247       
    245    
     248    ##
     249    # @brief
     250    # @param points
     251    # @return
     252    # @note
    246253    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,
    249255        return the points as absolute values.
    250256        """
    251257
    252         #if self.is_absolute():
     258        #if self.is_absolute:
    253259        #    return points
     260
    254261        is_list = False
    255262        if type(points) == types.ListType:
    256263            is_list = True
    257264
    258         points = ensure_numeric(points, num.Float)
     265        points = ensure_numeric(points, num.float)
    259266        if len(points.shape) == 1:
    260267            #One point has been passed
     
    264271                #points = reshape(points, (1,2))
    265272
    266 
    267273        msg = 'Input must be an N x 2 array or list of (x,y) values. '
    268274        msg += 'I got an %d x %d array' %points.shape   
    269275        if not points.shape[1] == 2:
    270276            raise ShapeError, msg   
    271            
    272277       
    273278        # Add geo ref to points
     279        #if not self.is_absolute:
    274280        if not self.is_absolute():
    275281            points[:,0] += self.xllcorner
    276282            points[:,1] += self.yllcorner
    277 
     283            #self.is_absolute = True
    278284       
    279285        if is_list:
     
    296302            is_list = True
    297303
    298         points = ensure_numeric(points, num.Float)
     304        points = ensure_numeric(points, num.float)
    299305        if len(points.shape) == 1:
    300306            #One point has been passed
  • branches/numpy/anuga/coordinate_transforms/test_geo_reference.py

    r6149 r6304  
    99from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
    1010
    11 import Numeric as num
     11import numpy as num
    1212
    1313
     
    171171        #print "4 new_lofl",new_lofl
    172172
    173         self.failUnless(type(new_lofl) == num.ArrayType, ' failed')
     173        self.failUnless(isinstance(new_lofl, num.ndarray), ' failed')
    174174        self.failUnless(type(new_lofl) == type(lofl), ' failed')
    175175        lofl[:,0] -= x
     
    189189        #print "5 new_lofl",new_lofl
    190190
    191         self.failUnless(type(new_lofl) == num.ArrayType, ' failed')
     191        self.failUnless(isinstance(new_lofl, num.ndarray), ' failed')
    192192        self.failUnless(type(new_lofl) == type(lofl), ' failed')
    193193
     
    206206        #print "new_lofl",new_lofl
    207207
    208         self.failUnless(type(new_lofl) == num.ArrayType, ' failed')
     208        self.failUnless(isinstance(new_lofl, num.ndarray), ' failed')
    209209        self.failUnless(type(new_lofl) == type(lofl), ' failed')
    210210        for point,new_point in map(None,[lofl],new_lofl):
     
    229229            self.failUnless(point[0]+point_x-x==new_point[0], ' failed')
    230230            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
    234234        x = 7.0
    235235        y = 3.0
    236236       
    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')
    249257           
     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
    250299        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
    262342    def test_is_absolute(self):
    263343       
     
    427507if __name__ == "__main__":
    428508
    429     suite = unittest.makeSuite(geo_referenceTestCase,'test')
     509    #suite = unittest.makeSuite(geo_referenceTestCase,'test')
     510    suite = unittest.makeSuite(geo_referenceTestCase,'test_get_absolute')
    430511    runner = unittest.TextTestRunner() #verbosity=2)
    431512    runner.run(suite)
  • branches/numpy/anuga/coordinate_transforms/test_lat_long_UTM_conversion.py

    r6149 r6304  
    1212from anuga.utilities.anuga_exceptions import ANUGAError
    1313
    14 import Numeric as num
     14import numpy as num
    1515
    1616
  • branches/numpy/anuga/coordinate_transforms/test_redfearn.py

    r6149 r6304  
    1111from anuga.utilities.anuga_exceptions import ANUGAError
    1212
    13 import Numeric as num
     13import numpy as num
    1414
    1515
  • branches/numpy/anuga/culvert_flows/Test_Culvert_Flat_Water_Lev.py

    r6150 r6304  
    2626from math import pi,pow,sqrt
    2727
    28 import Numeric as num
     28import numpy as num
    2929
    3030
  • branches/numpy/anuga/culvert_flows/culvert_class.py

    r6150 r6304  
    1414from anuga.config import minimum_allowed_height, velocity_protection       
    1515
    16 import Numeric as num
     16import numpy as num
    1717
    1818
  • branches/numpy/anuga/culvert_flows/culvert_polygons.py

    r6150 r6304  
    66from anuga.utilities.polygon import inside_polygon, polygon_area
    77
    8 import Numeric as num
     8import numpy as num
    99
    1010
  • branches/numpy/anuga/culvert_flows/test_culvert_class.py

    r6150 r6304  
    2121from math import pi,pow,sqrt
    2222
    23 import Numeric as num
     23import numpy as num
    2424
    2525
     
    470470        ref_volume = domain.get_quantity('stage').get_integral()
    471471        for t in domain.evolve(yieldstep = 1, finaltime = 25):
     472           
    472473            #print domain.timestepping_statistics()
    473474            new_volume = domain.get_quantity('stage').get_integral()
    474            
     475
    475476            msg = 'Total volume has changed'
    476477            assert num.allclose(new_volume, ref_volume), msg
     
    564565#-------------------------------------------------------------
    565566if __name__ == "__main__":
    566     #suite = unittest.makeSuite(Test_Culvert, 'test_that_culvert_rating_limits_flow_in_shallow_inlet_condition')
    567567    suite = unittest.makeSuite(Test_Culvert, 'test')
    568     runner = unittest.TextTestRunner()
     568    runner = unittest.TextTestRunner() #verbosity=2)
    569569    runner.run(suite)
    570570       
  • branches/numpy/anuga/damage_modelling/inundation_damage.py

    r6151 r6304  
    1010from types import StringType
    1111
    12 import Numeric as num
     12import numpy as num
    1313
    1414
     
    1717except ImportError: 
    1818    # 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 may 
     19    # was recently removed from the standard numeric distro.  Some users may 
    2020    # not have it by default. 
    2121    class _bunch: 
     
    314314
    315315        # 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)
    318318        self.struct_inundated = ['']* self.structure_count
    319319
  • branches/numpy/anuga/damage_modelling/test_inundation_damage.py

    r6151 r6304  
    1717from anuga.shallow_water.data_manager import get_dataobject
    1818
    19 import Numeric as num
     19import numpy as num
    2020
    2121
     
    8383        #Initial condition - with jumps
    8484        bed = domain.quantities['elevation'].vertex_values
    85         stage = num.zeros(bed.shape, num.Float)
     85        stage = num.zeros(bed.shape, num.float)
    8686
    8787        h = 0.3
     
    153153        #Initial condition - with jumps
    154154        bed = domain.quantities['elevation'].vertex_values
    155         stage = num.zeros(bed.shape, num.Float)
     155        stage = num.zeros(bed.shape, num.float)
    156156
    157157        h = 30.
     
    476476        edm = EventDamageModel([0.0]*17, [0.0]*17, [0.0]*17,
    477477                               [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)
    480480        collapse_probability = {0.4:[0], #0
    481481                                0.6:[1], #1
     
    597597        pass
    598598    suite = unittest.makeSuite(Test_inundation_damage,'test')
    599     #suite = unittest.makeSuite(Test_inundation_damage,'test_inundation_damage_list_as_input')
    600599    runner = unittest.TextTestRunner()
    601600    runner.run(suite)
  • branches/numpy/anuga/fit_interpolate/fit.py

    r6244 r6304  
    4545class VertsWithNoTrianglesError(exceptions.Exception): pass
    4646
    47 import Numeric as num
     47import numpy as num
    4848
    4949
     
    6666
    6767          vertex_coordinates: List of coordinate pairs [xi, eta] of
    68               points constituting a mesh (or an m x 2 Numeric array or
     68              points constituting a mesh (or an m x 2 numeric array or
    6969              a geospatial object)
    7070              Points may appear multiple times
    7171              (e.g. if vertices have discontinuities)
    7272
    73           triangles: List of 3-tuples (or a Numeric array) of
     73          triangles: List of 3-tuples (or a numeric array) of
    7474              integers representing indices of all vertices in the mesh.
    7575
     
    251251            if len(z.shape) > 1:
    252252                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)
    254254            else:
    255255                att_num = 1
    256                 self.Atz = num.zeros((m,), num.Float)
     256                self.Atz = num.zeros((m,), num.float)
    257257            assert z.shape[0] == point_coordinates.shape[0]
    258258
     
    336336        point_coordinates: The co-ordinates of the data points.
    337337              List of coordinate pairs [x, y] of
    338               data points or an nx2 Numeric array or a Geospatial_data object
     338              data points or an nx2 numeric array or a Geospatial_data object
    339339              or points file filename
    340340          z: Single 1d vector or array of data at the point_coordinates.
     
    382382        if point_coordinates is None:
    383383            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
    386388           
    387389            # FIXME (DSG) - do  a message
     
    433435        point_coordinates: The co-ordinates of the data points.
    434436              List of coordinate pairs [x, y] of
    435               data points or an nx2 Numeric array or a Geospatial_data object
     437              data points or an nx2 numeric array or a Geospatial_data object
    436438        z: Single 1d vector or array of data at the point_coordinates.
    437439        attribute_name: Used to get the z values from the
     
    448450                absolute = True)
    449451       
    450         # Convert input to Numeric arrays
     452        # Convert input to numeric arrays
    451453        if z is not None:
    452             z = ensure_numeric(z, num.Float)
     454            z = ensure_numeric(z, num.float)
    453455        else:
    454456            msg = 'z not specified'
     
    456458            z = point_coordinates.get_attributes(attribute_name)
    457459
    458         point_coordinates = ensure_numeric(point_coordinates, num.Float)
     460        point_coordinates = ensure_numeric(point_coordinates, num.float)
    459461        self._build_matrix_AtA_Atz(point_coordinates, z, verbose)
    460462
     
    556558        Inputs:
    557559        vertex_coordinates: List of coordinate pairs [xi, eta] of
    558               points constituting a mesh (or an m x 2 Numeric array or
     560              points constituting a mesh (or an m x 2 numeric array or
    559561              a geospatial object)
    560562              Points may appear multiple times
    561563              (e.g. if vertices have discontinuities)
    562564
    563           triangles: List of 3-tuples (or a Numeric array) of
     565          triangles: List of 3-tuples (or a numeric array) of
    564566          integers representing indices of all vertices in the mesh.
    565567
    566568          point_coordinates: List of coordinate pairs [x, y] of data points
    567           (or an nx2 Numeric array). This can also be a .csv/.txt/.pts
     569          (or an nx2 numeric array). This can also be a .csv/.txt/.pts
    568570          file name.
    569571
     
    593595        # are None
    594596           
    595         #Convert input to Numeric arrays
    596         triangles = ensure_numeric(triangles, num.Int)
     597        #Convert input to numeric arrays
     598        triangles = ensure_numeric(triangles, num.int)
    597599        vertex_coordinates = ensure_absolute(vertex_coordinates,
    598600                                             geo_reference = mesh_origin)
     
    662664    vertex_coordinates = mesh_dict['vertices']
    663665    triangles = mesh_dict['triangles']
    664     if type(mesh_dict['vertex_attributes']) == num.ArrayType:
     666    if isinstance(mesh_dict['vertex_attributes'], num.ndarray):
    665667        old_point_attributes = mesh_dict['vertex_attributes'].tolist()
    666668    else:
    667669        old_point_attributes = mesh_dict['vertex_attributes']
    668670
    669     if type(mesh_dict['vertex_attribute_titles']) == num.ArrayType:
     671    if isinstance(mesh_dict['vertex_attribute_titles'], num.ndarray):
    670672        old_title_list = mesh_dict['vertex_attribute_titles'].tolist()
    671673    else:
  • branches/numpy/anuga/fit_interpolate/general_fit_interpolate.py

    r6152 r6304  
    3535from anuga.fit_interpolate.search_functions import set_last_triangle
    3636
    37 import Numeric as num
     37import numpy as num
    3838
    3939
     
    6767
    6868          vertex_coordinates: List of coordinate pairs [xi, eta] of
    69               points constituting a mesh (or an m x 2 Numeric array or
     69              points constituting a mesh (or an m x 2 numeric array or
    7070              a geospatial object)
    7171              Points may appear multiple times
    7272              (e.g. if vertices have discontinuities)
    7373
    74           triangles: List of 3-tuples (or a Numeric array) of
     74          triangles: List of 3-tuples (or a numeric array) of
    7575              integers representing indices of all vertices in the mesh.
    7676
     
    9696                # are None
    9797           
    98                 #Convert input to Numeric arrays
    99                 triangles = ensure_numeric(triangles, num.Int)
     98                #Convert input to numeric arrays
     99                triangles = ensure_numeric(triangles, num.int)
    100100                vertex_coordinates = ensure_absolute(vertex_coordinates,
    101101                                                 geo_reference = mesh_origin)
  • branches/numpy/anuga/fit_interpolate/interpolate.py

    r6223 r6304  
    4141
    4242
    43 import Numeric as num
     43import numpy as num
    4444
    4545
     
    7777    vertex_coordinates: List of coordinate pairs [xi, eta] of
    7878                        points constituting a mesh
    79                         (or an m x 2 Numeric array or
     79                        (or an m x 2 numeric array or
    8080                        a geospatial object)
    8181                        Points may appear multiple times
    8282                        (e.g. if vertices have discontinuities)
    8383
    84     triangles: List of 3-tuples (or a Numeric array) of
     84    triangles: List of 3-tuples (or a numeric array) of
    8585               integers representing indices of all vertices
    8686               in the mesh.
     
    9292    interpolation_points: Interpolate mesh data to these positions.
    9393                          List of coordinate pairs [x, y] of
    94                           data points or an nx2 Numeric array or a
     94                          data points or an nx2 numeric array or a
    9595                          Geospatial_data object
    9696               
     
    132132
    133133    # Create interpolation object with matrix
    134     args = (ensure_numeric(vertex_coordinates, num.Float),
     134    args = (ensure_numeric(vertex_coordinates, num.float),
    135135            ensure_numeric(triangles))
    136136    kwargs = {'mesh_origin': mesh_origin,
     
    181181        Inputs:
    182182          vertex_coordinates: List of coordinate pairs [xi, eta] of
    183               points constituting a mesh (or an m x 2 Numeric array or
     183              points constituting a mesh (or an m x 2 numeric array or
    184184              a geospatial object)
    185185              Points may appear multiple times
    186186              (e.g. if vertices have discontinuities)
    187187
    188           triangles: List of 3-tuples (or a Numeric array) of
     188          triangles: List of 3-tuples (or a numeric array) of
    189189              integers representing indices of all vertices in the mesh.
    190190
     
    243243          point_coordinates: Interpolate mesh data to these positions.
    244244              List of coordinate pairs [x, y] of
    245               data points or an nx2 Numeric array or a Geospatial_data object
     245              data points or an nx2 numeric array or a Geospatial_data object
    246246             
    247247              If point_coordinates is absent, the points inputted last time
     
    294294                # creating a dummy array to concatenate to.
    295295               
    296                 f = ensure_numeric(f, num.Float)
     296                f = ensure_numeric(f, num.float)
    297297                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#
    299299                else:
    300                     z = num.zeros((0,))
     300                    z = num.zeros((0,), num.int)        #array default#
    301301                   
    302302                for end in range(start_blocking_len,
     
    340340            point_coordinates = point_coordinates.get_data_points(absolute=True)
    341341
    342         # Convert lists to Numeric arrays if necessary
    343         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)               
    345345
    346346        from anuga.caching import myhash
     
    447447        if verbose: print 'Building interpolation matrix'
    448448
    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)
    451451
    452452        if verbose: print 'Getting indices inside mesh boundary'
     
    526526    points: Interpolate mesh data to these positions.
    527527            List of coordinate pairs [x, y] of
    528             data points or an nx2 Numeric array or a Geospatial_data object
     528            data points or an nx2 numeric array or a Geospatial_data object
    529529             
    530530    No test for this yet.
     
    694694
    695695    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)
    698698                              The arrays must either have dimensions pxm or mx1.
    699699                              The resulting function will be time dependent in
     
    704704        quantity_names:       List of keys into the quantities dictionary for
    705705                              imposing a particular order on the output vector.
    706         vertex_coordinates:   mx2 array of coordinates (Float)
     706        vertex_coordinates:   mx2 array of coordinates (float)
    707707        triangles:            nx3 array of indices into vertex_coordinates (Int)
    708708        interpolation_points: Nx2 array of coordinates to be interpolated to
     
    810810        self.quantities_range = {}
    811811        for name in quantity_names:
    812             q = quantities[name][:].flat
     812            q = quantities[name][:].flatten()
    813813            self.quantities_range[name] = [min(q), max(q)]
    814814       
     
    830830                    interpolation_points = ensure_numeric(interpolation_points)
    831831            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 ' \
    833833                      'or a list of points\n'
    834834                msg += 'Got: %s.' %(str(self.interpolation_points)[:60] + '...')
     
    913913           
    914914            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)
    916916
    917917            if verbose is True:
     
    10561056
    10571057        # Compute interpolated values
    1058         q = num.zeros(len(self.quantity_names), num.Float)
     1058        q = num.zeros(len(self.quantity_names), num.float)
    10591059        for i, name in enumerate(self.quantity_names):
    10601060            Q = self.precomputed_values[name]
     
    11051105                    res = []
    11061106                    for col in q:
    1107                         res.append(col*num.ones(N, num.Float))
     1107                        res.append(col*num.ones(N, num.float))
    11081108                       
    11091109                return res
     
    11451145            minq, maxq = self.quantities_range[name]
    11461146            str += '    %s in [%f, %f]\n' %(name, minq, maxq)           
    1147             #q = quantities[name][:].flat
     1147            #q = quantities[name][:].flatten()
    11481148            #str += '    %s in [%f, %f]\n' %(name, min(q), max(q))
    11491149
     
    11581158       
    11591159            for name in quantity_names:
    1160                 q = precomputed_values[name][:].flat
     1160                q = precomputed_values[name][:].flatten()
    11611161                str += '    %s at interpolation points in [%f, %f]\n'\
    11621162                       %(name, min(q), max(q))
     
    11901190
    11911191    #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)
    11931193
    11941194    #Will return the quantity values at the specified times and locations
     
    12621262    keys.remove("volumes")
    12631263    keys.remove("time")
    1264      #Turn NetCDF objects into Numeric arrays
     1264     #Turn NetCDF objects into numeric arrays
    12651265    quantities = {}
    12661266    for name in keys:
  • branches/numpy/anuga/fit_interpolate/search_functions.py

    r6174 r6304  
    1111from anuga.config import max_float
    1212
    13 import Numeric as num
     13import numpy as num
    1414
    1515
     
    2222                        num.array([max_float,max_float]),
    2323                        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]),
    2626                        num.array([-1.1,-1.1]))]]]
    2727
  • branches/numpy/anuga/fit_interpolate/test_fit.py

    r6174 r6304  
    2121from anuga.shallow_water import Domain
    2222
    23 import Numeric as num
     23import numpy as num
    2424
    2525
     
    582582
    583583        #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
    585585
    586586        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
     
    589589
    590590        #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
    592592
    593593        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
     
    596596
    597597        #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
    599599
    600600        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
     
    623623
    624624        #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
    626626
    627627        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
     
    630630
    631631        #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
    633633
    634634        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
     
    637637
    638638        #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
    640640
    641641        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
     
    10991099if __name__ == "__main__":
    11001100    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)
    11041102    runner.run(suite)
    11051103
  • branches/numpy/anuga/fit_interpolate/test_interpolate.py

    r6189 r6304  
    1515from Scientific.IO.NetCDF import NetCDFFile
    1616
    17 import Numeric as num
     17import numpy as num
    1818
    1919
     
    6767
    6868        bed = domain.quantities['elevation'].vertex_values
    69         stage = num.zeros(bed.shape, num.Float)
     69        stage = num.zeros(bed.shape, num.float)
    7070
    7171        h = 0.3
     
    129129
    130130        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 )
    132132        # FIXME: This concat should roll into get_vertex_values
    133133
     
    149149       
    150150        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 )
    152152        # FIXME: This concat should roll into get_vertex_values
    153153
     
    182182
    183183        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 )
    185185        # FIXME: This concat should roll into get_vertex_values
    186186
     
    201201       
    202202        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 )
    204204        # FIXME: This concat should roll into get_vertex_values
    205205
     
    233233       
    234234        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 )
    236236        # FIXME: This concat should roll into get_vertex_values
    237237
     
    10781078
    10791079        #One quantity
    1080         Q = num.zeros( (3,6), num.Float )
     1080        Q = num.zeros( (3,6), num.float )
    10811081
    10821082        #Linear in time and space
     
    12251225
    12261226        #One quantity
    1227         Q = num.zeros( (3,6), num.Float )
     1227        Q = num.zeros( (3,6), num.float )
    12281228
    12291229        #Linear in time and space
     
    12851285
    12861286        # One quantity
    1287         Q = num.zeros((8,6), num.Float)
     1287        Q = num.zeros((8,6), num.float)
    12881288
    12891289        # Linear in time and space
     
    13531353
    13541354        #One quantity
    1355         Q = num.zeros( (2,6), num.Float )
     1355        Q = num.zeros( (2,6), num.float )
    13561356
    13571357        #Linear in time and space
     
    14191419
    14201420        # One quantity
    1421         Q = num.zeros( (3,6), num.Float )
     1421        Q = num.zeros( (3,6), num.float )
    14221422
    14231423        # Linear in time and space
     
    16081608
    16091609        #One quantity
    1610         Q = num.zeros( (len(time),6), num.Float )
     1610        Q = num.zeros( (len(time),6), num.float )
    16111611
    16121612        #Linear in time and space
     
    18501850if __name__ == "__main__":
    18511851    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)
    18541853    runner.run(suite)
    18551854
  • branches/numpy/anuga/fit_interpolate/test_search_functions.py

    r6152 r6304  
    211211if __name__ == "__main__":
    212212    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)
    215214    runner.run(suite)
    216215   
  • branches/numpy/anuga/geospatial_data/geospatial_data.py

    r6166 r6304  
    1313from Scientific.IO.NetCDF import NetCDFFile
    1414
    15 import Numeric as num
     15import numpy as num
    1616
    1717from anuga.coordinate_transforms.lat_long_UTM_conversion import UTMtoLL
     
    2323from anuga.config import points_file_block_line_size as MAX_READ_LINES
    2424from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
     25from anuga.config import netcdf_float
    2526
    2627DEFAULT_ATTRIBUTE = 'elevation'
     
    5657                 load_file_now=True,
    5758                 verbose=False):
    58         """
    59         Create instance from data points and associated attributes
     59        """Create instance from data points and associated attributes
    6060
    6161        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 name
     62        sequence of 2-tuples or an Mx2 numeric array of floats.  A file name
    6363        with extension .txt, .cvs or .pts can also be passed in here.
    6464
     
    131131
    132132        verbose:
    133 
    134133        """
    135134
    136135        if isinstance(data_points, basestring):
    137             # assume data point is really a file name
     136            # assume data_points is really a file name
    138137            file_name = data_points
    139138
    140139        self.set_verbose(verbose)
    141         self.geo_reference = None #create the attribute
     140        self.geo_reference = None # create the attribute
    142141        self.file_name = file_name
    143142
     
    157156                                        data_points=data_points,
    158157                                        points_are_lats_longs=\
    159                                             points_are_lats_longs)
     158                                        points_are_lats_longs)
    160159            self.check_data_points(data_points)
    161160            self.set_attributes(attributes)
     
    188187                        # This message was misleading.
    189188                        # 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'
    193192
    194193    ##
     
    203202
    204203    ##
    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.
    207206    # @note Throws ValueError exception if no data.
    208207    def check_data_points(self, data_points):
    209         """Checks data points
    210         """
     208        """Checks data points"""
    211209
    212210        if data_points is None:
     
    217215        else:
    218216            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)
    219221            if not (0,) == self.data_points.shape:
    220222                assert len(self.data_points.shape) == 2
     
    226228    # @note Throws exception if unable to convert dict keys to numeric.
    227229    def set_attributes(self, attributes):
    228         """Check and assign attributes dictionary
    229         """
     230        """Check and assign attributes dictionary"""
    230231
    231232        if attributes is None:
     
    234235
    235236        if not isinstance(attributes, DictType):
    236             #Convert single attribute into dictionary
     237            # Convert single attribute into dictionary
    237238            attributes = {DEFAULT_ATTRIBUTE: attributes}
    238239
    239         #Check input attributes
     240        # Check input attributes
    240241        for key in attributes.keys():
    241242            try:
    242243                attributes[key] = ensure_numeric(attributes[key])
    243244            except:
    244                 msg = 'Attribute %s could not be converted' %key
    245                 msg += 'to a numeric vector'
    246                 raise msg
     245                msg = ("Attribute '%s' (%s) could not be converted to a"
     246                       "numeric vector" % (str(key), str(attributes[key])))
     247                raise Exception, msg
    247248
    248249        self.attributes = attributes
    249250
    250     #def set_geo_reference(self, geo_reference):
    251     #    # FIXME (Ole): Backwards compatibility - deprecate
    252     #    self.setgeo_reference(geo_reference)
    253 
    254251    ##
    255252    # @brief Set the georeference of geospatial data.
    256     # @param geo_reference The georeference data    to set.
     253    # @param geo_reference The georeference data to set.
    257254    # @note Will raise exception if param not instance of Geo_reference.
    258255    def set_geo_reference(self, geo_reference):
     
    277274            msg = 'Argument geo_reference must be a valid Geo_reference '
    278275            msg += 'object or None.'
    279             raise msg
     276            raise Expection, msg
    280277
    281278        # If a geo_reference already exists, change the point data according to
     
    511508                        raise Exception, msg
    512509        else:
    513             #other is None:
     510            # other is None:
    514511            new_points = self.get_data_points(absolute=True)
    515512            new_attributes = self.attributes
     
    525522    # @return The new geospatial object.
    526523    def __radd__(self, other):
    527         """Handle cases like None + Geospatial_data(...)
    528         """
     524        """Handle cases like None + Geospatial_data(...)"""
    529525
    530526        return self + other
     
    542538    def import_points_file(self, file_name, delimiter=None, verbose=False):
    543539        """ load an .txt, .csv or .pts file
     540
    544541        Note: will throw an IOError/SyntaxError if it can't load the file.
    545542        Catch these!
     
    571568            except SyntaxError, e:
    572569                # This should only be if there is a format error
    573                 msg = 'Could not open file %s. \n' %file_name
     570                msg = 'Problem with format of file %s. \n' %file_name
    574571                msg += Error_message['IOError']
    575572                raise SyntaxError, msg
     
    591588                           as_lat_long=False, isSouthHemisphere=True):
    592589
    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
    595592        file_name is the file name, including the extension
    596593        The point_dict is defined at the top of this file.
     
    659656        """
    660657
    661         #FIXME: add the geo_reference to this
     658        # FIXME: add the geo_reference to this
    662659        points = self.get_data_points()
    663660        sampled_points = num.take(points, indices)
     
    679676    # @note Points in each result object are selected randomly.
    680677    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'
    683679        smaller the original and the second is the remainder. The two
    684         new object are disjoin set of each other.
     680        new objects are disjoint sets of each other.
    685681
    686682        Points of the two new object have selected RANDOMLY.
     
    707703        if verbose: print "make unique random number list and get indices"
    708704
    709         total=num.array(range(self_size), num.Int)     #array default#
     705        total=num.array(range(self_size))
    710706        total_list = total.tolist()
    711707
     
    731727        random_num = random_num.tolist()
    732728
    733         #need to sort and reverse so the pop() works correctly
     729        # need to sort and reverse so the pop() works correctly
    734730        random_num.sort()
    735731        random_num.reverse()
     
    748744            random_list.append(remainder_list.pop(i))
    749745            j += 1
    750             #prints progress
     746            # prints progress
    751747            if verbose and round(random_num_len/10*k) == j:
    752748                print '(%s/%s)' % (j, random_num_len)
     
    779775        """
    780776        from Scientific.IO.NetCDF import NetCDFFile
    781         #FIXME - what to do if the file isn't there
     777        # FIXME - what to do if the file isn't there
    782778
    783779        # FIXME (Ole): Shouldn't this go into the constructor?
     
    941937                        data_points,
    942938                        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."""
    946940
    947941    if geo_reference is not None:
     
    10551049                                                 header,
    10561050                                                 max_read_lines=1e30)
    1057                                     #If the file is bigger that this, block..
     1051                                    # If the file is bigger that this, block..
    10581052                                    # FIXME (Ole) What's up here?
    10591053    except ANUGAError:
     
    10821076    """
    10831077
    1084     line = file_pointer.readline()
     1078    line = file_pointer.readline().strip()
    10851079    header = clean_line(line, delimiter)
    10861080
     
    10951089# @param verbose True if this function is to be verbose.
    10961090# @note Will throw IndexError, SyntaxError exceptions.
    1097 def _read_csv_file_blocking(file_pointer, header,
     1091def _read_csv_file_blocking(file_pointer,
     1092                            header,
    10981093                            delimiter=CSV_DELIMITER,
    10991094                            max_read_lines=MAX_READ_LINES,
     
    11501145        raise StopIteration
    11511146
    1152     pointlist = num.array(points, num.Float)
     1147    pointlist = num.array(points, num.float)
    11531148    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)
    11551150
    11561151    # Do stuff here so the info is in lat's and longs
     
    11831178# @note Will throw IOError and AttributeError exceptions.
    11841179def _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"""
    11871181
    11881182    keys = fid.variables.keys()
     
    12121206# @return Tuple of (pointlist, attributes).
    12131207def _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."""
    12161209
    12171210    pointlist = num.array(fid.variables['points'][start_row:fin_row])
     
    12391232
    12401233    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.
    12421235    # There can't be an attribute called points
    12431236    # consider format change
     
    12641257    shape = write_data_points.shape[0]
    12651258    outfile.createDimension('number_of_points', shape)
    1266     outfile.createDimension('number_of_dimensions', 2) #This is 2d data
     1259    outfile.createDimension('number_of_dimensions', 2) # This is 2d data
    12671260
    12681261    # Variable definition
    1269     outfile.createVariable('points', num.Float, ('number_of_points',
    1270                                                  'number_of_dimensions'))
    1271 
    1272     #create variables
    1273     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
    12741267
    12751268    if write_attributes is not None:
    12761269        for key in write_attributes.keys():
    1277             outfile.createVariable(key, num.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]
    12791272
    12801273    if write_geo_reference is not None:
     
    12961289                    as_lat_long=False,
    12971290                    delimiter=','):
    1298     """Write a .csv file.
    1299     """
     1291    """Write a .csv file."""
    13001292
    13011293    points = write_data_points
     
    13611353# @return ??
    13621354def _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)
    13641356
    13651357    for key in point_atts['attributelist'].keys():
    13661358        point_atts['attributelist'][key] = \
    1367                 num.array(point_atts['attributelist'][key], num.Float)
     1359                num.array(point_atts['attributelist'][key], num.float)
    13681360
    13691361    return point_atts
     
    13751367# @return A points dictionary.
    13761368def geospatial_data2points_dictionary(geospatial_data):
    1377     """Convert geospatial data to points_dictionary
    1378     """
     1369    """Convert geospatial data to points_dictionary"""
    13791370
    13801371    points_dictionary = {}
     
    13961387# @param points_dictionary A points dictionary to convert.
    13971388def points_dictionary2geospatial_data(points_dictionary):
    1398     """Convert points_dictionary to geospatial data object
    1399     """
     1389    """Convert points_dictionary to geospatial data object"""
    14001390
    14011391    msg = 'Points dictionary must have key pointlist'
     
    14171407##
    14181408# @brief Split a string into 'clean' fields.
    1419 # @param line The string to process.
     1409# @param str The string to process.
    14201410# @param delimiter The delimiter string to split 'line' with.
    14211411# @return A list of 'cleaned' field strings.
    14221412# @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.
     1414def 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 != '']
    14391418
    14401419
     
    14621441    # Input check
    14631442    if isinstance(points, basestring):
    1464         #It's a string - assume it is a point file
     1443        # It's a string - assume it is a point file
    14651444        points = Geospatial_data(file_name=points)
    14661445
     
    14701449        assert geo_reference == None, msg
    14711450    else:
    1472         points = ensure_numeric(points, num.Float)
     1451        points = ensure_numeric(points, num.float)
    14731452
    14741453    # Sort of geo_reference and convert points
    14751454    if geo_reference is None:
    1476         geo = None #Geo_reference()
     1455        geo = None # Geo_reference()
    14771456    else:
    14781457        if isinstance(geo_reference, Geo_reference):
     
    14931472# @return A geospatial object.
    14941473def 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.
    14981475
    14991476    Inputed formats are;
     
    15141491    else:
    15151492        # List or numeric array of absolute points
    1516         points = ensure_numeric(points, num.Float)
     1493        points = ensure_numeric(points, num.float)
    15171494
    15181495    # Sort out geo reference
     
    15631540                                     cache=False,
    15641541                                     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.
    15701546
    15711547    data_file: must not contain points outside the boundaries defined
     
    16281604        if no_boundary is True:
    16291605            msg = 'All boundaries must be defined'
    1630             raise msg
     1606            raise Expection, msg
    16311607
    16321608        poly_topo = [[east_boundary,south_boundary],
     
    16451621
    16461622    else: # if mesh file provided
    1647         #test mesh file exists?
     1623        # test mesh file exists?
    16481624        if verbose: "reading from file: %s" % mesh_file
    16491625        if access(mesh_file,F_OK) == 0:
     
    16511627            raise IOError, msg
    16521628
    1653     #split topo data
     1629    # split topo data
    16541630    if verbose: print 'Reading elevation file: %s' % data_file
    16551631    G = Geospatial_data(file_name = data_file)
     
    16681644        alphas = alpha_list
    16691645
    1670     #creates array with columns 1 and 2 are x, y. column 3 is elevation
    1671     #4 onwards is the elevation_predicted using the alpha, which will
    1672     #be compared later against the real removed data
    1673     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)
    16741650
    16751651    data=num.resize(data, (len(points), 3+len(alphas)))
    16761652
    1677     #gets relative point from sample
     1653    # gets relative point from sample
    16781654    data[:,0] = points[:,0]
    16791655    data[:,1] = points[:,1]
     
    16811657    data[:,2] = elevation_sample
    16821658
    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)
    16841660
    16851661    if verbose: print 'Setup computational domains with different alphas'
    16861662
    16871663    for i, alpha in enumerate(alphas):
    1688         #add G_other data to domains with different alphas
     1664        # add G_other data to domains with different alphas
    16891665        if verbose:
    16901666            print '\n Calculating domain and mesh for Alpha = ', alpha, '\n'
     
    17001676        points_geo = Geospatial_data(points, domain.geo_reference)
    17011677
    1702         #returns the predicted elevation of the points that were "split" out
    1703         #of the original data set for one particular alpha
     1678        # returns the predicted elevation of the points that were "split" out
     1679        # of the original data set for one particular alpha
    17041680        if verbose: print 'Get predicted elevation for location to be compared'
    17051681        elevation_predicted = \
     
    17071683                    get_values(interpolation_points=points_geo)
    17081684
    1709         #add predicted elevation to array that starts with x, y, z...
     1685        # add predicted elevation to array that starts with x, y, z...
    17101686        data[:,i+3] = elevation_predicted
    17111687
     
    18341810        if no_boundary is True:
    18351811            msg = 'All boundaries must be defined'
    1836             raise msg
     1812            raise Expection, msg
    18371813
    18381814        poly_topo = [[east_boundary,south_boundary],
     
    18511827
    18521828    else: # if mesh file provided
    1853         #test mesh file exists?
     1829        # test mesh file exists?
    18541830        if access(mesh_file,F_OK) == 0:
    18551831            msg = "file %s doesn't exist!" % mesh_file
    18561832            raise IOError, msg
    18571833
    1858     #split topo data
     1834    # split topo data
    18591835    G = Geospatial_data(file_name=data_file)
    18601836    if verbose: print 'start split'
     
    18631839    points = G_small.get_data_points()
    18641840
    1865     #FIXME: Remove points outside boundary polygon
     1841    # FIXME: Remove points outside boundary polygon
    18661842#    print 'new point',len(points)
    18671843#
    18681844#    new_points=[]
    1869 #    new_points=array([],typecode=Float)
     1845#    new_points=array([],dtype=float)
    18701846#    new_points=resize(new_points,(len(points),2))
    18711847#    print "BOUNDARY", boundary_poly
     
    18901866
    18911867    for alpha in alphas:
    1892         #add G_other data to domains with different alphas
     1868        # add G_other data to domains with different alphas
    18931869        if verbose:
    18941870            print '\n Calculating domain and mesh for Alpha = ', alpha, '\n'
     
    19021878        domains[alpha] = domain
    19031879
    1904     #creates array with columns 1 and 2 are x, y. column 3 is elevation
    1905     #4 onwards is the elevation_predicted using the alpha, which will
    1906     #be compared later against the real removed data
    1907     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)
    19081884
    19091885    data = num.resize(data, (len(points), 3+len(alphas)))
    19101886
    1911     #gets relative point from sample
     1887    # gets relative point from sample
    19121888    data[:,0] = points[:,0]
    19131889    data[:,1] = points[:,1]
     
    19151891    data[:,2] = elevation_sample
    19161892
    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)
    19181894
    19191895    if verbose:
     
    19231899
    19241900        points_geo = domains[alpha].geo_reference.change_points_geo_ref(points)
    1925         #returns the predicted elevation of the points that were "split" out
    1926         #of the original data set for one particular alpha
     1901        # returns the predicted elevation of the points that were "split" out
     1902        # of the original data set for one particular alpha
    19271903        elevation_predicted = \
    19281904                domains[alpha].quantities[attribute_smoothed].\
    19291905                        get_values(interpolation_points=points_geo)
    19301906
    1931         #add predicted elevation to array that starts with x, y, z...
     1907        # add predicted elevation to array that starts with x, y, z...
    19321908        data[:,i+3] = elevation_predicted
    19331909
  • branches/numpy/anuga/geospatial_data/test_geospatial_data.py

    r6153 r6304  
    11#!/usr/bin/env python
    2 
    32
    43import unittest
    54import os
     5import tempfile
    66from math import sqrt, pi
    7 import tempfile
    87from sets import ImmutableSet
    98
    10 import Numeric as num
     9import numpy as num
    1110
    1211from anuga.geospatial_data.geospatial_data import *
     
    1615from anuga.utilities.system_tools import get_host_name
    1716from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
     17from anuga.config import netcdf_float
     18
    1819
    1920class Test_Geospatial_data(unittest.TestCase):
     
    2425        pass
    2526
    26 
    2727    def test_0(self):
    2828        #Basic points
    2929        from anuga.coordinate_transforms.geo_reference import Geo_reference
    30        
     30
    3131        points = [[1.0, 2.1], [3.0, 5.3]]
    3232        G = Geospatial_data(points)
    33 
    3433        assert num.allclose(G.data_points, [[1.0, 2.1], [3.0, 5.3]])
    3534
     
    3837        rep = `G`
    3938        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)
    4240        assert rep == ref, msg
    4341
    4442        #Check getter
    4543        assert num.allclose(G.get_data_points(), [[1.0, 2.1], [3.0, 5.3]])
    46        
     44
    4745        #Check defaults
    4846        assert G.attributes is None
    49        
    5047        assert G.geo_reference.zone == Geo_reference().zone
    5148        assert G.geo_reference.xllcorner == Geo_reference().xllcorner
    5249        assert G.geo_reference.yllcorner == Geo_reference().yllcorner
    53        
    5450
    5551    def test_1(self):
    5652        points = [[1.0, 2.1], [3.0, 5.3]]
    5753        attributes = [2, 4]
    58         G = Geospatial_data(points, attributes)       
     54        G = Geospatial_data(points, attributes)
    5955        assert G.attributes.keys()[0] == DEFAULT_ATTRIBUTE
    6056        assert num.allclose(G.attributes.values()[0], [2, 4])
    61        
    6257
    6358    def test_2(self):
    6459        from anuga.coordinate_transforms.geo_reference import Geo_reference
     60
    6561        points = [[1.0, 2.1], [3.0, 5.3]]
    6662        attributes = [2, 4]
     
    7268        assert G.geo_reference.yllcorner == 200
    7369
    74 
    7570    def test_get_attributes_1(self):
    7671        from anuga.coordinate_transforms.geo_reference import Geo_reference
     72
    7773        points = [[1.0, 2.1], [3.0, 5.3]]
    7874        attributes = [2, 4]
     
    8076                            geo_reference=Geo_reference(56, 100, 200))
    8177
    82 
    8378        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]])
    8580
    8681        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]])
    8883
    8984        V = G.get_attributes() #Simply get them
     
    9590    def test_get_attributes_2(self):
    9691        #Multiple attributes
    97        
    98        
    9992        from anuga.coordinate_transforms.geo_reference import Geo_reference
     93
    10094        points = [[1.0, 2.1], [3.0, 5.3]]
    10195        attributes = {'a0': [0, 0], 'a1': [2, 4], 'a2': [79.4, -7]}
     
    10498                            default_attribute_name='a1')
    10599
    106 
    107100        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
    110103        V = G.get_attributes() #Get default attribute
    111104        assert num.allclose(V, [2, 4])
     
    125118            pass
    126119        else:
    127             raise 'Should have raised exception'
     120            raise Exception, 'Should have raised exception'
    128121
    129122    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]]
    131124        x_p = -10
    132125        y_p = -40
    133126        geo_ref = Geo_reference(56, x_p, y_p)
    134127        points_rel = geo_ref.change_points_geo_ref(points_ab)
    135        
     128
    136129        spatial = Geospatial_data(points_rel, geo_reference=geo_ref)
    137 
    138130        results = spatial.get_data_points(absolute=False)
    139        
    140131        assert num.allclose(results, points_rel)
    141        
     132
    142133        x_p = -1770
    143134        y_p = 4.01
    144135        geo_ref = Geo_reference(56, x_p, y_p)
    145136        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
    149139        assert num.allclose(results, points_rel)
    150140
    151  
    152141    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])
    165152        results = spatial.get_data_points(as_lat_long=True)
    166         #print "test_get_data_points_lat_long - results", results
    167         #print "points_Lat_long",points_Lat_long
    168153        assert num.allclose(results, points_Lat_long)
    169      
     154
    170155    def test_get_data_points_lat_longII(self):
    171156        # x,y  North,east long,lat
    172157        boundary_polygon = [[ 250000, 7630000]]
    173158        zone = 50
    174        
     159
    175160        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)
    177162        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)
    182180        assert num.allclose(seg_lat_long[0][0], lat_result)#lat
    183181        assert num.allclose(seg_lat_long[0][1], long_result)#long
    184182
    185 
    186     def test_get_data_points_lat_longIII(self):
    187         # x,y  North,east long,lat
    188         #for northern hemisphere
    189         boundary_polygon = [[419944.8, 918642.4]]
    190         zone = 47
    191        
    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_result
    203         assert num.allclose(seg_lat_long[0][0], lat_result)#lat
    204         assert num.allclose(seg_lat_long[0][1], long_result)#long
    205 
    206 
    207              
    208183    def test_set_geo_reference(self):
    209         """test_set_georeference
    210        
    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
    212187        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]]
    216191        x_p = -10
    217192        y_p = -40
    218193        geo_ref = Geo_reference(56, x_p, y_p)
    219194        points_rel = geo_ref.change_points_geo_ref(points_ab)
    220        
     195
    221196        # Create without geo_ref properly set
    222         G = Geospatial_data(points_rel)       
     197        G = Geospatial_data(points_rel)
    223198        assert not num.allclose(points_ab, G.get_data_points(absolute=True))
    224        
     199
    225200        # Create the way it should be
    226201        G = Geospatial_data(points_rel, geo_reference=geo_ref)
    227202        assert num.allclose(points_ab, G.get_data_points(absolute=True))
    228        
     203
    229204        # Change georeference and check that absolute values are unchanged.
    230205        x_p = 10
     
    232207        new_geo_ref = Geo_reference(56, x_p, y_p)
    233208        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
    239213    def test_conversions_to_points_dict(self):
    240214        #test conversions to points_dict
    241        
    242        
    243215        from anuga.coordinate_transforms.geo_reference import Geo_reference
     216
    244217        points = [[1.0, 2.1], [3.0, 5.3]]
    245218        attributes = {'a0': [0, 0], 'a1': [2, 4], 'a2': [79.4, -7]}
     
    248221                            default_attribute_name='a1')
    249222
    250 
    251223        points_dict = geospatial_data2points_dictionary(G)
    252224
    253225        assert points_dict.has_key('pointlist')
    254         assert points_dict.has_key('attributelist')       
     226        assert points_dict.has_key('attributelist')
    255227        assert points_dict.has_key('geo_reference')
    256228
     
    260232        assert A.has_key('a0')
    261233        assert A.has_key('a1')
    262         assert A.has_key('a2')       
     234        assert A.has_key('a2')
    263235
    264236        assert num.allclose( A['a0'], [0, 0] )
    265         assert num.allclose( A['a1'], [2, 4] )       
     237        assert num.allclose( A['a1'], [2, 4] )
    266238        assert num.allclose( A['a2'], [79.4, -7] )
    267 
    268239
    269240        geo = points_dict['geo_reference']
    270241        assert geo is G.geo_reference
    271242
    272 
    273243    def test_conversions_from_points_dict(self):
    274         """test conversions from points_dict
    275         """
     244        '''test conversions from points_dict'''
    276245
    277246        from anuga.coordinate_transforms.geo_reference import Geo_reference
    278        
     247
    279248        points = [[1.0, 2.1], [3.0, 5.3]]
    280249        attributes = {'a0': [0, 0], 'a1': [2, 4], 'a2': [79.4, -7]}
     
    284253        points_dict['attributelist'] = attributes
    285254        points_dict['geo_reference'] = Geo_reference(56, 100, 200)
    286        
    287255
    288256        G = points_dictionary2geospatial_data(points_dict)
    289 
    290257        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]])
    295259
    296260        V = G.get_attributes('a0') #Get by name
     
    304268
    305269    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
    309274        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
    318280        G = G1 + G2
    319281
     
    326288
    327289    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
    331294        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
    335298        points = [[5.0, 2.1], [3.0, 50.3]]
    336         attributes = {'depth':[200, 400]}
     299        attributes = {'depth': [200, 400]}
    337300        G2 = Geospatial_data(points, attributes)
    338        
    339 #        g3 = geospatial_data2points_dictionary(G1)
    340 #        print 'g3=', g3
    341        
     301
    342302        G = G1 + G2
    343303
    344         assert G.attributes.has_key('depth') 
     304        assert G.attributes.has_key('depth')
    345305        assert G.attributes.keys(), ['depth']
    346306        assert num.allclose(G.attributes['depth'], [2, 4, 200, 400])
    347307        assert num.allclose(G.get_data_points(), [[1.0, 2.1], [3.0, 5.3],
    348308                                                  [5.0, 2.1], [3.0, 50.3]])
     309
    349310    def test_add_with_geo (self):
    350         """
    351         Difference in Geo_reference resolved
    352         """
     311        '''Difference in Geo_reference resolved'''
     312
    353313        points1 = [[1.0, 2.1], [3.0, 5.3]]
    354314        points2 = [[5.0, 6.1], [6.0, 3.3]]
     
    362322                                 projection='UTM',
    363323                                 units='m')
    364                                
     324
    365325        G1 = Geospatial_data(points1, attributes1, geo_ref1)
    366326        G2 = Geospatial_data(points2, attributes2, geo_ref2)
     
    371331
    372332        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
    375335        G = G1 + G2
    376336
     
    381341        P = G.get_data_points(absolute=True)
    382342
    383         #P_relative = G.get_data_points(absolute=False)
    384         #
    385         #assert allclose(P_relative, P - [0.1, 2.0])
    386 
    387343        assert num.allclose(P, num.concatenate( (P1,P2) ))
     344        msg = 'P=%s' % str(P)
    388345        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
    394347
    395348    def test_add_with_geo_absolute (self):
    396         """
    397         Difference in Geo_reference resolved
    398         """
     349        '''Difference in Geo_reference resolved'''
     350
    399351        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]])
    401353        attributes1 = [2, 4]
    402354        attributes2 = [5, 76]
     
    404356        geo_ref2 = Geo_reference(55, 2.0, 3.0)
    405357
    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()],
    409360                             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()],
    412364                             attributes2, geo_ref2)
    413365
     
    417369
    418370        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
    420377
    421378        P2 = G2.get_data_points(absolute=True)
     
    423380
    424381        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
    427385        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 
    432386        P = G.get_data_points(absolute=True)
    433387
    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)))
    440389
    441390    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
    445393        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]])
    447395
    448396        geo_ref1= Geo_reference(55, 1.0, 2.0)
     
    453401                                 projection='UTM',
    454402                                 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]}
    460406
    461407        G1 = Geospatial_data(points1, attributes1, geo_ref1)
     
    465411        assert G1.attributes.has_key('elevation')
    466412        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
    469415        G2 = Geospatial_data(points2, attributes2, geo_ref2)
    470416        assert num.allclose(G2.get_geo_reference().get_xllcorner(), 0.1)
     
    473419        assert G2.attributes.has_key('elevation')
    474420        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])
    476422
    477423        #Check that absolute values are as expected
     
    480426
    481427        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]])
    483429
    484430        # Normal add
    485431        G = G1 + None
    486 
    487432        assert G.attributes.has_key('depth')
    488433        assert G.attributes.has_key('elevation')
    489434        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])
    491436
    492437        # Points are now absolute.
    493438        assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0)
    494439        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
    498443
    499444        G = G2 + None
     
    501446        assert G.attributes.has_key('elevation')
    502447        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])
    505449        assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0)
    506450        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)
    508453        assert num.allclose(P, [[5.2, 12.1], [6.2, 9.3]])
    509        
    510 
    511454
    512455        # Reverse add
    513456        G = None + G1
    514 
    515457        assert G.attributes.has_key('depth')
    516458        assert G.attributes.has_key('elevation')
    517459        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])
    519461
    520462        # Points are now absolute.
    521463        assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0)
    522464        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]])
    526468
    527469        G = None + G2
     
    529471        assert G.attributes.has_key('elevation')
    530472        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])
    532474
    533475        assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0)
    534476        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)
    536479        assert num.allclose(P, [[5.2, 12.1], [6.2, 9.3]])
    537480
    538        
    539 
    540        
    541                            
    542        
    543481    def test_clip0(self):
    544         """test_clip0(self):
    545        
     482        '''test_clip0(self):
     483
    546484        Test that point sets can be clipped by a polygon
    547         """
    548        
     485        '''
     486
    549487        from anuga.coordinate_transforms.geo_reference import Geo_reference
    550        
     488
    551489        points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3],
    552490                  [0, 0], [2.4, 3.3]]
    553491        G = Geospatial_data(points)
    554492
    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]])
    558497
    559498        # Then a more complex polygon
    560499        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]]
    562502        G = Geospatial_data(points)
    563503
    564504        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]])
    566506
    567507    def test_clip0_with_attributes(self):
    568         """test_clip0_with_attributes(self):
    569        
     508        '''test_clip0_with_attributes(self):
     509
    570510        Test that point sets with attributes can be clipped by a polygon
    571         """
    572        
     511        '''
     512
    573513        from anuga.coordinate_transforms.geo_reference import Geo_reference
    574        
     514
    575515        points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3],
    576516                  [0, 0], [2.4, 3.3]]
     
    579519        att_dict = {'att1': attributes,
    580520                    'att2': num.array(attributes)+1}
    581        
     521
    582522        G = Geospatial_data(points, att_dict)
    583523
    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]])
    587528        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])
    589530
    590531        # Then a more complex polygon
    591532        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]]
    593535
    594536        # This time just one attribute
    595537        attributes = [2, -4, 5, 76, -2, 0.1]
    596538        G = Geospatial_data(points, attributes)
    597 
    598539        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]])
    600541        assert num.allclose(G.clip(polygon).get_attributes(), [-4, 5, 76])
    601        
    602542
    603543    def test_clip1(self):
    604         """test_clip1(self):
    605        
     544        '''test_clip1(self):
     545
    606546        Test that point sets can be clipped by a polygon given as
    607547        another Geospatial dataset
    608         """
    609        
     548        '''
     549
    610550        from anuga.coordinate_transforms.geo_reference import Geo_reference
    611        
     551
    612552        points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3],
    613553                  [0, 0], [2.4, 3.3]]
     
    616556                    'att2': num.array(attributes)+1}
    617557        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]])
    621561        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]])
    624563        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
    627566        # 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]
    630570        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]])
    633573
    634574        assert num.allclose(G.clip(polygon).get_data_points(),
    635575                            [[0.5, 0.5], [1, -0.5], [1.5, 0]])
    636576        assert num.allclose(G.clip(polygon).get_attributes(), [-4, 5, 76])
    637        
    638577
    639578    def test_clip0_outside(self):
    640         """test_clip0_outside(self):
    641        
     579        '''test_clip0_outside(self):
     580
    642581        Test that point sets can be clipped outside of a polygon
    643         """
    644        
     582        '''
     583
    645584        from anuga.coordinate_transforms.geo_reference import Geo_reference
    646        
     585
    647586        points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3],
    648587                  [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]
    650589        G = Geospatial_data(points, attributes)
    651590
    652         # First try the unit square   
     591        # First try the unit square
    653592        U = [[0,0], [1,0], [1,1], [0,1]]
    654593        assert num.allclose(G.clip_outside(U).get_data_points(),
    655594                            [[-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])
    659596
    660597        # Then a more complex polygon
    661598        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]
    664602        G = Geospatial_data(points, attributes)
    665 
    666603        assert num.allclose(G.clip_outside(polygon).get_data_points(),
    667604                            [[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])
    670607
    671608    def test_clip1_outside(self):
    672         """test_clip1_outside(self):
    673        
     609        '''test_clip1_outside(self):
     610
    674611        Test that point sets can be clipped outside of a polygon given as
    675612        another Geospatial dataset
    676         """
    677        
     613        '''
     614
    678615        from anuga.coordinate_transforms.geo_reference import Geo_reference
    679        
     616
    680617        points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3],
    681618                  [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]])
    687624        assert num.allclose(G.clip_outside(U).get_data_points(),
    688625                            [[-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])
    690627
    691628        # 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]
    694632        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]])
    699635        assert num.allclose(G.clip_outside(polygon).get_data_points(),
    700636                            [[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])
    704639
    705640    def test_clip1_inside_outside(self):
    706         """test_clip1_inside_outside(self):
    707        
     641        '''test_clip1_inside_outside(self):
     642
    708643        Test that point sets can be clipped outside of a polygon given as
    709644        another Geospatial dataset
    710         """
    711        
     645        '''
     646
    712647        from anuga.coordinate_transforms.geo_reference import Geo_reference
    713        
     648
    714649        points = [[-1, 4], [0.2, 0.5], [1.0, 2.1], [0.4, 0.3], [3.0, 5.3],
    715650                  [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]
    717652        G = Geospatial_data(points, attributes)
    718653
    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]])
    721656        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]])
    723659        assert num.allclose(G.clip(U).get_attributes(), [-4, 76, 0.1])
    724        
    725660        G2 = G.clip_outside(U)
    726661        assert num.allclose(G2.get_data_points(),[[-1, 4], [1.0, 2.1],
    727662                                                  [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
    731665        # 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
    737670        assert num.allclose((G1+G2).get_data_points(), new_points)
    738671        assert num.allclose((G1+G2).get_attributes(), new_attributes)
     
    742675        G.export_points_file(FN)
    743676
    744 
    745677        # Read it back in
    746678        G3 = Geospatial_data(FN)
    747679
    748 
    749680        # 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
    753684        os.remove(FN)
    754685
    755        
    756686    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\
    7646901.0 0.0 10.0 0.0\n\
    7656910.0 1.0 0.0 10.0\n\
    766 1.0 0.0 10.4 40.0\n")
     6921.0 0.0 10.4 40.0\n')
    767693        file.close()
    768         #print fileName
     694
    769695        results = Geospatial_data(fileName)
    770696        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]])
    774699        assert num.allclose(results.get_attributes(attribute_name='elevation'),
    775700                            [10.0, 0.0, 10.4])
     
    777702                            [0.0, 10.0, 40.0])
    778703
    779 
    780   ###################### .CSV ##############################
     704################################################################################
     705# Test CSV files
     706################################################################################
    781707
    782708    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):
    785710        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\
    790716-25.0,180.0,452.688000\n\
    791 -34,150.0,459.126000\n")
     717-34,150.0,459.126000\n')
    792718        file.close()
    793        
     719
    794720        results = Geospatial_data(fileName, max_read_lines=1,
    795721                                  load_file_now=False)
    796        
    797         #for i in results:
    798         #    pass
     722
    799723        try:
    800724            for i in results:
     
    804728        else:
    805729            msg = 'Different zones in Geo references not caught.'
    806             raise msg       
    807        
    808         os.remove(fileName)
    809        
     730            raise Exception, msg
     731
     732        os.remove(fileName)
     733
    810734    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\
     7381.0, 0.0, 10.0, 0.0\n\
     7390.0, 1.0, 0.0, 10.0\n\
     7401.0, 0.0 ,10.4, 40.0\n')
    818741        file.close()
    819742
    820743        results = Geospatial_data(fileName, max_read_lines=2)
    821744
    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])
    826751
    827752        # Blocking
     
    829754        for i in results:
    830755            geo_list.append(i)
    831            
     756
    832757        assert num.allclose(geo_list[0].get_data_points(),
    833758                            [[1.0, 0.0],[0.0, 1.0]])
    834 
    835759        assert num.allclose(geo_list[0].get_attributes(attribute_name='elevation'),
    836760                            [10.0, 0.0])
    837761        assert num.allclose(geo_list[1].get_data_points(),
    838                             [[1.0, 0.0]])       
     762                            [[1.0, 0.0]])
    839763        assert num.allclose(geo_list[1].get_attributes(attribute_name='elevation'),
    840764                            [10.4])
    841            
    842         os.remove(fileName)         
    843        
     765
     766        os.remove(fileName)
     767
    844768    def test_load_csv_bad(self):
    845         """ test_load_csv_bad(self):
     769        '''test_load_csv_bad(self):
    846770        header column, body column missmatch
    847771        (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\
     7771.0, 0.0, 10.0, 0.0\n\
     7780.0, 1.0, 0.0, 10.0\n\
     7791.0, 0.0 ,10.4, 40.0\n')
    857780        file.close()
    858781
     
    862785        # Blocking
    863786        geo_list = []
    864         #for i in results:
    865         #    geo_list.append(i)
    866787        try:
    867788            for i in results:
     
    870791            pass
    871792        else:
    872             msg = 'bad file did not raise error!'
    873             raise msg
     793            msg = 'Bad file did not raise error!'
     794            raise Exception, msg
    874795        os.remove(fileName)
    875796
    876797    def test_load_csv_badII(self):
    877         """ test_load_csv_bad(self):
     798        '''test_load_csv_bad(self):
    878799        header column, body column missmatch
    879800        (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\
    8868061.0, 0.0, 10.0, 0.0\n\
    8878070.0, 1.0, 0.0, 10\n\
    888 1.0, 0.0 ,10.4 yeah\n")
     8081.0, 0.0 ,10.4 yeah\n')
    889809        file.close()
    890810
     
    894814        # Blocking
    895815        geo_list = []
    896         #for i in results:
    897         #    geo_list.append(i)
    898816        try:
    899817            for i in results:
     
    902820            pass
    903821        else:
    904             msg = 'bad file did not raise error!'
    905             raise msg
     822            msg = 'Bad file did not raise error!'
     823            raise Exception, msg
    906824        os.remove(fileName)
    907825
    908826    def test_load_csv_badIII(self):
    909         """ test_load_csv_bad(self):
     827        '''test_load_csv_bad(self):
    910828        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\
    9178341. 0.0 10.0 0.0\n\
    9188350.0 1.0 0.0 10.0\n\
    919 1.0 0.0 10.4 40.0\n")
     8361.0 0.0 10.4 40.0\n')
    920837        file.close()
    921838
     
    926843            pass
    927844        else:
    928             msg = 'bad file did not raise error!'
    929             raise msg
    930         os.remove(fileName)
    931        
     845            msg = 'Bad file did not raise error!'
     846            raise Exception, msg
     847        os.remove(fileName)
     848
    932849    def test_load_csv_badIV(self):
    933         """ test_load_csv_bad(self):
     850        ''' test_load_csv_bad(self):
    934851        header column, body column missmatch
    935852        (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\
    9428581.0, 0.0, 10.0, wow\n\
    9438590.0, 1.0, 0.0, ha\n\
    944 1.0, 0.0 ,10.4, yeah\n")
     8601.0, 0.0 ,10.4, yeah\n')
    945861        file.close()
    946862
     
    950866        # Blocking
    951867        geo_list = []
    952         #for i in results:
    953          #   geo_list.append(i)
    954868        try:
    955869            for i in results:
     
    958872            pass
    959873        else:
    960             msg = 'bad file did not raise error!'
    961             raise msg
     874            msg = 'Bad file did not raise error!'
     875            raise Exception, msg
    962876        os.remove(fileName)
    963877
    964878    def test_load_pts_blocking(self):
    965879        #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\
     8831.0, 0.0, 10.0, 0.0\n\
     8840.0, 1.0, 0.0, 10.0\n\
     8851.0, 0.0 ,10.4, 40.0\n')
    975886        file.close()
    976887
    977         pts_file = tempfile.mktemp(".pts")
    978        
     888        pts_file = tempfile.mktemp('.pts')
     889
    979890        convert = Geospatial_data(fileName)
    980891        convert.export_points_file(pts_file)
    981892        results = Geospatial_data(pts_file, max_read_lines=2)
    982893
    983         assert num.allclose(results.get_data_points(), [[1.0, 0.0],[0.0, 1.0],
    984                                                         [1.0, 0.0]])
     894        assert num.allclose(results.get_data_points(),
     895                            [[1.0, 0.0],[0.0, 1.0], [1.0, 0.0]])
    985896        assert num.allclose(results.get_attributes(attribute_name='elevation'),
    986897                            [10.0, 0.0, 10.4])
     
    991902        geo_list = []
    992903        for i in results:
    993             geo_list.append(i) 
     904            geo_list.append(i)
    994905        assert num.allclose(geo_list[0].get_data_points(),
    995906                            [[1.0, 0.0],[0.0, 1.0]])
     
    997908                            [10.0, 0.0])
    998909        assert num.allclose(geo_list[1].get_data_points(),
    999                             [[1.0, 0.0]])       
     910                            [[1.0, 0.0]])
    1000911        assert num.allclose(geo_list[1].get_attributes(attribute_name='elevation'),
    1001912                            [10.4])
    1002            
    1003         os.remove(fileName) 
    1004         os.remove(pts_file)               
     913
     914        os.remove(fileName)
     915        os.remove(pts_file)
    1005916
    1006917    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\
     9211.0, 0.0, 10.0, 0.0\n\
     9220.0, 1.0, 0.0, 10.0\n\
     9231.0, 0.0, 10.0, 0.0\n\
     9240.0, 1.0, 0.0, 10.0\n\
     9251.0, 0.0, 10.0, 0.0\n\
     9260.0, 1.0, 0.0, 10.0\n\
     9271.0, 0.0, 10.0, 0.0\n\
     9280.0, 1.0, 0.0, 10.0\n\
     9291.0, 0.0, 10.0, 0.0\n\
     9300.0, 1.0, 0.0, 10.0\n\
     9311.0, 0.0, 10.0, 0.0\n\
     9320.0, 1.0, 0.0, 10.0\n\
     9331.0, 0.0, 10.0, 0.0\n\
     9340.0, 1.0, 0.0, 10.0\n\
     9351.0, 0.0, 10.0, 0.0\n\
     9360.0, 1.0, 0.0, 10.0\n\
     9371.0, 0.0, 10.0, 0.0\n\
     9380.0, 1.0, 0.0, 10.0\n\
     9391.0, 0.0, 10.0, 0.0\n\
     9400.0, 1.0, 0.0, 10.0\n\
     9411.0, 0.0, 10.0, 0.0\n\
     9420.0, 1.0, 0.0, 10.0\n\
     9431.0, 0.0, 10.0, 0.0\n\
     9440.0, 1.0, 0.0, 10.0\n\
     9451.0, 0.0, 10.0, 0.0\n\
     9460.0, 1.0, 0.0, 10.0\n\
     9471.0, 0.0, 10.0, 0.0\n\
     9480.0, 1.0, 0.0, 10.0\n\
     9491.0, 0.0, 10.0, 0.0\n\
     9500.0, 1.0, 0.0, 10.0\n\
     9511.0, 0.0, 10.0, 0.0\n\
     9520.0, 1.0, 0.0, 10.0\n\
     9531.0, 0.0, 10.0, 0.0\n\
     9540.0, 1.0, 0.0, 10.0\n\
     9551.0, 0.0, 10.0, 0.0\n\
     9560.0, 1.0, 0.0, 10.0\n\
     9571.0, 0.0, 10.0, 0.0\n\
     9580.0, 1.0, 0.0, 10.0\n\
     9591.0, 0.0, 10.0, 0.0\n\
     9600.0, 1.0, 0.0, 10.0\n\
     9611.0, 0.0, 10.0, 0.0\n\
     9620.0, 1.0, 0.0, 10.0\n\
     9631.0, 0.0, 10.0, 0.0\n\
     9640.0, 1.0, 0.0, 10.0\n\
     9651.0, 0.0, 10.0, 0.0\n\
     9660.0, 1.0, 0.0, 10.0\n\
     9671.0, 0.0 ,10.4, 40.0\n')
    1060968        file.close()
    1061969
    1062         pts_file = tempfile.mktemp(".pts")
    1063        
     970        pts_file = tempfile.mktemp('.pts')
    1064971        convert = Geospatial_data(fileName)
    1065972        convert.export_points_file(pts_file)
     
    1069976        geo_list = []
    1070977        for i in results:
    1071             geo_list.append(i) 
     978            geo_list.append(i)
    1072979        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]])
    1074981        assert num.allclose(geo_list[0].get_attributes(attribute_name='elevation'),
    1075982                            [10.0, 0.0])
    1076983        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] ])
    1078985        assert num.allclose(geo_list[1].get_attributes(attribute_name='elevation'),
    1079986                            [10.0, 0.0])
    1080            
    1081         os.remove(fileName) 
     987
     988        os.remove(fileName)
    1082989        os.remove(pts_file)
    1083        
    1084        
    1085990
    1086991    def test_new_export_pts_file(self):
     
    1089994        att_dict['elevation'] = num.array([10.1, 0.0, 10.4])
    1090995        att_dict['brightness'] = num.array([10.0, 1.0, 10.4])
    1091        
    1092         fileName = tempfile.mktemp(".pts")
    1093        
     996
     997        fileName = tempfile.mktemp('.pts')
    1094998        G = Geospatial_data(pointlist, att_dict)
    1095        
    1096999        G.export_points_file(fileName)
    1097 
    10981000        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])
    11041007        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)
    11061010
    11071011    def test_new_export_absolute_pts_file(self):
    11081012        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]])
    11101014        att_dict['elevation'] = num.array([10.1, 0.0, 10.4])
    11111015        att_dict['brightness'] = num.array([10.0, 1.0, 10.4])
    11121016        geo_ref = Geo_reference(50, 25, 55)
    1113        
    1114         fileName = tempfile.mktemp(".pts")
    1115        
     1017
     1018        fileName = tempfile.mktemp('.pts')
    11161019        G = Geospatial_data(pointlist, att_dict, geo_ref)
    1117        
    11181020        G.export_points_file(fileName, absolute=True)
    1119 
    11201021        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
    11261032        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
    11281039
    11291040    def test_loadpts(self):
    1130        
    11311041        from Scientific.IO.NetCDF import NetCDFFile
    11321042
    1133         fileName = tempfile.mktemp(".pts")
     1043        fileName = tempfile.mktemp('.pts')
    11341044        # NetCDF file definition
    11351045        outfile = NetCDFFile(fileName, netcdf_mode_w)
    1136        
     1046
    11371047        # dimension definitions
    1138         outfile.createDimension('number_of_points', 3)   
    1139         outfile.createDimension('number_of_dimensions', 2) #This is 2d data
    1140    
     1048        outfile.createDimension('number_of_points', 3)
     1049        outfile.createDimension('number_of_dimensions', 2) # This is 2d data
     1050
    11411051        # variable definitions
    1142         outfile.createVariable('points', num.Float, ('number_of_points',
    1143                                                      'number_of_dimensions'))
    1144         outfile.createVariable('elevation', num.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
    11461056        # Get handles to the variables
    11471057        points = outfile.variables['points']
    11481058        elevation = outfile.variables['elevation']
    1149  
     1059
    11501060        points[0, :] = [1.0,0.0]
    1151         elevation[0] = 10.0 
     1061        elevation[0] = 10.0
    11521062        points[1, :] = [0.0,1.0]
    1153         elevation[1] = 0.0 
     1063        elevation[1] = 0.0
    11541064        points[2, :] = [1.0,0.0]
    1155         elevation[2] = 10.4   
     1065        elevation[2] = 10.4
    11561066
    11571067        outfile.close()
    1158        
     1068
    11591069        results = Geospatial_data(file_name = fileName)
    11601070        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
    11651078    def test_writepts(self):
    1166         #test_writepts: Test that storage of x,y,attributes works
    1167        
     1079        '''Test that storage of x,y,attributes works'''
     1080
    11681081        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]])
    11701083        att_dict['elevation'] = num.array([10.0, 0.0, 10.4])
    11711084        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)
    11731086
    11741087        # Test pts format
    1175         fileName = tempfile.mktemp(".pts")
     1088        fileName = tempfile.mktemp('.pts')
    11761089        G = Geospatial_data(pointlist, att_dict, geo_reference)
    11771090        G.export_points_file(fileName, False)
     
    11791092        os.remove(fileName)
    11801093
    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])
    11831098        answer = [10.0, 0.0, 10.4]
    11841099        assert num.allclose(results.get_attributes('brightness'), answer)
    11851100        self.failUnless(geo_reference == geo_reference,
    1186                          'test_writepts failed. Test geo_reference')
     1101                        'test_writepts failed. Test geo_reference')
    11871102
    11881103    def test_write_csv_attributes(self):
    1189         #test_write : Test that storage of x,y,attributes works
    1190        
     1104        '''Test that storage of x,y,attributes works'''
     1105
    11911106        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]])
    11931108        att_dict['elevation'] = num.array([10.0, 0.0, 10.4])
    11941109        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
    11961112        # Test txt format
    1197         fileName = tempfile.mktemp(".txt")
     1113        fileName = tempfile.mktemp('.txt')
    11981114        G = Geospatial_data(pointlist, att_dict, geo_reference)
    11991115        G.export_points_file(fileName)
    1200         #print "fileName", fileName
    12011116        results = Geospatial_data(file_name=fileName)
    12021117        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])
    12051123        answer = [10.0, 0.0, 10.4]
    12061124        assert num.allclose(results.get_attributes('brightness'), answer)
    1207        
    1208  
     1125
    12091126    def test_write_csv_attributes_lat_long(self):
    1210         #test_write : Test that storage of x,y,attributes works
    1211        
     1127        '''Test that storage of x,y,attributes works'''
     1128
    12121129        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]])
    12141131        att_dict['elevation'] = num.array([10.0, 0.0, 10.4])
    12151132        att_dict['brightness'] = num.array([10.0, 0.0, 10.4])
     1133
    12161134        # Test txt format
    1217         fileName = tempfile.mktemp(".txt")
     1135        fileName = tempfile.mktemp('.txt')
    12181136        G = Geospatial_data(pointlist, att_dict, points_are_lats_longs=True)
    12191137        G.export_points_file(fileName, as_lat_long=True)
    1220         #print "fileName", fileName
    12211138        results = Geospatial_data(file_name=fileName)
    12221139        os.remove(fileName)
     1140
    12231141        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])
    12261145        answer = [10.0, 0.0, 10.4]
    12271146        assert num.allclose(results.get_attributes('brightness'), answer)
    1228        
     1147
    12291148    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
    12331151        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)
    12361154
    12371155        # Test pts format
    1238         fileName = tempfile.mktemp(".pts")
     1156        fileName = tempfile.mktemp('.pts')
    12391157        G = Geospatial_data(pointlist, None, geo_reference)
    12401158        G.export_points_file(fileName, False)
     
    12421160        os.remove(fileName)
    12431161
    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]])
    12451164        self.failUnless(geo_reference == geo_reference,
    1246                          'test_writepts failed. Test geo_reference')
    1247        
    1248        
     1165                        'test_writepts failed. Test geo_reference')
     1166
    12491167    def test_write_csv_no_attributes(self):
    1250         #test_write txt _no_attributes: Test that storage of x,y alone works
    1251        
     1168        '''Test that storage of x,y alone works'''
     1169
    12521170        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]])
    12541172        geo_reference=Geo_reference(56,0,0)
     1173
    12551174        # Test format
    1256         fileName = tempfile.mktemp(".txt")
     1175        fileName = tempfile.mktemp('.txt')
    12571176        G = Geospatial_data(pointlist, None, geo_reference)
    12581177        G.export_points_file(fileName)
    12591178        results = Geospatial_data(file_name=fileName)
    12601179        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################################################################################
    12661187
    12671188    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')
    12731190        try:
    1274             results = Geospatial_data(file_name = fileName)
    1275 #            dict = import_points_file(fileName)
     1191            results = Geospatial_data(file_name=fileName)
    12761192        except IOError:
    12771193            pass
    12781194        else:
    12791195            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
    12841197
    12851198    def test_create_from_pts_file(self):
    1286        
    12871199        from Scientific.IO.NetCDF import NetCDFFile
    12881200
    1289 #        fileName = tempfile.mktemp(".pts")
     1201        # NetCDF file definition
    12901202        FN = 'test_points.pts'
    1291         # NetCDF file definition
    12921203        outfile = NetCDFFile(FN, netcdf_mode_w)
    1293        
     1204
    12941205        # dimension definitions
    1295         outfile.createDimension('number_of_points', 3)   
    1296         outfile.createDimension('number_of_dimensions', 2) #This is 2d data
    1297    
     1206        outfile.createDimension('number_of_points', 3)
     1207        outfile.createDimension('number_of_dimensions', 2) # This is 2d data
     1208
    12981209        # variable definitions
    1299         outfile.createVariable('points', num.Float, ('number_of_points',
    1300                                                      'number_of_dimensions'))
    1301         outfile.createVariable('elevation', num.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
    13031214        # Get handles to the variables
    13041215        points = outfile.variables['points']
    13051216        elevation = outfile.variables['elevation']
    1306  
     1217
    13071218        points[0, :] = [1.0,0.0]
    1308         elevation[0] = 10.0 
     1219        elevation[0] = 10.0
    13091220        points[1, :] = [0.0,1.0]
    1310         elevation[1] = 0.0 
     1221        elevation[1] = 0.0
    13111222        points[2, :] = [1.0,0.0]
    1312         elevation[2] = 10.4   
     1223        elevation[2] = 10.4
    13131224
    13141225        outfile.close()
     
    13181229        assert num.allclose(G.get_geo_reference().get_xllcorner(), 0.0)
    13191230        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]])
    13221233        assert num.allclose(G.get_attributes(), [10.0, 0.0, 10.4])
    13231234        os.remove(FN)
    13241235
    13251236    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
    13291239        from Scientific.IO.NetCDF import NetCDFFile
    13301240
     1241        # NetCDF file definition
    13311242        FN = 'test_points.pts'
    1332         # NetCDF file definition
    13331243        outfile = NetCDFFile(FN, netcdf_mode_w)
    13341244
     
    13401250
    13411251        # dimension definitions
    1342         outfile.createDimension('number_of_points', 3)   
    1343         outfile.createDimension('number_of_dimensions', 2) #This is 2d data
    1344    
     1252        outfile.createDimension('number_of_points', 3)
     1253        outfile.createDimension('number_of_dimensions', 2) # This is 2d data
     1254
    13451255        # variable definitions
    1346         outfile.createVariable('points', num.Float, ('number_of_points',
    1347                                                      'number_of_dimensions'))
    1348         outfile.createVariable('elevation', num.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
    13501260        # Get handles to the variables
    13511261        points = outfile.variables['points']
     
    13531263
    13541264        points[0, :] = [1.0,0.0]
    1355         elevation[0] = 10.0 
     1265        elevation[0] = 10.0
    13561266        points[1, :] = [0.0,1.0]
    1357         elevation[1] = 0.0 
     1267        elevation[1] = 0.0
    13581268        points[2, :] = [1.0,0.0]
    1359         elevation[2] = 10.4   
     1269        elevation[2] = 10.4
    13601270
    13611271        outfile.close()
     
    13651275        assert num.allclose(G.get_geo_reference().get_xllcorner(), xll)
    13661276        assert num.allclose(G.get_geo_reference().get_yllcorner(), yll)
    1367 
    13681277        assert num.allclose(G.get_data_points(), [[1.0+xll, 0.0+yll],
    13691278                                                  [0.0+xll, 1.0+yll],
    13701279                                                  [1.0+xll, 0.0+yll]])
    1371        
    13721280        assert num.allclose(G.get_attributes(), [10.0, 0.0, 10.4])
     1281
    13731282        os.remove(FN)
    13741283
    1375        
    13761284    def test_add_(self):
    13771285        '''test_add_(self):
    13781286        adds an txt and pts files, reads the files and adds them
    1379            checking results are correct
     1287        checking results are correct
    13801288        '''
     1289
    13811290        # create files
    13821291        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]])
    13841293        att_dict1['elevation'] = num.array([-10.0, 0.0, 10.4])
    13851294        att_dict1['brightness'] = num.array([10.0, 0.0, 10.4])
    13861295        geo_reference1 = Geo_reference(56, 2.0, 1.0)
    1387        
     1296
    13881297        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]])
    13901299        att_dict2['elevation'] = num.array([1.0, 15.0, 1.4])
    13911300        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)
    13931302
    13941303        G1 = Geospatial_data(pointlist1, att_dict1, geo_reference1)
    13951304        G2 = Geospatial_data(pointlist2, att_dict2, geo_reference2)
    1396        
    1397         fileName1 = tempfile.mktemp(".txt")
    1398         fileName2 = tempfile.mktemp(".pts")
    1399 
    1400         #makes files
     1305
     1306        fileName1 = tempfile.mktemp('.txt')
     1307        fileName2 = tempfile.mktemp('.pts')
     1308
     1309        # makes files
    14011310        G1.export_points_file(fileName1)
    14021311        G2.export_points_file(fileName2)
    1403        
     1312
    14041313        # 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)
    14091316        G = G3 + G4
    14101317
    1411        
    14121318        #read results
    1413 #        print'res', G.get_data_points()
    1414 #        print'res1', G.get_data_points(False)
    14151319        assert num.allclose(G.get_data_points(),
    14161320                            [[ 3.0, 1.0], [ 2.0, 2.0],
    14171321                             [ 3.0, 1.0], [ 3.0, 3.0],
    14181322                             [ 2.0, 4.0], [ 3.0, 3.0]])
    1419                          
    14201323        assert num.allclose(G.get_attributes(attribute_name='elevation'),
    14211324                            [-10.0, 0.0, 10.4, 1.0, 15.0, 1.4])
    1422        
    14231325        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)
    14261328        self.failUnless(G.get_geo_reference() == geo_reference1,
    1427                          'test_writepts failed. Test geo_reference')
    1428                          
     1329                        'test_writepts failed. Test geo_reference')
     1330
    14291331        os.remove(fileName1)
    14301332        os.remove(fileName2)
    1431        
     1333
    14321334    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]]
    14361338        new_points = ensure_absolute(points)
    1437        
     1339
    14381340        assert num.allclose(new_points, points)
    14391341
    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]])
    14431345        new_points = ensure_absolute(points)
    1444        
     1346
    14451347        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, northing
    1452 
    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
    14541356        #Shift datapoints according to new origins
    14551357        for k in range(len(ab_points)):
    14561358            data_points[k][0] = ab_points[k][0] - mesh_origin[1]
    14571359            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
    14641362        assert num.allclose(new_points, ab_points)
    14651363
    14661364        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
    14741368        assert num.allclose(new_points, ab_points)
    1475 
    14761369
    14771370        geo_reference = Geo_reference(56, 100, 200)
     
    14791372        points = geo_reference.change_points_geo_ref(ab_points)
    14801373        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)
    14851375        new_points = ensure_absolute(G)
    1486         #print "new_points",new_points
    1487         #print "ab_points",ab_points
    1488            
     1376
    14891377        assert num.allclose(new_points, ab_points)
    14901378
    1491 
    1492        
    14931379    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]]
    14971383        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]])
    15041389        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
    15081392        ab_points = num.array([[2.0, 0.0],[1.0, 1.0],
    15091393                               [2.0, 0.0],[2.0, 2.0],
    15101394                               [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
    15151398        #Shift datapoints according to new origins
    15161399        for k in range(len(ab_points)):
    15171400            data_points[k][0] = ab_points[k][0] - mesh_origin[1]
    15181401            data_points[k][1] = ab_points[k][1] - mesh_origin[2]
    1519         #print "data_points",data_points     
    15201402        new_geospatial = ensure_geospatial(data_points,
    1521                                              geo_reference=mesh_origin)
     1403                                           geo_reference=mesh_origin)
    15221404        new_points = new_geospatial.get_data_points(absolute=True)
    1523         #print "new_points",new_points
    1524         #print "ab_points",ab_points
    1525            
    15261405        assert num.allclose(new_points, ab_points)
    15271406
    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)
    15331410        new_points = new_geospatial.get_data_points(absolute=True)
    1534         #print "new_points",new_points
    1535         #print "ab_points",ab_points
    1536            
    15371411        assert num.allclose(new_points, ab_points)
    1538 
    15391412
    15401413        geo_reference = Geo_reference(56, 100, 200)
     
    15421415        points = geo_reference.change_points_geo_ref(ab_points)
    15431416        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)
    15491419        new_points = new_geospatial.get_data_points(absolute=True)
    1550         #print "new_points",new_points
    1551         #print "ab_points",ab_points
    1552            
    15531420        assert num.allclose(new_points, ab_points)
    1554        
     1421
    15551422    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\
     14261.0, 0.0, 10.0, 0.0\n\
     14270.0, 1.0, 0.0, 10.0\n\
     14281.0, 0.0, 10.4, 40.0\n')
    15651429        file.close()
    15661430
    15671431        results = Geospatial_data(fileName)
    15681432        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]])
    15701434        assert num.allclose(results.get_attributes(attribute_name='elevation'),
    15711435                            [10.0, 0.0, 10.4])
     
    15741438
    15751439        os.remove(fileName)
    1576        
    15771440
    15781441    def test_no_constructors(self):
    1579        
    15801442        try:
    15811443            G = Geospatial_data()
    1582 #            results = Geospatial_data(file_name = fileName)
    1583 #            dict = import_points_file(fileName)
    15841444        except ValueError:
    15851445            pass
    15861446        else:
    15871447            msg = 'Instance must have a filename or data points'
    1588             raise msg       
     1448            raise Exception, msg
    15891449
    15901450    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\
    15981456150.916666667,-34.50,452.688000, 10\n\
    1599 150.0,-34,459.126000, 10\n")
     1457150.0,-34,459.126000, 10\n')
    16001458        file.close()
     1459
    16011460        results = Geospatial_data(fileName)
    16021461        os.remove(fileName)
    16031462        points = results.get_data_points()
    1604        
     1463
    16051464        assert num.allclose(points[0][0], 308728.009)
    16061465        assert num.allclose(points[0][1], 6180432.601)
    16071466        assert num.allclose(points[1][0],  222908.705)
    16081467        assert num.allclose(points[1][1], 6233785.284)
    1609        
    1610      
     1468
    16111469    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\
    16191475-34.50,150.916666667,452.688000\n\
    1620 -34,150.0,459.126000\n")
     1476-34,150.0,459.126000\n')
    16211477        file.close()
     1478
    16221479        results = Geospatial_data(fileName)
    16231480        os.remove(fileName)
    16241481        points = results.get_data_points()
    1625        
     1482
    16261483        assert num.allclose(points[0][0], 308728.009)
    16271484        assert num.allclose(points[0][1], 6180432.601)
    1628         assert num.allclose(points[1][0],  222908.705)
     1485        assert num.allclose(points[1][0], 222908.705)
    16291486        assert num.allclose(points[1][1], 6233785.284)
    16301487
    1631          
    16321488    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\
    16401494-25.0,180.0,452.688000\n\
    1641 -34,150.0,459.126000\n")
     1495-34,150.0,459.126000\n')
    16421496        file.close()
     1497
    16431498        try:
    16441499            results = Geospatial_data(fileName)
     
    16471502        else:
    16481503            msg = 'Different zones in Geo references not caught.'
    1649             raise msg       
    1650        
    1651         os.remove(fileName)
    1652        
     1504            raise Exception, msg
     1505
     1506        os.remove(fileName)
     1507
    16531508    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
    16601515        lats = [lat_gong, lat_2]
    16611516        longs = [lon_gong, lon_2]
     
    16631518
    16641519        points = gsd.get_data_points(absolute=True)
    1665        
     1520
    16661521        assert num.allclose(points[0][0], 308728.009)
    16671522        assert num.allclose(points[0][1], 6180432.601)
    1668         assert num.allclose(points[1][0],  222908.705)
     1523        assert num.allclose(points[1][0], 222908.705)
    16691524        assert num.allclose(points[1][1], 6233785.284)
    16701525        self.failUnless(gsd.get_geo_reference().get_zone() == 56,
    16711526                        'Bad zone error!')
    1672        
     1527
    16731528        try:
    16741529            results = Geospatial_data(latitudes=lats)
     
    16761531            pass
    16771532        else:
    1678             self.failUnless(0 ==1,  'Error not thrown error!')
     1533            self.fail('Error not thrown error!')
    16791534        try:
    16801535            results = Geospatial_data(latitudes=lats)
     
    16821537            pass
    16831538        else:
    1684             self.failUnless(0 ==1,  'Error not thrown error!')
     1539            self.fail('Error not thrown error!')
    16851540        try:
    16861541            results = Geospatial_data(longitudes=lats)
     
    16881543            pass
    16891544        else:
    1690             self.failUnless(0 ==1, 'Error not thrown error!')
     1545            self.fail('Error not thrown error!')
    16911546        try:
    16921547            results = Geospatial_data(latitudes=lats, longitudes=longs,
     
    16951550            pass
    16961551        else:
    1697             self.failUnless(0 ==1,  'Error not thrown error!')
    1698            
     1552            self.fail('Error not thrown error!')
     1553
    16991554        try:
    17001555            results = Geospatial_data(latitudes=lats, longitudes=longs,
     
    17031558            pass
    17041559        else:
    1705             self.failUnless(0 ==1,  'Error not thrown error!')
     1560            self.fail('Error not thrown error!')
    17061561
    17071562    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
    17141569        points = [[lat_gong, lon_gong], [lat_2, lon_2]]
    17151570        gsd = Geospatial_data(data_points=points, points_are_lats_longs=True)
    17161571
    17171572        points = gsd.get_data_points(absolute=True)
    1718        
     1573
    17191574        assert num.allclose(points[0][0], 308728.009)
    17201575        assert num.allclose(points[0][1], 6180432.601)
    1721         assert num.allclose(points[1][0],  222908.705)
     1576        assert num.allclose(points[1][0], 222908.705)
    17221577        assert num.allclose(points[1][1], 6233785.284)
    17231578        self.failUnless(gsd.get_geo_reference().get_zone() == 56,
     
    17291584            pass
    17301585        else:
    1731             self.failUnless(0 ==1,  'Error not thrown error!')
    1732 
     1586            self.fail('Error not thrown error!')
    17331587
    17341588    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.)
    17401594        p1 = (lat_gong, lon_gong)
    17411595        p2 = (lat_2, lon_2)
     
    17431597        gsd = Geospatial_data(data_points=list(points),
    17441598                              points_are_lats_longs=True)
    1745        
    1746         fn = tempfile.mktemp(".urs")
     1599
     1600        fn = tempfile.mktemp('.urs')
    17471601        gsd.export_points_file(fn)
    1748         #print "fn", fn
    17491602        handle = open(fn)
    17501603        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'
    17541607        handle.close()
    17551608        os.remove(fn)
    1756        
     1609
    17571610    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.)
    17631616        p1 = (lat_gong, lon_gong)
    17641617        p2 = (lat_2, lon_2)
     
    17681621
    17691622        points = gsd.get_data_points(absolute=True)
    1770         #print "points[0][0]", points[0][0]
    17711623        #Note the order is unknown, due to using sets
    17721624        # and it changes from windows to linux
     
    17741626            assert num.allclose(points[1][0], 308728.009)
    17751627            assert num.allclose(points[1][1], 6180432.601)
    1776             assert num.allclose(points[0][0],  222908.705)
     1628            assert num.allclose(points[0][0], 222908.705)
    17771629            assert num.allclose(points[0][1], 6233785.284)
    17781630        except AssertionError:
    17791631            assert num.allclose(points[0][0], 308728.009)
    17801632            assert num.allclose(points[0][1], 6180432.601)
    1781             assert num.allclose(points[1][0],  222908.705)
     1633            assert num.allclose(points[1][0], 222908.705)
    17821634            assert num.allclose(points[1][1], 6233785.284)
    1783            
     1635
    17841636        self.failUnless(gsd.get_geo_reference().get_zone() == 56,
    17851637                        'Bad zone error!')
    17861638        points = gsd.get_data_points(as_lat_long=True)
    1787         #print "test_lat_long_set points", points
    17881639        try:
    17891640            assert num.allclose(points[0][0], -34)
     
    17941645
    17951646    def test_len(self):
    1796        
    17971647        points = [[1.0, 2.1], [3.0, 5.3]]
    17981648        G = Geospatial_data(points)
    1799         self.failUnless(2 ==len(G), 'Len error!')
    1800        
     1649        self.failUnless(2 == len(G), 'Len error!')
     1650
    18011651        points = [[1.0, 2.1]]
    18021652        G = Geospatial_data(points)
    1803         self.failUnless(1 ==len(G), 'Len error!')
     1653        self.failUnless(1 == len(G), 'Len error!')
    18041654
    18051655        points = [[1.0, 2.1], [3.0, 5.3], [3.0, 5.3], [3.0, 5.3]]
    18061656        G = Geospatial_data(points)
    1807         self.failUnless(4 ==len(G), 'Len error!')
    1808        
     1657        self.failUnless(4 == len(G), 'Len error!')
     1658
    18091659    def test_split(self):
    18101660        """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':
    18161664            points = [[1.0, 1.0], [1.0, 2.0],[1.0, 3.0], [1.0, 4.0], [1.0, 5.0],
    18171665                      [2.0, 1.0], [2.0, 2.0],[2.0, 3.0], [2.0, 4.0], [2.0, 5.0],
     
    18191667                      [4.0, 1.0], [4.0, 2.0],[4.0, 3.0], [4.0, 4.0], [4.0, 5.0],
    18201668                      [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]}
    18251675            G = Geospatial_data(points, attributes)
    1826    
     1676
    18271677            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)
    18321681            assert num.allclose(len(G), len(G1)+len(G2))
    18331682            assert num.allclose(round(len(G)*factor), len(G1))
    1834    
     1683
    18351684            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
    18381690            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
    18411695    def test_split1(self):
    1842         """test if the results from spilt are disjoin sets"""
    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':
    18461700            from RandomArray import randint,seed
     1701
    18471702            seed(100,100)
    1848             a_points = randint(0,999999,(10,2))
     1703            a_points = randint(0, 999999, (10,2))
    18491704            points = a_points.tolist()
    1850     #        print points
    1851    
     1705
    18521706            G = Geospatial_data(points)
    1853    
     1707
    18541708            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)
    18601712            assert num.allclose(len(G), len(G1)+len(G2))
    18611713            assert num.allclose(round(len(G)*factor), len(G1))
    1862    
     1714
    18631715            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
    18671720    def test_find_optimal_smoothing_parameter(self):
    18681721        """
    1869         Creates a elevation file represting hill (sort of) and runs
     1722        Creates a elevation file representing a hill (sort of) and runs
    18701723        find_optimal_smoothing_parameter for 3 different alphas,
    1871        
     1724
    18721725        NOTE the random number seed is provided to control the results
    18731726        """
     1727
    18741728        from cmath import cos
    18751729
    1876         #below is a work around until the randint works on cyclones compute nodes
     1730        # below is a workaround until randint works on cyclones compute nodes
    18771731        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
    18861739                    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
    18901742            file.close()
    1891      
    1892             value, alpha = find_optimal_smoothing_parameter(data_file=filename, 
     1743
     1744            value, alpha = find_optimal_smoothing_parameter(data_file=filename,
    18931745                                                 alpha_list=[0.0001, 0.01, 1],
    18941746                                                 mesh_file=None,
     
    19011753                                                 seed_num=100000,
    19021754                                                 verbose=False)
    1903    
     1755
    19041756            os.remove(filename)
    1905            
     1757
    19061758            # print value, alpha
    1907             assert (alpha==0.01)
     1759            assert(alpha == 0.01)
    19081760
    19091761    def test_find_optimal_smoothing_parameter1(self):
    19101762        """
    1911         Creates a elevation file represting hill (sort of) and
     1763        Creates a elevation file representing  a hill (sort of) and
    19121764        Then creates a mesh file and passes the mesh file and the elevation
    19131765        file to find_optimal_smoothing_parameter for 3 different alphas,
    1914        
     1766
    19151767        NOTE the random number seed is provided to control the results
    19161768        """
    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
    19181771        if get_host_name()[8:9]!='0':
    1919 
    19201772            from cmath import cos
    19211773            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 made surface like a circle ripple
     1774
     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
    19301782                    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
    19341785            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
    19391791            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,
    19501802                                                 alpha_list=[0.0001, 0.01, 1],
    19511803                                                 mesh_file=mesh_filename,
     
    19531805                                                 seed_num=174,
    19541806                                                 verbose=False)
    1955    
     1807
    19561808            os.remove(filename)
    19571809            os.remove(mesh_filename)
    1958            
    1959     #        print value, alpha
    1960             assert (alpha==0.01)
     1810
     1811            assert(alpha == 0.01)
    19611812
    19621813    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
    19661816        NOTE the random number seed is provided to control the results
    1967         """
     1817        '''
     1818
    19681819        from cmath import cos
    19691820        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
    19741825        try:
    1975             value, alpha = find_optimal_smoothing_parameter(data_file=filename, 
     1826            value, alpha = find_optimal_smoothing_parameter(data_file=filename,
    19761827                                             alpha_list=[0.0001, 0.01, 1],
    19771828                                             mesh_file=mesh_filename,
     
    19821833            pass
    19831834        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
    19871888if __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')
    19921889    suite = unittest.makeSuite(Test_Geospatial_data, 'test')
    19931890    runner = unittest.TextTestRunner() #verbosity=2)
    19941891    runner.run(suite)
    19951892
    1996    
     1893
  • branches/numpy/anuga/load_mesh/loadASCII.py

    r6166 r6304  
    5858
    5959from string import  find, rfind
    60 import Numeric as num
     60import numpy as num
    6161from os.path import splitext
    6262
     
    6666from Scientific.IO.NetCDF import NetCDFFile
    6767from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
    68 
     68from anuga.config import netcdf_float, netcdf_char, netcdf_int
    6969
    7070import exceptions
     71
     72
    7173class TitleAmountError(exceptions.Exception): pass
    7274
     
    8284# @note This is used by pmesh.
    8385def import_mesh_file(ofile):
    84     """
    85     read a mesh file, either .tsh or .msh
     86    """Read a mesh file, either .tsh or .msh
    8687
    8788    Note: will throw an IOError if it can't load the file.
    8889    Catch these!
    8990    """
    90     try:
    91         if ofile[-4:]== ".tsh":
     91
     92    try:
     93        if ofile[-4:] == ".tsh":
    9294            dict = _read_tsh_file(ofile)
    93         elif ofile[-4:]== ".msh":
     95        elif ofile[-4:] == ".msh":
    9496            dict = _read_msh_file(ofile)
    9597        else:
     
    98100    #FIXME No test for ValueError
    99101    except (TitleError, SyntaxError, IndexError, ValueError):
    100             msg = 'File could not be opened'
    101             raise IOError, msg
     102        msg = 'File could not be opened'
     103        raise IOError, msg
    102104    return dict
    103105
     
    109111# @note Raises IOError if file extension is unrecognized.
    110112def export_mesh_file(ofile, mesh_dict):
    111     """
    112     write a file, ofile, with the format
     113    """Write a mesh file given a dictionary.
    113114
    114115    First line:       <# of vertices> <# of attributes>
     
    137138    # hand-off to appropriate function
    138139    if (ofile[-4:] == ".tsh"):
    139         _write_tsh_file(ofile,mesh_dict)
     140        _write_tsh_file(ofile, mesh_dict)
    140141    elif (ofile[-4:] == ".msh"):
    141142        _write_msh_file(ofile, mesh_dict)
    142143    else:
    143         msg = 'Unknown file type %s ' %ofile
     144        msg = 'Unknown file type %s ' % ofile
    144145        raise IOError, msg
    145146
    146147
    147148##
    148 # @brief Read .tsh file into a dictionary.
     149# @brief Read a mesh file into a dictionary.
    149150# @param ofile Path of the file to read.
    150 # @return Data dictionary from the .tsh file.
     151# @return Data dictionary from the mesh (.tsh) file.
    151152def _read_tsh_file(ofile):
    152     """
    153     Read the text file format for meshes
    154     """
     153    """Read the text file format for meshes"""
    155154
    156155    fd = open(ofile, 'r')
     
    169168# @return A dictionary ...
    170169def _read_triangulation(fd):
    171     """
    172     Read the generated triangulation, NOT the outline.
    173     """
     170    """Read the generated triangulation, NOT the outline."""
    174171
    175172    delimiter = " "
     
    178175    line = fd.readline()
    179176    fragments = line.split()
    180     if fragments ==[]:
     177    if fragments == []:
    181178        NumOfVertices = 0
    182179        NumOfVertAttributes = 0
     
    188185    for index in range(int(NumOfVertices)):
    189186        fragments = fd.readline().split()
    190         fragments.pop(0) #pop off the index
    191 
    192         # pop the x y off so we're left with a list of attributes
     187        fragments.pop(0)        # pop off the index
     188
     189        # pop the x & y off so we're left with a list of attributes
    193190        vert = [float(fragments.pop(0)), float(fragments.pop(0))]
    194191        points.append(vert)
     
    215212    for index in range(int(NumOfTriangles)):
    216213        line = fd.readline()
    217         line.strip() # so we can get the region string
     214        line.strip()            # so we can get the region string
    218215        fragments = line.split()
    219         fragments.pop(0) #pop off the index
     216        fragments.pop(0)        # pop off the index
    220217
    221218        tri = [int(fragments[0]), int(fragments[1]), int(fragments[2])]
     
    223220        neighbors = [int(fragments[3]), int(fragments[4]), int(fragments[5])]
    224221        triangleneighbors.append(neighbors)
    225         for x in range(7): # remove index [<vertex #>] [<neigbouring tri #>]
    226             line = line[find(line, delimiter):] # remove index
     222        for x in range(7):  # remove index [<vertex #>] [<neigbouring tri #>]
     223            line = line[find(line, delimiter):]     # remove index
    227224            line = line.lstrip()
    228225        stringtag = line.strip()
     
    237234    for index in range(int(NumOfSegments)):
    238235        line = fd.readline()
    239         line.strip() # to get the segment string
     236        line.strip()            # to get the segment string
    240237        fragments = line.split()
    241         fragments.pop(0) #pop off the index
     238        fragments.pop(0)        #pop off the index
    242239        seg = [int(fragments[0]), int(fragments[1])]
    243240        segments.append(seg)
     
    272269# @note If file has no mesh info, an empty dict will be returned.
    273270def _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'.
    274275    """
    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
    280278
    281279    # loading the point info
    282280    line = fd.readline()
    283281    fragments = line.split()
    284     if fragments ==[]:
     282    if fragments == []:
    285283        NumOfVertices = 0
    286284        NumOfVertAttributes = 0
     
    292290    for index in range(int(NumOfVertices)):
    293291        fragments = fd.readline().split()
    294         fragments.pop(0) #pop off the index
    295         # pop the x y off so we're left with a list of attributes
     292        fragments.pop(0)                # pop off the index
     293        # pop the x & y off so we're left with a list of attributes
    296294        vert = [float(fragments.pop(0)), float(fragments.pop(0))]
    297295        points.append(vert)
     
    304302    line = fd.readline()
    305303    fragments = line.split()
    306     if fragments ==[]:
     304    if fragments == []:
    307305        NumOfSegments = 0
    308306    else:
     
    313311        line = fd.readline()
    314312        fragments = line.split()
    315         fragments.pop(0) #pop off the index
     313        fragments.pop(0)                    # pop off the index
    316314        seg = [int(fragments[0]), int(fragments[1])]
    317315        segments.append(seg)
     
    350348        line = fd.readline()
    351349        fragments = line.split()
    352         fragments.pop(0) #pop off the index
     350        fragments.pop(0)                    # pop off the index
    353351        region = [float(fragments[0]), float(fragments[1])]
    354352        regions.append(region)
     
    364362    regionmaxareas = []
    365363    line = fd.readline()
    366     for index in range(int(numOfRegions)): # Read in the Max area info
     364    for index in range(int(numOfRegions)):  # Read in the Max area info
    367365        line = fd.readline()
    368366        fragments = line.split()
    369367        # The try is here for format compatibility
    370368        try:
    371             fragments.pop(0) #pop off the index
    372             if len(fragments) == 0: #no max area
     369            fragments.pop(0)                # pop off the index
     370            if len(fragments) == 0:         # no max area
    373371                regionmaxareas.append(None)
    374372            else:
     
    404402# @note Will also remove any field that was originally ''.
    405403def clean_line(line, delimiter):
    406     """Remove whitespace
    407     """
     404    """Clean up a line - return fields with end space removed."""
    408405
    409406    line = line.strip()
     
    447444    # Don't understand why we have to do vertices_attributes[0] is None,
    448445    # 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):
    452449        numVertAttrib = "0"
    453450    else:
     
    478475        fd.write(title + "\n")
    479476
    480     #<# of triangles>
     477    # <# of triangles>
    481478    n = len(triangles)
    482479    fd.write(str(n)
     
    501498                    else:
    502499                        neighbors +=  "-1 "
    503         #Warning even though a list is past, only the first value
    504         #is written.  There's an assumption that the list only
     500        # Warning even though a list is passed, only the first value
     501        # is written.  There's an assumption that the list only
    505502        # contains one item. This assumption is made since the
    506         #dict that's being passed around is also be used to communicate
     503        # dict that's being passed around is also be used to communicate
    507504        # with triangle, and it seems to have the option of returning
    508505        # 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] == ['']):
    512509            att = ""
    513510        else:
     
    520517                 + att + "\n")
    521518
    522     #One line:  <# of segments>
     519    # One line:  <# of segments>
    523520    fd.write(str(len(segments)) +
    524521             " # <# of segments>, next lines <segment #> <vertex #>  "
    525522             "<vertex #> [boundary tag] ...Triangulation Segments...\n")
    526523
    527     #Following lines:  <segment #> <vertex #>  <vertex #> [boundary tag]
     524    # Following lines:  <segment #> <vertex #>  <vertex #> [boundary tag]
    528525    for i in range(len(segments)):
    529526        seg = segments[i]
     
    560557
    561558    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'
    564561    else:
    565562        num_point_atts = str(len(point_attributes[0]))
    566563
    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')
    570567
    571568    # <x> <y> [attributes]
    572     for i,point in enumerate(points):
    573         attlist = ""
     569    for i, point in enumerate(points):
     570        attlist = ''
    574571        for att in point_attributes[i]:
    575             attlist = attlist + str(att) + " "
     572            attlist = attlist + str(att) + ' '
    576573        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>
    583578    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]
    588583    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>
    595588    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')
    597590    # <x> <y>
    598591    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>
    604595    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')
    607598
    608599    # <index> <x> <y> <tag>
    609600    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>
    618607    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')
    621610    for i,r in enumerate(regions):
    622611        area = str(region_max_areas[i])
    623612
    624         fd.write(str(i) + " " + area + "\n")
     613        fd.write(str(i) + ' ' + area + '\n')
    625614
    626615    # geo_reference info
     
    649638    # in more detail.
    650639
    651     IntType = num.Int32
     640    IntType = num.int32
    652641    #IntType = Int
    653642
    654643    #the triangulation
    655     mesh['vertices'] = num.array(mesh['vertices'], num.Float)
     644    mesh['vertices'] = num.array(mesh['vertices'], num.float)
    656645    if mesh['vertex_attributes'] != None:
    657646        mesh['vertex_attributes'] = \
    658             num.array(mesh['vertex_attributes'], num.Float)
     647            num.array(mesh['vertex_attributes'], num.float)
    659648    mesh['vertex_attribute_titles'] = \
    660         num.array(mesh['vertex_attribute_titles'], num.Character)
     649        num.array(mesh['vertex_attribute_titles'], num.character)
    661650    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)
    663652    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'])
    665654    mesh['triangle_neighbors'] = \
    666655        num.array(mesh['triangle_neighbors'], IntType)
    667656
    668657    #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)
    671660    mesh['outline_segments'] = num.array(mesh['outline_segments'], IntType)
    672661    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)
    682667
    683668    # NetCDF file definition
     
    686671    except IOError:
    687672        msg = 'File %s could not be created' % file_name
    688         raise msg
     673        raise Exception, msg
    689674
    690675    #Create new file
    691676    outfile.institution = 'Geoscience Australia'
    692     outfile.description = 'NetCDF format for compact and portable storage ' +\
     677    outfile.description = 'NetCDF format for compact and portable storage ' + \
    693678                          'of spatial point data'
    694679
    695680    # dimension definitions - fixed
    696     outfile.createDimension('num_of_dimensions', 2) #This is 2d data
    697     outfile.createDimension('num_of_segment_ends', 2) #Segs have two points
     681    outfile.createDimension('num_of_dimensions', 2)     # This is 2d data
     682    outfile.createDimension('num_of_segment_ends', 2)   # Segs have two points
    698683    outfile.createDimension('num_of_triangle_vertices', 3)
    699684    outfile.createDimension('num_of_triangle_faces', 3)
     
    706691    if (mesh['vertices'].shape[0] > 0):
    707692        outfile.createDimension('num_of_vertices', mesh['vertices'].shape[0])
    708         outfile.createVariable('vertices', num.Float, ('num_of_vertices',
    709                                                        'num_of_dimensions'))
     693        outfile.createVariable('vertices', netcdf_float, ('num_of_vertices',
     694                                                          'num_of_dimensions'))
    710695        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)):
    714699            outfile.createDimension('num_of_vertex_attributes',
    715700                                    mesh['vertex_attributes'].shape[1])
     
    717702                                    mesh['vertex_attribute_titles'].shape[1])
    718703            outfile.createVariable('vertex_attributes',
    719                                    num.Float,
     704                                   netcdf_float,
    720705                                   ('num_of_vertices',
    721706                                    'num_of_vertex_attributes'))
    722707            outfile.createVariable('vertex_attribute_titles',
    723                                    num.Character,
     708                                   netcdf_char,
    724709                                   ('num_of_vertex_attributes',
    725710                                    'num_of_vertex_attribute_title_chars'))
     
    732717    if (mesh['segments'].shape[0] > 0):
    733718        outfile.createDimension('num_of_segments', mesh['segments'].shape[0])
    734         outfile.createVariable('segments', IntType,
     719        outfile.createVariable('segments', netcdf_int,
    735720                               ('num_of_segments', 'num_of_segment_ends'))
    736721        outfile.variables['segments'][:] = mesh['segments']
    737         if (mesh['segment_tags'].shape[1] > 0):
     722        if mesh['segment_tags'].shape[1] > 0:
    738723            outfile.createDimension('num_of_segment_tag_chars',
    739724                                    mesh['segment_tags'].shape[1])
    740725            outfile.createVariable('segment_tags',
    741                                    num.Character,
     726                                   netcdf_char,
    742727                                   ('num_of_segments',
    743728                                    'num_of_segment_tag_chars'))
     
    747732    if (mesh['triangles'].shape[0] > 0):
    748733        outfile.createDimension('num_of_triangles', mesh['triangles'].shape[0])
    749         outfile.createVariable('triangles',
    750                                IntType,
     734        outfile.createVariable('triangles', netcdf_int,
    751735                               ('num_of_triangles', 'num_of_triangle_vertices'))
    752         outfile.createVariable('triangle_neighbors',
    753                                IntType,
     736        outfile.createVariable('triangle_neighbors', netcdf_int,
    754737                               ('num_of_triangles', 'num_of_triangle_faces'))
    755738        outfile.variables['triangles'][:] = mesh['triangles']
    756739        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)):
    759742            outfile.createDimension('num_of_triangle_tag_chars',
    760743                                    mesh['triangle_tags'].shape[1])
    761             outfile.createVariable('triangle_tags',
    762                                    num.Character,
     744            outfile.createVariable('triangle_tags', netcdf_char,
    763745                                   ('num_of_triangles',
    764746                                    'num_of_triangle_tag_chars'))
     
    769751    if (mesh['points'].shape[0] > 0):
    770752        outfile.createDimension('num_of_points', mesh['points'].shape[0])
    771         outfile.createVariable('points', num.Float, ('num_of_points',
    772                                                      'num_of_dimensions'))
     753        outfile.createVariable('points', netcdf_float,
     754                               ('num_of_points', 'num_of_dimensions'))
    773755        outfile.variables['points'][:] = mesh['points']
    774756        if mesh['point_attributes'].shape[0] > 0  \
     
    776758            outfile.createDimension('num_of_point_attributes',
    777759                                    mesh['point_attributes'].shape[1])
    778             outfile.createVariable('point_attributes',
    779                                    num.Float,
     760            outfile.createVariable('point_attributes', netcdf_float,
    780761                                   ('num_of_points', 'num_of_point_attributes'))
    781762            outfile.variables['point_attributes'][:] = mesh['point_attributes']
     
    785766        outfile.createDimension('num_of_outline_segments',
    786767                                mesh['outline_segments'].shape[0])
    787         outfile.createVariable('outline_segments',
    788                                IntType,
     768        outfile.createVariable('outline_segments', netcdf_int,
    789769                               ('num_of_outline_segments',
    790770                                'num_of_segment_ends'))
     
    793773            outfile.createDimension('num_of_outline_segment_tag_chars',
    794774                                    mesh['outline_segment_tags'].shape[1])
    795             outfile.createVariable('outline_segment_tags',
    796                                    num.Character,
     775            outfile.createVariable('outline_segment_tags', netcdf_char,
    797776                                   ('num_of_outline_segments',
    798777                                    'num_of_outline_segment_tag_chars'))
     
    803782    if (mesh['holes'].shape[0] > 0):
    804783        outfile.createDimension('num_of_holes', mesh['holes'].shape[0])
    805         outfile.createVariable('holes', num.Float, ('num_of_holes',
    806                                                    'num_of_dimensions'))
     784        outfile.createVariable('holes', netcdf_float,
     785                               ('num_of_holes', 'num_of_dimensions'))
    807786        outfile.variables['holes'][:] = mesh['holes']
    808787
     
    810789    if (mesh['regions'].shape[0] > 0):
    811790        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',))
    815795        outfile.variables['regions'][:] = mesh['regions']
    816796        outfile.variables['region_max_areas'][:] = mesh['region_max_areas']
     
    818798            outfile.createDimension('num_of_region_tag_chars',
    819799                                    mesh['region_tags'].shape[1])
    820             outfile.createVariable('region_tags', num.Character,
     800            outfile.createVariable('region_tags', netcdf_char,
    821801                                   ('num_of_regions',
    822802                                    'num_of_region_tag_chars'))
     
    834814# @param file_name Path to the file to read.
    835815# @return A dictionary containing the .msh file data.
     816# @note Throws IOError if file not found.
    836817def _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
    843821    fd = open(file_name, 'r')
    844822    fd.close()
    845823
    846     #throws prints to screen if file not present
     824    # throws prints to screen if file not present
    847825    fid = NetCDFFile(file_name, netcdf_mode_r)
    848826    mesh = {}
    849827
    850     # Get the variables
    851     # the triangulation
     828    # Get the variables - the triangulation
    852829    try:
    853830        mesh['vertices'] = fid.variables['vertices'][:]
    854831    except KeyError:
    855         mesh['vertices'] = num.array([], num.Int)      #array default#
     832        mesh['vertices'] = num.array([], num.int)      #array default#
    856833
    857834    try:
     
    859836    except KeyError:
    860837        mesh['vertex_attributes'] = None
    861         #for ob in mesh['vertices']:
    862             #mesh['vertex_attributes'].append([])
    863838
    864839    mesh['vertex_attribute_titles'] = []
     
    873848        mesh['segments'] = fid.variables['segments'][:]
    874849    except KeyError:
    875         mesh['segments'] = num.array([], num.Int)      #array default#
     850        mesh['segments'] = num.array([], num.int)      #array default#
    876851
    877852    mesh['segment_tags'] =[]
     
    888863        mesh['triangle_neighbors'] = fid.variables['triangle_neighbors'][:]
    889864    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'] = []
    894869    try:
    895870        tags = fid.variables['triangle_tags'][:]
     
    916891        mesh['outline_segments'] = fid.variables['outline_segments'][:]
    917892    except KeyError:
    918         mesh['outline_segments'] = num.array([], num.Int)      #array default#
     893        mesh['outline_segments'] = num.array([], num.int)      #array default#
    919894
    920895    mesh['outline_segment_tags'] =[]
     
    930905        mesh['holes'] = fid.variables['holes'][:]
    931906    except KeyError:
    932         mesh['holes'] = num.array([], num.Int)      #array default#
     907        mesh['holes'] = num.array([], num.int)          #array default#
    933908
    934909    try:
    935910        mesh['regions'] = fid.variables['regions'][:]
    936911    except KeyError:
    937         mesh['regions'] = num.array([], num.Int)      #array default#
     912        mesh['regions'] = num.array([], num.int)        #array default#
    938913
    939914    mesh['region_tags'] =[]
     
    949924        mesh['region_max_areas'] = fid.variables['region_max_areas'][:]
    950925    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#
    953927
    954928    try:
     
    972946# @note Used by alpha shapes
    973947def 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:
    977951    First line: Title variable
    978952    Following lines:  [point index][delimiter][point index]
     
    985959    fd = open(file_name, 'w')
    986960
    987     fd.write(title + "\n")
    988 
    989     #[point index][delimiter][point index]
     961    fd.write(title + '\n')
     962
     963    # [point index][delimiter][point index]
    990964    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')
    992966
    993967    fd.close()
    994968
    995969
    996 ###
     970################################################################################
    997971#  IMPORT/EXPORT POINTS FILES
    998 ###
     972################################################################################
    999973
    1000974##
     
    1002976# @param point_atts
    1003977def extent_point_atts(point_atts):
     978    """Returns 4 points representing the extent
     979    This loses attribute info.
    1004980    """
    1005     Returns 4 points representing the extent
    1006     This losses attribute info.
    1007     """
     981
    1008982    point_atts['pointlist'] = extent(point_atts['pointlist'])
    1009983    point_atts['attributelist'] = {}
     
    1018992#                                  [max_x, max_y], [min_x, max_y]]
    1019993def extent(points):
    1020     points = num.array(points, num.Float)
     994    points = num.array(points, num.float)
    1021995
    1022996    max_x = min_x = points[0][0]
     
    1025999    for point in points[1:]:
    10261000        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
    10291005
    10301006        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
    10331011
    10341012    extent = num.array([[min_x, min_y],
     
    10471025# @param verbose True if this function is to be verbose.
    10481026def 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
    10511030    is less than max_points.
    10521031    """
     
    10911070##
    10921071# @brief
    1093 # @param point_atts Object with attribute of 'points list'.
     1072# @param point_atts Object with attribute of 'pointlist'.
    10941073# @return
    10951074def point_atts2array(point_atts):
    10961075    # 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)
    10981077
    10991078    for key in point_atts['attributelist'].keys():
    11001079        point_atts['attributelist'][key] = \
    1101             num.array(point_atts['attributelist'][key], num.Float)
     1080            num.array(point_atts['attributelist'][key], num.float)
    11021081
    11031082    return point_atts
     
    11271106    """
    11281107
    1129     point_attributes = num.array([], num.Float)
     1108    point_attributes = num.array([], num.float)
    11301109    keys = dic.keys()
    11311110    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))
    11331112    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))
    11361114        point_attributes = num.concatenate([point_attributes, reshaped], axis=1)
    11371115
     
    11441122# @param indices_to_keep
    11451123# @return
    1146 #FIXME(dsg), turn this dict plus methods into a class?
     1124# @note FIXME(dsg), turn this dict plus methods into a class?
    11471125def take_points(dict, indices_to_keep):
    11481126    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)
    11511128
    11521129    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)
    11551132
    11561133    return dict
     
    11611138# @param dict2 ??
    11621139# @return ??
    1163 def add_point_dictionaries (dict1, dict2):
     1140def add_point_dictionaries(dict1, dict2):
    11641141    """
    11651142    """
     
    11701147    combined = {}
    11711148    combined['pointlist'] = num.concatenate((dict2['pointlist'],
    1172                                              dict1['pointlist']),axis=0)
     1149                                             dict1['pointlist']), axis=0)
    11731150
    11741151    atts = {}
     
    11761153        atts[key]= num.concatenate((dict2['attributelist'][key],
    11771154                                    dict1['attributelist'][key]), axis=0)
    1178     combined['attributelist']=atts
     1155    combined['attributelist'] = atts
    11791156    combined['geo_reference'] = dict1['geo_reference']
    11801157
  • branches/numpy/anuga/load_mesh/test_loadASCII.py

    r6154 r6304  
    11#!/usr/bin/env python
    2 #
    32
    43import tempfile
     
    109from os.path import splitext
    1110
    12 import Numeric as num
     11import numpy as num
    1312   
    1413from anuga.load_mesh.loadASCII import *
    1514from anuga.coordinate_transforms.geo_reference import Geo_reference
    1615import loadASCII
     16
    1717
    1818class loadASCIITestCase(unittest.TestCase):
     
    2525        self.dict['regions'] = [(0.3, 0.3),(0.3, 0.4)]
    2626        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]
    2828        self.dict['points'] = [(0.0, 0.0), (0.0, 4.0), (4.0, 0.0), (1.0, 1.0)]
    2929        self.dict['vertices'] = [(0.0, 0.0), (0.0, 4.0),
     
    3535        self.dict['triangle_tags'] = ['1.3', '1.3',
    3636                                      '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.]]
    3939        self.dict['triangle_neighbors'] = [[-1, 2, 3], [3, 2, -1],
    4040                                           [-1, 1, 0], [1, -1, 0]]
    4141        self.dict['segment_tags'] = ['50', '40', '30', '20', '40']
    4242        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)
    4444       
    4545        self.sparse_dict ={}
     
    4747        self.sparse_dict['outline_segment_tags'] = []
    4848        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 have
    51                                                     # attributes
     49        self.sparse_dict['points'] = [(0.0, 0.0), (9, 8)]
     50        self.sparse_dict['point_attributes'] = [[], []] # points don't have to
     51                                                        # have attributes
    5252        self.sparse_dict['regions'] = []
    5353        self.sparse_dict['region_tags'] = []
     
    8282       
    8383        self.tri_dict ={}
    84         self.tri_dict['outline_segments'] = [[0,1]]
     84        self.tri_dict['outline_segments'] = [[0, 1]]
    8585        self.tri_dict['outline_segment_tags'] = ['']
    8686        self.tri_dict['holes'] = []
    87         self.tri_dict['points'] = [(9,8),(7,8)]
     87        self.tri_dict['points'] = [(9, 8), (7, 8)]
    8888        self.tri_dict['point_attributes'] = [[],[]]
    8989        self.tri_dict['regions'] = []
    9090        self.tri_dict['region_tags'] = []
    9191        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]]
    9595        self.tri_dict['triangle_tags'] = ['']
    9696        self.tri_dict['vertex_attributes'] = None
    97         self.tri_dict['triangle_neighbors'] = [[0,0,0]]
     97        self.tri_dict['triangle_neighbors'] = [[0, 0, 0]]
    9898        self.tri_dict['segment_tags'] = ['']
    9999        self.tri_dict['vertex_attribute_titles'] = []
    100100       
    101101        self.seg_dict ={}
    102         self.seg_dict['outline_segments'] = [[0,1]]
     102        self.seg_dict['outline_segments'] = [[0, 1]]
    103103        self.seg_dict['outline_segment_tags'] = ['']
    104104        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)]
    108108        self.seg_dict['region_tags'] = ['']
    109109        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)]
    111111        self.seg_dict['triangles'] = []
    112         self.seg_dict['segments'] = [[0,1]]
     112        self.seg_dict['segments'] = [[0, 1]]
    113113        self.seg_dict['triangle_tags'] = []
    114114        self.seg_dict['vertex_attributes'] = None
     
    118118       
    119119        self.reg_dict ={}
    120         self.reg_dict['outline_segments'] = [[0,1]]
     120        self.reg_dict['outline_segments'] = [[0, 1]]
    121121        self.reg_dict['outline_segment_tags'] = ['']
    122122        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)]
    126126        self.reg_dict['region_tags'] = ['']
    127127        self.reg_dict['region_max_areas'] = []
    128         self.reg_dict['vertices'] = [(9,8),(7,8)]
     128        self.reg_dict['vertices'] = [(9, 8), (7, 8)]
    129129        self.reg_dict['triangles'] = []
    130         self.reg_dict['segments'] = [[0,1]]
     130        self.reg_dict['segments'] = [[0, 1]]
    131131        self.reg_dict['triangle_tags'] = []
    132         self.reg_dict['vertex_attributes'] = [[],[]]
     132        self.reg_dict['vertex_attributes'] = [[], []]
    133133        self.reg_dict['triangle_neighbors'] = []
    134134        self.reg_dict['segment_tags'] = ['']
     
    136136       
    137137        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']
    140142        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]]
    142145        self.triangle_tags_dict['regions'] = [(0.3, 0.3),(0.3, 0.4)]
    143146        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)]
    146150        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)]
    148153        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)]
    150155        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', '']
    154158        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.]]
    156161        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]]
    158163        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)
    161167       
    162168    def tearDown(self):
     
    169175       
    170176        meshDict = self.dict
    171         fileName = tempfile.mktemp(".tsh")
     177        fileName = tempfile.mktemp('.tsh')
    172178        export_mesh_file(fileName, meshDict)
    173179        loadedDict = import_mesh_file(fileName)
    174180       
    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']) ==
    182182                                    num.array(loadedDict['vertices'])),
    183183                        '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']) ==
    185185                                    num.array(loadedDict['triangles'])),
    186186                        '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']) ==
    188188                                    num.array(loadedDict['segments'])),
    189189                        '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']) ==
    191191                                    num.array(loadedDict['triangle_tags'])),
    192192                        'test_export_mesh_file failed. Test 4')
    193193
    194         self.failUnless(meshDict['vertex_attributes']  ==
     194        self.failUnless(meshDict['vertex_attributes'] ==
    195195                        loadedDict['vertex_attributes'],
    196196                        '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']) ==
    198198                                    num.array(loadedDict['triangle_neighbors'])),
    199199                        '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']) ==
    201201                                    num.array(loadedDict['segment_tags'])),
    202202                        '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']) ==
    204204                                    num.array(loadedDict['vertex_attribute_titles'])),
    205205                        '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']) ==
    207207                                    num.array(loadedDict['geo_reference'])),
    208208                        'test_export_mesh_file failed. Test 9')
     
    212212    def test_read_write_tsh_file(self):
    213213        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)
    216216        loaded_dict = import_mesh_file(fileName)
    217217        os.remove(fileName)
    218218        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')
    225220       
    226221    def test_read_write_tsh_fileII(self):
    227222        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)
    230225        loaded_dict = import_mesh_file(fileName)
    231226        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')
    233228        os.remove(fileName)
    234229       
    235230    def test_read_write_tsh_fileIII(self):
    236231        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)
    239234        loaded_dict = import_mesh_file(fileName)
    240235        os.remove(fileName)
     
    245240        #print loaded_dict
    246241        #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')
    248243
    249244    def test_read_write_tsh_file4(self):
    250245        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)
    253248        loaded_dict = import_mesh_file(fileName)
    254249        os.remove(fileName)
    255250        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')
    257252
    258253    def test_read_write_tsh_file5(self):
    259254        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)
    262257        loaded_dict = import_mesh_file(fileName)
    263258        dict = self.triangle_tags_dict
     
    267262        #print loaded_dict
    268263        #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') 
    270265        os.remove(fileName)
    271266
    272267    def test_read_write_tsh_file6(self):
    273268        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)
    276271        loaded_dict = import_mesh_file(fileName)
    277272        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') 
    279274        os.remove(fileName)
    280275       
     
    285280        import tempfile
    286281       
    287         fileName = tempfile.mktemp(".tsh")
    288         #print fileName
     282        fileName = tempfile.mktemp('.tsh')
    289283        try:
    290284            dict = import_mesh_file(fileName)
     
    292286            pass
    293287        else:
    294             self.failUnless(0 ==1,
    295                         'imaginary file did not raise error!')
     288            self.failUnless(0 == 1, 'imaginary file did not raise error!')
    296289         
    297290    def test_read_write_tsh_file_bad(self):
    298291        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)
    302295        except IOError:
    303296            pass
    304297        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!')       
    307299       
    308300    def test_import_tsh_bad(self):
     
    310302        import tempfile
    311303       
    312         fileName = tempfile.mktemp(".tsh")
    313         file = open(fileName,"w")
     304        fileName = tempfile.mktemp('.tsh')
     305        file = open(fileName, 'w')
    314306        #   this is  a bad tsh file
    315         file.write("elevn\n\
     307        file.write('elevn\n\
    3163081.0 what \n\
    3173090.0 the \n\
    318 1.0 !!! \n")
     3101.0 !!! \n')
    319311        file.close()
    320312        #print fileName
     
    324316            pass
    325317        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!')
    328319        os.remove(fileName)
    329320
     
    332323        import tempfile
    333324       
    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\
    337328showme1.0 0.0 10.0 \n\
    3383290.0 1.0\n\
    339 13.0 \n")
     33013.0 \n')
    340331        file.close()
    341         #print fileName
    342332        try:
    343333            dict = import_mesh_file(fileName)
     
    345335            pass
    346336        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!')
    349338       
    350339        os.remove(fileName)         
     
    355344    def test_read_write_msh_file(self):
    356345        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)
    359348        loaded_dict = loadASCII._read_msh_file(fileName)
    360349        os.remove(fileName)
     
    365354        #print loaded_dict
    366355        #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')
    368357
    369358    def test_read_write_msh_fileII(self):
    370359        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)
    373362        loaded_dict = loadASCII._read_msh_file(fileName)
    374363        os.remove(fileName)
     
    379368        #print loaded_dict
    380369        #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')
    382371             
    383372    def test_read_write_msh_fileIII(self):
    384373        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)
    387376        loaded_dict = loadASCII._read_msh_file(fileName)
    388377        os.remove(fileName)
     
    393382        #print loaded_dict
    394383        #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')
    396385       
    397386    def test_read_write_msh_file4(self):
    398387        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)
    401390        loaded_dict = loadASCII._read_msh_file(fileName)
    402391        os.remove(fileName)
     
    407396        #print loaded_dict
    408397        #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')
    410399       
    411400    def test_read_write_msh_file5(self):
    412401        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)
    415404        loaded_dict = loadASCII._read_msh_file(fileName)
    416405        os.remove(fileName)
     
    421410        #print loaded_dict
    422411        #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')
    425413       
    426414    def test_read_write_msh_file6(self):
    427415        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)
    430418        loaded_dict = loadASCII._read_msh_file(fileName)
    431419        os.remove(fileName)
    432420        dict = self.tri_dict
    433         #print "*********************"
    434         #print dict
    435         #print "**loaded_dict*******************"
    436         #print loaded_dict
    437         #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')
    439427                         
    440     def check_mesh_dicts(self, loaded_dict, dict, fail_string ):
     428    def check_mesh_dicts(self, loaded_dict, dict, fail_string):
    441429        assert num.allclose(num.array(loaded_dict['points']),
    442430                            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']),
    445432                            num.array(dict['point_attributes']))
    446433        assert num.allclose(num.array(loaded_dict['outline_segments']),
    447434                            num.array(dict['outline_segments']))
    448435       
    449         self.failUnless(loaded_dict['outline_segment_tags']  ==
     436        self.failUnless(loaded_dict['outline_segment_tags'] ==
    450437                        dict['outline_segment_tags'],
    451438                        fail_string + ' failed!! Test 4')
    452        
    453439           
    454440        assert num.allclose(num.array(loaded_dict['regions']),
    455441                            num.array(dict['regions']))
    456442                       
    457         self.failUnless(loaded_dict['region_tags']  ==
    458                         dict['region_tags'],
     443        self.failUnless(loaded_dict['region_tags'] == dict['region_tags'],
    459444                        fail_string + ' failed!! Test 5')
    460445       
     
    473458        assert num.allclose(num.array(dict['segments']),
    474459                            num.array(loaded_dict['segments']))
     460
    475461        for ob, ldob in map(None,dict['triangle_tags'],
    476462                              loaded_dict['triangle_tags']):
    477463            self.failUnless(ob == ldob,
    478                         fail_string + ' failed!! Test triangle_tags')
     464                            fail_string + ' failed!! Test triangle_tags')
     465
    479466        # A bit hacky
    480         self.failUnless((loaded_dict['vertex_attributes']  ==
    481                         dict['vertex_attributes']) or \
    482                         (loaded_dict['vertex_attributes']  == None and \
     467        self.failUnless((loaded_dict['vertex_attributes'] ==
     468                         dict['vertex_attributes']) or \
     469                        (loaded_dict['vertex_attributes'] == None and \
    483470                         dict['vertex_attributes'] == []),
    484471                        fail_string + ' failed!! Test vertex_attributes')
     
    489476        for seg, ldseg in map(None,dict['segment_tags'],
    490477                              loaded_dict['segment_tags']):
    491             self.failUnless(seg  == ldseg,
    492                         fail_string + ' failed!! Test 8')
     478            self.failUnless(seg == ldseg,
     479                            fail_string + ' failed!! Test 8')
    493480        try:
    494481            assert num.allclose(num.array(dict['vertex_attribute_titles']),
    495482                                num.array(loaded_dict['vertex_attribute_titles']))
    496483        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'])),
    498486                            fail_string + ' failed!! Test 8')
    499487        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')
    503491        except KeyError:         
    504492            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')
    507495 
    508496########################## BAD .MSH ##########################         
     
    512500        import tempfile
    513501       
    514         fileName = tempfile.mktemp(".msh")
    515         #print fileName
     502        fileName = tempfile.mktemp('.msh')
    516503        try:
    517504            dict = import_mesh_file(fileName)
     
    519506            pass
    520507        else:
    521             self.failUnless(0 ==1,
    522                         'imaginary file did not raise error!')
     508            self.failUnless(0 == 1, 'imaginary file did not raise error!')
    523509           
    524510    def throws_error_2_screen_test_import_mesh_bad(self):
     
    526512        import tempfile
    527513       
    528         fileName = tempfile.mktemp(".msh")
    529         file = open(fileName,"w")
    530         #   this is  a bad tsh file
    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\
    5325181.0 what \n\
    5335190.0 the \n\
    534 1.0 !!! \n")
     5201.0 !!! \n')
    535521        file.close()
    536         #print fileName
    537522        try:
    538523            dict = import_mesh_file(fileName)
     
    540525            pass
    541526        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!')
    544528        os.remove(fileName)         
    545529
    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              
    565530#-------------------------------------------------------------
    566 if __name__ == "__main__":
     531if __name__ == '__main__':
    567532
    568533    suite = unittest.makeSuite(loadASCIITestCase,'test')
    569     #suite = unittest.makeSuite(loadASCIITestCase,'test_read_write_tsh_file4')
    570534    runner = unittest.TextTestRunner() #verbosity=2)
    571535    runner.run(suite)
  • branches/numpy/anuga/mesh_engine/mesh_engine.py

    r6155 r6304  
    1111#import anuga.mesh_engine.list_dic as triang
    1212
    13 import Numeric as num
     13import numpy as num
    1414
    1515from anuga.utilities.numerical_tools import ensure_numeric
     
    4646       
    4747    try:
    48         points =  ensure_numeric(points, num.Float)
     48        points =  ensure_numeric(points, num.float)
    4949    except ValueError:
    5050        msg = 'ERROR: Inconsistent points array.'
     
    6060       
    6161    try:
    62         # If Int is used, instead of Int32, it fails in Linux
    63         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)
    6464       
    6565    except ValueError:
     
    7272       
    7373    try:
    74         holes = ensure_numeric(holes, num.Float)
     74        holes = ensure_numeric(holes, num.float)
    7575    except ValueError:
    7676        msg = 'ERROR: Inconsistent holess array.'
     
    8080    regions = add_area_tag(regions)
    8181    try:
    82         regions = ensure_numeric(regions, num.Float)
     82        regions = ensure_numeric(regions, num.float)
    8383    except  (ValueError, TypeError):
    8484        msg = 'ERROR: Inconsistent regions array.'
     
    9090   
    9191    try:
    92         pointatts = ensure_numeric(pointatts, num.Float)
     92        pointatts = ensure_numeric(pointatts, num.float)
    9393    except (ValueError, TypeError):
    9494        msg = 'ERROR: Inconsistent point attributes array.'
     
    103103   
    104104    try:
    105         segatts = ensure_numeric(segatts, num.Int32)
     105        segatts = ensure_numeric(segatts, num.int32)
    106106    except ValueError:
    107107        msg = 'ERROR: Inconsistent point attributes array.'
  • branches/numpy/anuga/mesh_engine/mesh_engine_c_layer.c

    r4917 r6304  
    88
    99    This code interfaces pmesh directly with "triangle", a general       
    10     purpose triangulation code. In doing so, Python Numeric data structures
     10    purpose triangulation code. In doing so, Python numeric data structures
    1111     are passed to C for  use by "triangle" and the results are then         
    1212    converted back. This was accomplished using the Python/C API.           
     
    6464#define PY_ARRAY_UNIQUE_SYMBOL API_YEAH
    6565//#define NO_IMPORT_ARRAY
    66 #include "Numeric/arrayobject.h"
     66#include "numpy/arrayobject.h"
    6767#include <sys/types.h>
    6868
     
    245245     abs quantity_ext.c compute_gradients
    246246     
    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.
    248248   The first argument is the size of the second argument (
    249249   the dimensions array).
     
    351351 
    352352 
    353   /* These memory blocks are passed into Numeric arrays
     353  /* These memory blocks are passed into numeric arrays
    354354   so don't free them  */
    355355  /*
  • branches/numpy/anuga/mesh_engine/test_generate_mesh.py

    r6174 r6304  
    1212from anuga.mesh_engine.mesh_engine import generate_mesh
    1313
    14 import Numeric as num
     14import numpy as num
    1515
    1616from anuga.utilities.numerical_tools import ensure_numeric
     
    4343                              pointattlist,segattlist, mode, points)
    4444
    45         correct = num.array([(1, 0, 2), (2, 3, 1)], num.Int)      #array default#
     45        correct = num.array([(1, 0, 2), (2, 3, 1)])
    4646        self.failUnless(num.alltrue(data['generatedtrianglelist'].flat == \
    4747                                    correct.flat),
    4848                        '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)])
    5050        self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \
    5151                                    correct.flat),
     
    7474        data = generate_mesh(points,seglist,holelist,regionlist,
    7575                              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)])
    7777        self.failUnless(num.alltrue(data['generatedtrianglelist'].flat == \
    7878                                    correct.flat),
    7979                        '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)])
    8181        self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \
    8282                                    correct.flat),
     
    154154                              pointattlist,segattlist, mode, points)
    155155
    156         correct = num.array([(1, 0, 2), (2, 3, 1)], num.Int)      #array default#
     156        correct = num.array([(1, 0, 2), (2, 3, 1)])
    157157        self.failUnless(num.alltrue(data['generatedtrianglelist'].flat == \
    158158                                    correct.flat),
    159159                        '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)])
    161161        self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \
    162162                                    correct.flat),
     
    170170       
    171171        self.failUnless(num.alltrue(data['generatedsegmentmarkerlist'] == \
    172                                     num.array([1,2,3,4], num.Int)),      #array default#
     172                                    num.array([1,2,3,4])),
    173173                        'Failed!')
    174174       
     
    388388
    389389     
    390         correct = num.array([(1, 0, 2), (2, 3, 1)], num.Int)      #array default#
     390        correct = num.array([(1, 0, 2), (2, 3, 1)])
    391391        self.failUnless(num.alltrue(data['generatedtrianglelist'].flat == \
    392392                                    correct.flat),
    393393                        '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)])
    395395        self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \
    396396                                    correct.flat),
     
    407407                                     correct.flat),
    408408                        '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)])
    410410        self.failUnless(num.alltrue(data['generatedsegmentlist'].flat == \
    411411                                    correct.flat),
    412412                        'Failed!')
    413413       
    414         correct = num.array(segattlist, num.Int)      #array default#
     414        correct = num.array(segattlist)
    415415        self.failUnless(num.allclose(data['generatedsegmentmarkerlist'].flat,
    416416                                     correct.flat),
     
    418418       
    419419        # 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)])
    421421        self.failUnless(num.alltrue(data['generatedtriangleneighborlist'].flat == \
    422422                                    correct.flat),
     
    467467
    468468    suite = unittest.makeSuite(triangTestCase,'test')
    469     #suite = unittest.makeSuite(triangTestCase,'testrectangleIIb')
    470     #suite = unittest.makeSuite(triangTestCase,'testsegmarker')
    471     #suite = unittest.makeSuite(triangTestCase,'testrectangle_regionsII')
    472469    runner = unittest.TextTestRunner()  #verbosity=2)
    473470    runner.run(suite)
  • branches/numpy/anuga/pmesh/mesh.py

    r6156 r6304  
    2222import types
    2323import exceptions
     24
     25import numpy as num
    2426
    2527
     
    3739except ImportError: 
    3840    # 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 may 
     41    # was recently removed from the standard numeric distro.  Some users may 
    4042    # not have it by default. 
    4143    class _bunch: 
     
    117119
    118120class Vertex(Point):
    119     """
    120     A point on the mesh.
     121    """A point on the mesh.
    121122    Object attributes based on the Triangle program
    122123    """
    123     def __init__(self,X,Y, attributes = None):
     124
     125    VERTEXSQUARESIDELENGTH = 6
     126
     127    def __init__(self, X, Y, attributes=None):
    124128        __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:
    135136            self.attributes=attributes
    136137   
    137 
    138138    def setAttributes(self,attributes):
    139         """
    140         attributes is a list.
    141         """
     139        """attributes is a list. """
     140
    142141        self.attributes = attributes
    143142       
    144     VERTEXSQUARESIDELENGTH = 6
    145143    def draw(self, canvas, tags, colour = 'black',scale = 1, xoffset = 0,
    146144             yoffset =0, ):
     
    176174    def __repr__(self):
    177175        return "[(%f,%f),%r]" % (self.x,self.y,self.attributes)
    178    
     176
     177
    179178class 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.
    182180    Defined by a point in the hole enclosed by segments.
    183181    """
     
    201199   
    202200class 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.
    206203    """
     204
    207205    CROSSLENGTH = 6
    208206    TAG = 0
    209207    MAXAREA = 1
    210208   
    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
    216212        self.x=X
    217213        self.y=Y   
    218         self.attributes =[] # index 0 is the tag string
    219                             #optoinal index 1 is the max triangle area
    220                             #NOTE the size of this attribute is assumed
    221                             # to be 1 or 2 in regionstrings2int
     214        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
    222218        if tag is None:
    223219            self.attributes.append("")
  • branches/numpy/anuga/pmesh/mesh_interface.py

    r6180 r6304  
    33from anuga.utilities.polygon import  point_in_polygon ,populate_polygon
    44from anuga.utilities.numerical_tools import ensure_numeric
    5 import Numeric as num
     5import numpy as num
    66from anuga.utilities.polygon import inside_polygon
    77
     
    156156
    157157    # Simple check
    158     bounding_polygon = ensure_numeric(bounding_polygon, num.Float)
     158    bounding_polygon = ensure_numeric(bounding_polygon, num.float)
    159159    msg = 'Bounding polygon must be a list of points or an Nx2 array'
    160160    assert len(bounding_polygon.shape) == 2, msg
  • branches/numpy/anuga/pmesh/test_mesh.py

    r6172 r6304  
    1515from anuga.utilities.polygon import  is_inside_polygon ### inside_polygon
    1616
    17 import Numeric as num
     17import numpy as num
    1818
    1919class meshTestCase(unittest.TestCase):
     
    428428        vert = m.getMeshVerticeAttributes()
    429429       
    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]) ,
    435436                        'vertex attributes are wrong!')
    436437
     
    16551656        #print "dict['vertices']",dict['vertices']
    16561657       
    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()),
    16611663                         '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()),
    16631666                         'test_Mesh2IOTriangulationDict failed. test vert ats')
    16641667
     
    17161719        #print "dict['vertices']",dict['vertices']
    17171720       
    1718         self.failUnless( dict['vertices'] == answer,
    1719                          'test_Mesh2IOTriangulationDict failed. test 2')
    1720 
    1721         self.failUnless( dict['vertices'] == verts,
    1722                          'test_Mesh2IOTriangulationDict failed. test vert')
    1723         self.failUnless( dict['vertex_attributes'] == vert_as,
    1724                          'test_Mesh2IOTriangulationDict failed. test vert ats')
    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]),
    17271730                        'test_Mesh2IODict failed. test 3')
    17281731       
    1729         self.failUnless( dict['segment_tags'] == seg_tags,
     1732        self.failUnless(dict['segment_tags'] == seg_tags,
    17301733                        'test_Mesh2IODict failed. test 3')
    17311734        #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]),
    17331736                        '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]),
    17351738                        'test_Mesh2IODict failed. test 6')
    17361739        #print "dict['triangle_tags'][0]", dict['triangle_tags'][0]
    1737         self.failUnless( dict['triangle_tags'][0] == "1.3",
    1738                          'test_Mesh2IODict failed. test 7')
     1740        self.failUnless(dict['triangle_tags'][0] == "1.3",
     1741                        'test_Mesh2IODict failed. test 7')
    17391742
    17401743        seg = m.getUserSegments()
     
    21982201        vert = m.get_user_vertices(absolute=True)
    21992202       
    2200         self.failUnless(num.alltrue(vert.flat == num.array(points).flat),
     2203        self.failUnless(num.alltrue(vert.flatten() ==
     2204                                    num.array(points).flatten()),
    22012205                        'FAILED!')
    22022206   
     
    23112315if __name__ == "__main__":
    23122316    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')
    23182317    runner = unittest.TextTestRunner() #verbosity=2)
    23192318    runner.run(suite)
  • branches/numpy/anuga/pmesh/test_mesh_interface.py

    r6199 r6304  
    11#!/usr/bin/env python
    2 #
     2
    33import tempfile
    44import unittest
     
    1313from anuga.coordinate_transforms.geo_reference import Geo_reference,DEFAULT_ZONE
    1414
     15
    1516class TestCase(unittest.TestCase):
    1617    def setUp(self):
    1718        pass
    18    
     19
    1920    def tearDown(self):
    2021        pass
     
    2324        x=-500
    2425        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
    3031        x_p = -10
    3132        y_p = -40
     
    3334        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)
    3435
    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
    5048        m = create_mesh_from_regions(polygon,
    5149                                     boundary_tags,
     
    5654
    5755        # Test the mesh instance
    58         self.failUnless(len(m.regions)==3,
    59                         'FAILED!')
     56        self.failUnless(len(m.regions)==3, 'FAILED!')
    6057        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!')
    7464
    7565        # Assuming the order of the region points is known.
     
    7767        # a black box)
    7868        poly_point = m.getRegions()[0]
    79        
    80         #print "poly_point", poly_point
    81         #print "polygon_absolute",polygon_absolute
    82          
     69
    8370        # poly_point values are relative to the mesh geo-ref
    8471        # 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),
    8774                        'FAILED!')
    88        
     75
    8976        # Assuming the order of the region points is known.
    9077        # (This isn't true, if you consider create_mesh_from_regions
    9178        # a black box)
    9279        poly_point = m.getRegions()[1]
    93        
    94         #print "poly_point", poly_point
    95         #print "polygon_absolute",polygon_absolute
    96          
     80
    9781        # poly_point values are relative to the mesh geo-ref
    9882        # 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],
    10084                                          inner1_polygon_absolute,
    101                                           closed = False),
     85                                          closed=False),
    10286                        'FAILED!')
    103        
     87
    10488        # Assuming the order of the region points is known.
    10589        # (This isn't true, if you consider create_mesh_from_regions
    10690        # a black box)
    10791        poly_point = m.getRegions()[2]
    108        
    109         #print "poly_point", poly_point
    110         #print "polygon_absolute",polygon_absolute
    111          
     92
    11293        # poly_point values are relative to the mesh geo-ref
    11394        # 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],
    11596                                          inner2_polygon_absolute,
    116                                           closed = False),
     97                                          closed=False),
    11798                        'FAILED!')
    118 
    11999
    120100    def test_create_mesh_from_regions_with_caching(self):
    121101        x=-500
    122102        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
    128108        x_p = -10
    129109        y_p = -40
     
    131111        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)
    132112
    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)]
    144124
    145125        interior_holes = None
     
    147127        # Clear cache first
    148128        from anuga.caching import cache
     129
    149130        cache(_create_mesh_from_regions,
    150131              (polygon, boundary_tags),
     
    159140              clear=1)
    160141
    161         #print polygon
    162         #print boundary_tags
    163        
    164142        m = create_mesh_from_regions(polygon,
    165143                                     boundary_tags,
     
    173151
    174152        # Test the mesh instance
    175         self.failUnless(len(m.regions)==3,
    176                         'FAILED!')
     153        self.failUnless(len(m.regions)==3, 'FAILED!')
    177154        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!')
    191161
    192162        # Assuming the order of the region points is known.
     
    194164        # a black box)
    195165        poly_point = m.getRegions()[0]
    196        
    197         #print "poly_point", poly_point
    198         #print "polygon_absolute",polygon_absolute
    199          
     166
    200167        # poly_point values are relative to the mesh geo-ref
    201168        # 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),
    204172                        'FAILED!')
    205        
     173
    206174        # Assuming the order of the region points is known.
    207175        # (This isn't true, if you consider create_mesh_from_regions
    208176        # a black box)
    209177        poly_point = m.getRegions()[1]
    210        
    211         #print "poly_point", poly_point
    212         #print "polygon_absolute",polygon_absolute
    213          
     178
    214179        # poly_point values are relative to the mesh geo-ref
    215180        # 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],
    217182                                          inner1_polygon_absolute,
    218                                           closed = False),
     183                                          closed=False),
    219184                        'FAILED!')
    220        
     185
    221186        # Assuming the order of the region points is known.
    222187        # (This isn't true, if you consider create_mesh_from_regions
    223188        # a black box)
    224189        poly_point = m.getRegions()[2]
    225        
    226         #print "poly_point", poly_point
    227         #print "polygon_absolute",polygon_absolute
    228          
     190
    229191        # poly_point values are relative to the mesh geo-ref
    230192        # 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],
    232194                                          inner2_polygon_absolute,
    233                                           closed = False),
     195                                          closed=False),
    234196                        'FAILED!')
    235 
    236197
    237198        # Now create m using cached values
     
    245206                                           use_cache=True)
    246207
    247 
    248 
    249        
    250208    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
    254211        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
    257214        x_p = -10
    258215        y_p = -40
     
    261218        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)
    262219
    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)]
    274231        m = create_mesh_from_regions(polygon,
    275232                                     boundary_tags,
     
    277234                                     interior_regions=interior_regions,
    278235                                     poly_geo_reference=geo_ref_poly)
    279        
    280236
    281237        # Test the mesh instance
    282         self.failUnless(len(m.regions)==3,
    283                         'FAILED!')
     238        self.failUnless(len(m.regions)==3, 'FAILED!')
    284239        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
    307250    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
    311253        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
    314256
    315257        x_p = -10
    316258        y_p = -40
    317259        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)]
    330272        m = create_mesh_from_regions(polygon,
    331273                                     boundary_tags,
    332274                                     10000000,
    333275                                     interior_regions=interior_regions)
    334        
    335276
    336277        # Test the mesh instance
    337         self.failUnless(len(m.regions)==3,
    338                         'FAILED!')
     278        self.failUnless(len(m.regions) == 3, 'FAILED!')
    339279        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!')
    360289
    361290    def test_create_mesh_from_regions4(self):
    362 
    363         file_name = tempfile.mktemp(".tsh")
    364        
     291        file_name = tempfile.mktemp('.tsh')
     292
    365293        # These are the absolute values
    366294        density_outer = 1000
    367         min_outer = 0 
     295        min_outer = 0
    368296        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
    372300        density_inner1 = 10000000
    373301        inner_buffer = 100
    374302        min_inner1 = min_outer + inner_buffer
    375303        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
    382309        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
    392316        m = importMeshFromFile(file_name)
    393        
    394         #print "file_name",file_name
     317
    395318        self.failUnless(len(m.getTriangulation()) <= 900,
    396319                        'Test mesh interface failed!')
    397320        self.failUnless(len(m.getTriangulation()) >= 200,
    398321                        '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
    408329        m = importMeshFromFile(file_name)
    409        
    410         #print "len(m.meshTriangles)",len(m.meshTriangles)
     330
    411331        self.failUnless(len(m.getTriangulation()) <= 100,
    412332                        'Test mesh interface failed!')
    413333
    414334        os.remove(file_name)
    415        
     335
    416336    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
    423342        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
    427346        density_inner1 = 1000
    428347        inner_buffer = 100
    429348        min_inner1 = min_outer + inner_buffer
    430349        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
    437355        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
    447363        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,
    451365                        'Test mesh interface failed!')
    452  
    453366        self.failUnless(len(m.getTriangulation()) >= 900,
    454367                        'Test mesh interface failed!')
    455368
    456369        os.remove(file_name)
    457        
     370
    458371    def test_create_mesh_from_regions6(self):
    459 
    460         file_name = tempfile.mktemp(".tsh")
    461        
     372        file_name = tempfile.mktemp('.tsh')
     373
    462374        # These are the absolute values
    463375        density_outer = 1000
    464         min_outer = 0 
     376        min_outer = 0
    465377        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]]
    468380
    469381        delta = 10
     
    471383        min_inner1 = min_outer + delta
    472384        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
    478389        min_inner2 = min_outer +  2*delta
    479390        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
    485396        interior_regions = [(inner1_polygon, density_inner1),
    486397                            (inner2_polygon, density_inner2)]
     
    491402                                 filename=file_name,
    492403                                 verbose=False)
    493        
     404
    494405        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,
    498407                        'Test mesh interface failed!')
    499  
    500408        self.failUnless(len(m.getTriangulation()) >= 900,
    501409                        'Test mesh interface failed!')
    502410
    503411        os.remove(file_name)
    504        
     412
    505413    def test_create_mesh_from_regions7(self):
    506 
    507         file_name = tempfile.mktemp(".tsh")
    508        
     414        file_name = tempfile.mktemp('.tsh')
     415
    509416        # These are the absolute values
    510417        density_outer = 1001
    511         min_outer = 0 
     418        min_outer = 0
    512419        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]]
    515422
    516423        delta = 10
     
    518425        min_inner1 = min_outer + delta
    519426        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
    525431        min_inner2 = min_outer +  2*delta
    526432        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 important
     433        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
    533439        # The last region added will be the region triangle uses,
    534440        # 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)]
    536443        create_mesh_from_regions(polygon_outer,
    537444                                 boundary_tags,
     
    540447                                 filename=file_name,
    541448                                 verbose=False)
    542        
     449
    543450        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,
    547452                        'Test mesh interface failed!')
    548  
    549453        self.failUnless(len(m.getTriangulation()) >= 2000,
    550454                        'Test mesh interface failed!')
     
    552456        os.remove(file_name)
    553457
    554        
    555458    def test_create_mesh_from_regions_interior_regions(self):
    556         """Test that create_mesh_from_regions fails when an interior region is
    557          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
    562465        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
    567470        # 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]]
    569472
    570473        interior_regions = [(inner_polygon, 5)]
     
    574477                                     interior_regions=interior_regions)
    575478
    576 
    577479        # 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]]
    580482        interior_regions = [[inner_polygon, 50], [inner_polygon1, 50]]
    581483
    582 
    583        
    584484        try:
    585485            m = create_mesh_from_regions(polygon,
     
    593493            msg = 'Interior polygon sticking outside bounding polygon should '
    594494            msg += 'cause an Exception to be raised'
    595             raise msg
     495            raise Exception, msg
    596496
    597497    def test_create_mesh_from_regions_interior_regions1(self):
    598         """Test that create_mesh_from_regions fails when an interior region is
    599          outside bounding polygon.       """
    600        
     498        '''Test that create_mesh_from_regions fails
     499        when an interior region is outside bounding polygon.
     500        '''
    601501
    602502        # These are the values
    603 
    604503        d0 = [310000, 7690000]
    605504        d1 = [280000, 7690000]
     
    609508        d5 = [300000, 7590000]
    610509        d6 = [340000, 7610000]
    611 
    612510        poly_all = [d0, d1, d2, d3, d4, d5, d6]
    613        
     511
    614512        i0 = [304000, 7607000]
    615513        i1 = [302000, 7605000]
     
    619517#        i4 = [310000, 7580000]
    620518        i5 = [307000, 7606000]
    621 
    622519        poly_onslow = [i0, i1, i2, i3, i4, i5]
    623520
    624         #Thevenard Island
     521        # Thevenard Island
    625522        j0 = [294000, 7629000]
    626523        j1 = [285000, 7625000]
    627524        j2 = [294000, 7621000]
    628525        j3 = [299000, 7625000]
    629 
    630526        poly_thevenard = [j0, j1, j2, j3]
    631527
    632         #med res around onslow
     528        # med res around onslow
    633529        l0 = [300000, 7610000]
    634530        l1 = [285000, 7600000]
    635531        l2 = [300000, 7597500]
    636         l3 = [310000, 7770000] #this one is outside
    637 #        l3 = [310000, 7630000] #this one is NOT outside
     532        l3 = [310000, 7770000] # this one is outside
     533#        l3 = [310000, 7630000] # this one is NOT outside
    638534        l4 = [315000, 7610000]
    639535        poly_coast = [l0, l1, l2, l3, l4]
    640536
    641         #general coast and local area to onslow region
     537        # general coast and local area to onslow region
    642538        m0 = [270000, 7581000]
    643539        m1 = [300000, 7591000]
     
    646542        m4 = [290000, 7640000]
    647543        m5 = [260000, 7600000]
    648 
    649544        poly_region = [m0, m1, m2, m3, m4, m5]
    650545
    651546        # 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
    657551        try:
    658552            m = create_mesh_from_regions(poly_all,
     
    666560            msg = 'Interior polygon sticking outside bounding polygon should '
    667561            msg += 'cause an Exception to be raised'
    668             raise msg
    669 
    670 
     562            raise Exception, msg
    671563
    672564    def FIXME_test_create_mesh_with_multiply_tagged_segments(self):
    673         """Test that create_mesh_from_regions fails when
     565        '''Test that create_mesh_from_regions fails when
    674566        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
    682571        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]}
    687574
    688575        # 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]]
    691577        interior_regions = [(inner_polygon, 5)]
    692578        m = create_mesh_from_regions(polygon,
    693579                                     boundary_tags,
    694580                                     10000000,
    695                                      interior_regions=interior_regions,verbose=False)
    696 
     581                                     interior_regions=interior_regions,
     582                                     verbose=False)
    697583
    698584        # 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]]
    700586        interior_regions = [(inner_polygon, 5)]
    701 
    702 
    703 
    704587        try:
    705588            m = create_mesh_from_regions(polygon,
     
    712595            msg = 'Tags are listed repeatedly, but create mesh from regions '
    713596            msg += 'does not cause an Exception to be raised'
    714             raise msg
    715 
    716        
    717 
     597            raise Exception, msg
    718598
    719599    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]]
    729606        x_p = -10
    730607        y_p = -40
     
    732609        geo_ref_poly = Geo_reference(zone, x_p, y_p)
    733610        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]}
    742616        m = create_mesh_from_regions(polygon,
    743617                                     boundary_tags,
    744618                                     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'
    749623        #m.export_mesh_file(fileName)
    750  
    751        
     624
    752625    def concept_create_mesh_from_regions_with_ungenerate(self):
    753626        x=0
    754627        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]]
    760632        x_p = -10
    761633        y_p = -40
     
    763635        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)
    764636
    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
    775647        max_area = 10000000
    776         interior_regions = [(inner1_polygon, 5),(inner2_polygon, 10)]
     648        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
    777649        m = create_mesh_from_regions(polygon,
    778650                                     boundary_tags,
     
    781653                                     poly_geo_reference=geo_ref_poly,
    782654                                     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\
    789661       90.0       90.0\n\
    790662       81.0       90.0\n\
     
    799671       10.0       80.0\n\
    800672END\n\
    801 END\n")
    802         file.close() 
    803        
     673END\n')
     674        file.close()
     675
    804676        m.import_ungenerate_file(fileName, tag='wall')
    805677        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)
    807679        m.export_mesh_file('b_test_mesh_iknterface.tsh')
    808680
    809681    def concept_ungenerateII(self):
    810        
    811682        from anuga.shallow_water import Domain, Reflective_boundary, \
    812683                            Dirichlet_boundary
     684
    813685        x=0
    814686        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]]
    820691        x_p = -10
    821692        y_p = -40
     
    823694        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)
    824695
    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
    835706        max_area = 1
    836         interior_regions = [(inner1_polygon, 5),(inner2_polygon, 10)]
     707        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
    837708        m = create_mesh_from_regions(polygon,
    838709                                     boundary_tags,
     
    841712                                     poly_geo_reference=geo_ref_poly,
    842713                                     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\
    849720       90.0       90.0\n\
    850721       81.0       90.0\n\
     
    859730       10.0       80.0\n\
    860731END\n\
    861 END\n")
    862         file.close() 
    863        
    864         m.import_ungenerate_file(fileName) #, tag='wall')
     732END\n')
     733        file.close()
     734
     735        m.import_ungenerate_file(fileName)      #, tag='wall')
    865736        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'
    868739        m.export_mesh_file(mesh_filename)
    869740
    870741        domain = Domain(mesh_filename, use_cache = False)
    871        
     742
    872743        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})
    875746        yieldstep = 0.1
    876747        finaltime = 10
    877         for t in domain.evolve(yieldstep, finaltime):   
     748        for t in domain.evolve(yieldstep, finaltime):
    878749            domain.write_time()
    879    
     750
    880751    def concept_ungenerateIII(self):
    881        
    882752        from anuga.shallow_water import Domain, Reflective_boundary, \
    883753                            Dirichlet_boundary
    884        
    885754        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
    898763        max_area = 1
    899         interior_regions = [(inner1_polygon, 5),(inner2_polygon, 10)]
     764        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]
    900765        m = create_mesh_from_regions(polygon,
    901766                                     boundary_tags,
    902767                                     max_area,
    903768                                     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\
    908773       90.0       90.0\n\
    909774       81.0       90.0\n\
     
    918783       10.0       80.0\n\
    919784END\n\
    920 END\n")
    921         file.close() 
    922        
    923         m.import_ungenerate_file(fileName) 
     785END\n')
     786        file.close()
     787
     788        m.import_ungenerate_file(fileName)
    924789        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'
    927792        m.export_mesh_file(mesh_filename)
    928793
    929         domain = Domain(mesh_filename, use_cache = False)
    930        
     794        domain = Domain(mesh_filename, use_cache=False)
     795
    931796        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})
    934799        yieldstep = 0.1
    935800        finaltime = 10
    936         for t in domain.evolve(yieldstep, finaltime):   
     801        for t in domain.evolve(yieldstep, finaltime):
    937802            domain.write_time()
    938803
    939            
    940        
    941804    def test_create_mesh_from_regions_check_segs(self):
    942         """Test that create_mesh_from_regions fails when an interior region is
    943          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
    948811        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
    953815        # 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]]
    956817        interior_regions = [(inner_polygon, 5)]
    957818        m = create_mesh_from_regions(polygon,
     
    960821                                     interior_regions=interior_regions)
    961822
    962         boundary_tags = {'walls':[0,1,3,4],'bom':[2]}
    963        
     823        boundary_tags = {'walls': [0,1,3,4], 'bom': [2]}
    964824        try:
    965825            m = create_mesh_from_regions(polygon,
     
    970830            pass
    971831        else:
    972             msg = 'segment out of bounds not caught '
    973             raise msg
    974 
    975        
     832            msg = 'Segment out of bounds not caught '
     833            raise Exception, msg
     834
     835
    976836#-------------------------------------------------------------
    977837if __name__ == "__main__":
    978838    suite = unittest.makeSuite(TestCase,'test')
    979     #suite = unittest.makeSuite(TestCase,'test_create_mesh_from_regions_check_segs')
    980839    runner = unittest.TextTestRunner() #verbosity=2)
    981840    runner.run(suite)
    982    
     841
  • branches/numpy/anuga/shallow_water/benchmark_sww2dem.py

    r6162 r6304  
    2525
    2626from Scientific.IO.NetCDF import NetCDFFile
    27 import Numeric as num
     27import numpy as num
    2828
    2929from anuga.fit_interpolate.interpolate import Interpolate
     
    101101    sww_fileName = tempfile.mktemp(".sww" )
    102102    # 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#
    104104    stage = elevation
    105105    ymomentum = elevation
     
    111111    sww.store_header(fid, 0,
    112112               len(mesh_dict['triangles']),
    113                len(mesh_dict["vertices"]),sww_precision=num.Float)
     113               len(mesh_dict["vertices"]),sww_precision=num.float)
    114114    sww.store_triangulation(fid,
    115115                      mesh_dict["vertices"], mesh_dict['triangles'],
  • branches/numpy/anuga/shallow_water/data_manager.py

    r6224 r6304  
    6161from os import sep, path, remove, mkdir, access, F_OK, W_OK, getcwd
    6262
    63 import Numeric as num
     63import numpy as num
    6464
    6565from Scientific.IO.NetCDF import NetCDFFile
     
    7676     default_minimum_storable_height
    7777from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
     78from anuga.config import netcdf_float, netcdf_float32, netcdf_int
    7879from anuga.config import max_float
    7980from anuga.utilities.numerical_tools import ensure_numeric,  mean
     
    343344        from Scientific.IO.NetCDF import NetCDFFile
    344345
    345         self.precision = num.Float32 #Use single precision for quantities
     346        self.precision = netcdf_float32 #Use single precision for quantities
    346347        self.recursion = recursion
    347348        self.mode = mode
     
    438439
    439440        # 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 )
    441442        self.writer.store_triangulation(fid,
    442443                                        points,
    443 #                                        V.astype(volumes.typecode()),
    444                                         V.astype(num.Float32),
     444                                        V.astype(num.float32),
    445445                                        Z,
    446446                                        points_georeference=\
     
    561561                # Define a zero vector of same size and type as A
    562562                # for use with momenta
    563                 null = num.zeros(num.size(A), A.typecode())
     563                null = num.zeros(num.size(A), A.dtype.char) #??#
    564564
    565565                # Get xmomentum where depth exceeds minimum_storable_height
     
    622622        from Scientific.IO.NetCDF import NetCDFFile
    623623
    624         self.precision = num.Float #Use full precision
     624        self.precision = netcdf_float #Use full precision
    625625
    626626        Data_format.__init__(self, domain, 'sww', mode)
     
    650650
    651651
    652             fid.createVariable('volumes', num.Int, ('number_of_volumes',
    653                                                     'number_of_vertices'))
     652            fid.createVariable('volumes', netcdf_int, ('number_of_volumes',
     653                                                       'number_of_vertices'))
    654654
    655655            fid.createVariable('time', self.precision, ('number_of_timesteps',))
     
    13041304
    13051305    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)
    13091309
    13101310    for i in range(M):
     
    13491349
    13501350    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)
    13541354
    13551355    for i, line in enumerate(lines):
     
    14091409# @param step Timestep stride.
    14101410def 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
    14121414    nettcdf file filename2
    14131415    """
     
    14261428    for name in infile.variables:
    14271429        var = infile.variables[name]
    1428         outfile.createVariable(name, var.typecode(), var.dimensions)
     1430        outfile.createVariable(name, var.dtype.char, var.dimensions)    #??#
    14291431
    14301432    # Copy the static variables
     
    14991501    Convert to NetCDF pts format which is
    15001502
    1501     points:  (Nx2) Float array
    1502     elevation: N Float array
     1503    points:  (Nx2) float array
     1504    elevation: N float array
    15031505    """
    15041506
     
    16581660
    16591661    # Variable definitions
    1660     outfile.createVariable('points', num.Float, ('number_of_points',
    1661                                                  'number_of_dimensions'))
    1662     outfile.createVariable('elevation', num.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',))
    16631665
    16641666    # Get handles to the variables
     
    16841686            newcols = lenv              # ncols_in_bounding_box
    16851687
    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)
    16881690
    16891691        local_index = 0
     
    18011803    Convert to NetCDF pts format which is
    18021804
    1803     points:  (Nx2) Float array
    1804     elevation: N Float array
     1805    points:  (Nx2) float array
     1806    elevation: N float array
    18051807    """
    18061808
     
    22452247        # Comment out for reduced memory consumption
    22462248        for name in ['stage', 'xmomentum', 'ymomentum']:
    2247             q = fid.variables[name][:].flat
     2249            q = fid.variables[name][:].flatten()
    22482250            if timestep is not None:
    22492251                q = q[timestep*len(x):(timestep+1)*len(x)]
    22502252            if verbose: print '    %s in [%f, %f]' %(name, min(q), max(q))
    22512253        for name in ['elevation']:
    2252             q = fid.variables[name][:].flat
     2254            q = fid.variables[name][:].flatten()
    22532255            if verbose: print '    %s in [%f, %f]' %(name, min(q), max(q))
    22542256
     
    22562258    if verbose: print 'Processing quantity %s' %quantity
    22572259
    2258     # Turn NetCDF objects into Numeric arrays
     2260    # Turn NetCDF objects into numeric arrays
    22592261    try:
    22602262        q = fid.variables[quantity][:]
     
    22692271        #q has a time component, must be reduced alongthe temporal dimension
    22702272        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)
    22722274
    22732275        if timestep is not None:
     
    23292331    y = y + yllcorner - newyllcorner
    23302332
    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)
    23322334    assert len(vertex_points.shape) == 2
    23332335
    2334     grid_points = num.zeros ((ncols*nrows, 2), num.Float)
     2336    grid_points = num.zeros ((ncols*nrows, 2), num.float)
    23352337
    23362338    for i in xrange(nrows):
     
    23592361    #Interpolate using quantity values
    23602362    if verbose: print 'Interpolating'
    2361     grid_values = interp.interpolate(q, grid_points).flat
     2363    grid_values = interp.interpolate(q, grid_points).flatten()
    23622364
    23632365    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))
    23662368
    23672369    #Assign NODATA_value to all points outside bounding polygon (from interpolation mesh)
     
    26312633    if verbose: print 'Processing quantity %s' % quantity
    26322634
    2633     # Turn NetCDF objects into Numeric arrays
     2635    # Turn NetCDF objects into numeric arrays
    26342636    quantity_dict = {}
    26352637    for name in fid.variables.keys():
     
    26442646        if verbose: print 'Reducing quantity %s' % quantity
    26452647
    2646         q_reduced = num.zeros(number_of_points, num.Float)
     2648        q_reduced = num.zeros(number_of_points, num.float)
    26472649        for k in range(number_of_points):
    26482650            q_reduced[k] = reduction(q[:,k])
     
    26582660
    26592661    # 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)
    26612663    assert len(vertex_points.shape) == 2
    26622664
     
    26672669    # Interpolate using quantity values
    26682670    if verbose: print 'Interpolating'
    2669     interpolated_values = interp.interpolate(q, data_points).flat
     2671    interpolated_values = interp.interpolate(q, data_points).flatten
    26702672
    26712673    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))
    26742676
    26752677    # Assign NODATA_value to all points outside bounding polygon
     
    28782880
    28792881    # variable definitions
    2880     fid.createVariable('elevation', num.Float, ('number_of_rows',
    2881                                                 'number_of_columns'))
     2882    fid.createVariable('elevation', netcdf_float, ('number_of_rows',
     2883                                                   'number_of_columns'))
    28822884
    28832885    # Get handles to the variables
     
    29592961    from Scientific.IO.NetCDF import NetCDFFile
    29602962
    2961     precision = num.Float
     2963    precision = num.float
    29622964
    29632965    msg = 'Must use latitudes and longitudes for minlat, maxlon etc'
     
    30783080    #        elevations = file_e.variables['ELEVATION'][kmin:kmax, lmin:lmax]
    30793081    #    elif latitudes2[0]==latitudes[-1] and latitudes2[-1]==latitudes[0]:
    3080     #        from Numeric import asarray
     3082    #        from numpy import asarray
    30813083    #        elevations=elevations.tolist()
    30823084    #        elevations.reverse()
    30833085    #        elevations=asarray(elevations)
    30843086    #    else:
    3085     #        from Numeric import asarray
     3087    #        from numpy import asarray
    30863088    #        elevations=elevations.tolist()
    30873089    #        elevations.reverse()
     
    31953197    sww.store_header(outfile, times, number_of_volumes,
    31963198                     number_of_points, description=description,
    3197                      verbose=verbose, sww_precision=num.Float)
     3199                     verbose=verbose, sww_precision=netcdf_float)
    31983200
    31993201    # Store
    32003202    from anuga.coordinate_transforms.redfearn import redfearn
    3201     x = num.zeros(number_of_points, num.Float)  #Easting
    3202     y = num.zeros(number_of_points, num.Float)  #Northing
     3203    x = num.zeros(number_of_points, num.float)  #Easting
     3204    y = num.zeros(number_of_points, num.float)  #Northing
    32033205
    32043206    if verbose: print 'Making triangular grid'
     
    32343236            volumes.append([v4,v3,v2]) #Lower element
    32353237
    3236     volumes = num.array(volumes, num.Int)      #array default#
     3238    volumes = num.array(volumes)
    32373239
    32383240    if origin is None:
     
    32553257    outfile.variables['z'][:] = z             #FIXME HACK for bacwards compat.
    32563258    outfile.variables['elevation'][:] = z
    3257     outfile.variables['volumes'][:] = volumes.astype(num.Int32) #For Opteron 64
     3259    outfile.variables['volumes'][:] = volumes.astype(num.int32) #For Opteron 64
    32583260
    32593261    #Time stepping
     
    33873389    d = len(q)
    33883390
    3389     T = num.zeros(N, num.Float)       # Time
    3390     Q = num.zeros((N, d), num.Float)  # Values
     3391    T = num.zeros(N, num.float)       # Time
     3392    Q = num.zeros((N, d), num.float)  # Values
    33913393
    33923394    for i, line in enumerate(lines):
     
    34243426    fid.createDimension('number_of_timesteps', len(T))
    34253427
    3426     fid.createVariable('time', num.Float, ('number_of_timesteps',))
     3428    fid.createVariable('time', netcdf_float, ('number_of_timesteps',))
    34273429
    34283430    fid.variables['time'][:] = T
     
    34343436            name = 'Attribute%d' % i
    34353437
    3436         fid.createVariable(name, num.Float, ('number_of_timesteps',))
     3438        fid.createVariable(name, netcdf_float, ('number_of_timesteps',))
    34373439        fid.variables[name][:] = Q[:,i]
    34383440
     
    35053507    time_interp = get_time_interp(time,t)
    35063508
    3507     # Get the variables as Numeric arrays
     3509    # Get the variables as numeric arrays
    35083510    x = fid.variables['x'][:]                   # x-coordinates of vertices
    35093511    y = fid.variables['y'][:]                   # y-coordinates of vertices
     
    35183520    # FIXME (Ole): Something like this might be better:
    35193521    #                 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)
    35213523
    35223524    conserved_quantities = []
     
    37063708# @param boundary
    37073709def weed(coordinates, volumes, boundary=None):
    3708     if type(coordinates) == num.ArrayType:
     3710    if isinstance(coordinates, num.ndarray):
    37093711        coordinates = coordinates.tolist()
    3710     if type(volumes) == num.ArrayType:
     3712    if isinstance(volumes, num.ndarray):
    37113713        volumes = volumes.tolist()
    37123714
     
    38543856
    38553857    # variable definition
    3856     outfile.createVariable('elevation', num.Float, ('number_of_points',))
     3858    outfile.createVariable('elevation', netcdf_float, ('number_of_points',))
    38573859
    38583860    # Get handle to the variable
     
    38673869
    38683870        lower_index = global_index
    3869         telev = num.zeros(ncols_new, num.Float)
     3871        telev = num.zeros(ncols_new, num.float)
    38703872        local_index = 0
    38713873        trow = i * cellsize_ratio
     
    39953997    from anuga.coordinate_transforms.redfearn import redfearn
    39963998
    3997     precision = num.Float # So if we want to change the precision its done here
     3999    precision = netcdf_float # So if we want to change the precision its done here
    39984000
    39994001    # go in to the bath dir and load the only file,
     
    40964098    #################################
    40974099
    4098     outfile.createVariable('volumes', num.Int, ('number_of_volumes',
    4099                                                 'number_of_vertices'))
     4100    outfile.createVariable('volumes', netcdf_int, ('number_of_volumes',
     4101                                                   'number_of_vertices'))
    41004102
    41014103    outfile.createVariable('time', precision, ('number_of_timesteps',))
     
    41134115    from anuga.coordinate_transforms.redfearn import redfearn
    41144116
    4115     x = num.zeros(number_of_points, num.Float)  #Easting
    4116     y = num.zeros(number_of_points, num.Float)  #Northing
     4117    x = num.zeros(number_of_points, num.float)  #Easting
     4118    y = num.zeros(number_of_points, num.float)  #Northing
    41174119
    41184120    if verbose: print 'Making triangular grid'
     
    41504152            volumes.append([v4,v2,v3]) #Lower element
    41514153
    4152     volumes = num.array(volumes, num.Int)      #array default#
     4154    volumes = num.array(volumes)
    41534155
    41544156    geo_ref = Geo_reference(refzone, min(x), min(y))
     
    41754177    outfile.variables['z'][:] = z
    41764178    outfile.variables['elevation'][:] = z
    4177     outfile.variables['volumes'][:] = volumes.astype(num.Int32) # On Opteron 64
     4179    outfile.variables['volumes'][:] = volumes.astype(num.int32) # On Opteron 64
    41784180
    41794181    stage = outfile.variables['stage']
     
    43674369lat_name = 'LAT'
    43684370time_name = 'TIME'
    4369 precision = num.Float # So if we want to change the precision its done here
     4371precision = netcdf_float # So if we want to change the precision its done here
    43704372
    43714373##
     
    46484650    lonlatdep = p_array.array('f')
    46494651    lonlatdep.read(mux_file, columns * points_num)
    4650     lonlatdep = num.array(lonlatdep, typecode=num.Float)
     4652    lonlatdep = num.array(lonlatdep, dtype=num.float)
    46514653    lonlatdep = num.reshape(lonlatdep, (points_num, columns))
    46524654
     
    46554657    lon_sorted.sort()
    46564658
    4657     if not lon == lon_sorted:
     4659    if not num.alltrue(lon == lon_sorted):
    46584660        msg = "Longitudes in mux file are not in ascending order"
    46594661        raise IOError, msg
     
    46614663    lat_sorted = list(lat)
    46624664    lat_sorted.sort()
    4663 
    4664 # UNUSED?
    4665 ##    if not lat == lat_sorted:
    4666 ##        msg = "Latitudes in mux file are not in ascending order"
    46674665
    46684666    nc_file = Write_nc(quantity,
     
    46774675        hz_p_array = p_array.array('f')
    46784676        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)
    46804678        hz_p = num.reshape(hz_p, (len(lon), len(lat)))
    46814679        hz_p = num.transpose(hz_p)  # mux has lat varying fastest, nc has long v.f.
     
    47754773    QUANTITY = 2
    47764774
    4777     long_lat_dep = ensure_numeric(long_lat_dep, num.Float)
     4775    long_lat_dep = ensure_numeric(long_lat_dep, num.float)
    47784776
    47794777    num_points = long_lat_dep.shape[0]
     
    48134811    # FIXME - make this faster/do this a better way
    48144812    # use numeric transpose, after reshaping the quantity vector
    4815     quantity = num.zeros(num_points, num.Float)
     4813    quantity = num.zeros(num_points, num.float)
    48164814
    48174815    for lat_i, _ in enumerate(lat):
     
    52665264
    52675265    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))
    52705268
    52715269    volumes = mesh_dic['generatedtrianglelist']
     
    52855283    sww = Write_sww()
    52865284    sww.store_header(outfile, times, len(volumes), len(points_utm),
    5287                      verbose=verbose, sww_precision=num.Float)
     5285                     verbose=verbose, sww_precision=netcdf_float)
    52885286    outfile.mean_stage = mean_stage
    52895287    outfile.zscale = zscale
     
    53095307                                 xmomentum=xmomentum,
    53105308                                 ymomentum=ymomentum,
    5311                                  sww_precision=num.Float)
     5309                                 sww_precision=num.float)
    53125310        j += 1
    53135311
     
    53565354    numSrc = len(filenames)
    53575355
    5358     file_params = -1 * num.ones(3, num.Float)                    # [nsta,dt,nt]
     5356    file_params = -1 * num.ones(3, num.float)                    # [nsta,dt,nt]
    53595357
    53605358    # Convert verbose to int C flag
     
    53655363
    53665364    if weights is None:
    5367         weights = num.ones(numSrc)
     5365        weights = num.ones(numSrc, num.int)     #array default#
    53685366
    53695367    if permutation is None:
    5370         permutation = ensure_numeric([], num.Float)
     5368        permutation = ensure_numeric([], num.float)
    53715369
    53725370    # Call underlying C implementation urs2sts_ext.c
     
    54165414
    54175415    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)
    54225420
    54235421    starttime = 1e16
     
    55435541    if weights is None:
    55445542        # Default is equal weighting
    5545         weights = num.ones(numSrc, num.Float) / numSrc
     5543        weights = num.ones(numSrc, num.float) / numSrc
    55465544    else:
    55475545        weights = ensure_numeric(weights)
     
    56655663    # 0 to number_of_points-1
    56665664    if permutation is None:
    5667         permutation = num.arange(number_of_points, typecode=num.Int)
     5665        permutation = num.arange(number_of_points, dtype=num.int)
    56685666
    56695667    # NetCDF file definition
     
    56795677                     description=description,
    56805678                     verbose=verbose,
    5681                      sts_precision=num.Float)
     5679                     sts_precision=netcdf_float)
    56825680
    56835681    # Store
    56845682    from anuga.coordinate_transforms.redfearn import redfearn
    56855683
    5686     x = num.zeros(number_of_points, num.Float)  # Easting
    5687     y = num.zeros(number_of_points, num.Float)  # Northing
     5684    x = num.zeros(number_of_points, num.float)  # Easting
     5685    y = num.zeros(number_of_points, num.float)  # Northing
    56885686
    56895687    # Check zone boundaries
     
    57165714
    57175715    elevation = num.resize(elevation, outfile.variables['elevation'][:].shape)
    5718     outfile.variables['permutation'][:] = permutation.astype(num.Int32) # Opteron 64
     5716    outfile.variables['permutation'][:] = permutation.astype(num.int32) # Opteron 64
    57195717    outfile.variables['x'][:] = x - geo_ref.get_xllcorner()
    57205718    outfile.variables['y'][:] = y - geo_ref.get_yllcorner()
     
    58215819    # @param smoothing True if smoothing is to be used.
    58225820    # @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)
    58245822    # @param verbose True if this function is to be verbose.
    58255823    # @note If 'times' is a list, the info will be made relative.
     
    58325830                     smoothing=True,
    58335831                     order=1,
    5834                      sww_precision=num.Float32,
     5832                     sww_precision=netcdf_float32,
    58355833                     verbose=False):
    58365834        """Write an SWW file header.
     
    58655863        # This is being used to seperate one number from a list.
    58665864        # 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):
    58685866            number_of_times = len(times)
    58695867            times = ensure_numeric(times)
     
    59145912        outfile.createVariable('z', sww_precision, ('number_of_points',))
    59155913
    5916         outfile.createVariable('volumes', num.Int, ('number_of_volumes',
    5917                                                     'number_of_vertices'))
     5914        outfile.createVariable('volumes', netcdf_int, ('number_of_volumes',
     5915                                                       'number_of_vertices'))
    59185916
    59195917        # Doing sww_precision instead of Float gives cast errors.
    5920         outfile.createVariable('time', num.Float,
     5918        outfile.createVariable('time', netcdf_float,
    59215919                               ('number_of_timesteps',))
    59225920
     
    59325930            #outfile.variables[q+Write_sww.RANGE][1] = -max_float # Max
    59335931
    5934         if type(times) is list or type(times) is num.ArrayType:
     5932        if type(times) is list or isinstance(times, num.ndarray):
    59355933            outfile.variables['time'][:] = times    #Store time relative
    59365934
     
    60356033        outfile.variables['z'][:] = elevation
    60366034        outfile.variables['elevation'][:] = elevation  #FIXME HACK
    6037         outfile.variables['volumes'][:] = volumes.astype(num.Int32) #On Opteron 64
     6035        outfile.variables['volumes'][:] = volumes.astype(num.int32) #On Opteron 64
    60386036
    60396037        q = 'elevation'
     
    60516049    # @param verbose True if this function is to be verbose.
    60526050    # @param **quant
    6053     def store_quantities(self, outfile, sww_precision=num.Float32,
     6051    def store_quantities(self, outfile, sww_precision=num.float32,
    60546052                         slice_index=None, time=None,
    60556053                         verbose=False, **quant):
     
    62366234    # @param number_of_points The number of URS gauge sites.
    62376235    # @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).
    62396237    # @param verbose True if this function is to be verbose.
    62406238    # @note If 'times' is a list, the info will be made relative.
     
    62446242                     number_of_points,
    62456243                     description='Converted from URS mux2 format',
    6246                      sts_precision=num.Float32,
     6244                     sts_precision=netcdf_float32,
    62476245                     verbose=False):
    62486246        """
     
    62676265        # This is being used to seperate one number from a list.
    62686266        # 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):
    62706268            number_of_times = len(times)
    62716269            times = ensure_numeric(times)
     
    62876285
    62886286        # Variable definitions
    6289         outfile.createVariable('permutation', num.Int, ('number_of_points',))
     6287        outfile.createVariable('permutation', netcdf_int, ('number_of_points',))
    62906288        outfile.createVariable('x', sts_precision, ('number_of_points',))
    62916289        outfile.createVariable('y', sts_precision, ('number_of_points',))
     
    63026300
    63036301        # Doing sts_precision instead of Float gives cast errors.
    6304         outfile.createVariable('time', num.Float, ('number_of_timesteps',))
     6302        outfile.createVariable('time', netcdf_float, ('number_of_timesteps',))
    63056303
    63066304        for q in Write_sts.sts_quantities:
     
    63146312            outfile.variables[q + Write_sts.RANGE][1] = -max_float # Max
    63156313
    6316         if type(times) is list or type(times) is num.ArrayType:
     6314        if type(times) is list or isinstance(times, num.ndarray):
    63176315            outfile.variables['time'][:] = times    #Store time relative
    63186316
     
    64236421    # @param verboseTrue if this function is to be verbose.
    64246422    # @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,
    64266424                         slice_index=None, time=None,
    64276425                         verbose=False, **quant):
     
    65146512        lonlatdep = p_array.array('f')
    65156513        lonlatdep.read(mux_file, columns * self.points_num)
    6516         lonlatdep = num.array(lonlatdep, typecode=num.Float)
     6514        lonlatdep = num.array(lonlatdep, dtype=num.float)
    65176515        lonlatdep = num.reshape(lonlatdep, (self.points_num, columns))
    65186516        self.lonlatdep = lonlatdep
     
    65506548        hz_p_array = p_array.array('f')
    65516549        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)
    65536551        self.iter_time_step += 1
    65546552
     
    66956693    # array to store data, number in there is to allow float...
    66966694    # i'm sure there is a better way!
    6697     data = num.array([], typecode=num.Float)
     6695    data = num.array([], dtype=num.float)
    66986696    data = num.resize(data, ((len(lines)-1), len(header_fields)))
    66996697
     
    68616859    time += fid.starttime[0]
    68626860
    6863     # Get the variables as Numeric arrays
     6861    # Get the variables as numeric arrays
    68646862    x = fid.variables['x'][:]                   # x-coordinates of nodes
    68656863    y = fid.variables['y'][:]                   # y-coordinates of nodes
     
    68706868
    68716869    # 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)
    68736871    triangles = fid.variables['volumes'][:]
    68746872
     
    72937291
    72947292        # 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)
    72977295
    72987296        # Here's where one could convert nodal information to centroid
     
    73117309            # and call it here
    73127310
    7313             points = num.concatenate((x[:,num.NewAxis], y[:,num.NewAxis]), axis=1)
     7311            points = num.concatenate((x[:,num.newaxis], y[:,num.newaxis]), axis=1)
    73147312
    73157313            point_indices = inside_polygon(points, polygon)
  • branches/numpy/anuga/shallow_water/eq_test.py

    r6162 r6304  
    6666   
    6767from anuga.abstract_2d_finite_volumes.util import file_function
    68 import Numeric as num
     68import numpy as num
    6969from pylab import plot, ion, hold,savefig
    7070
     
    7575
    7676y = 10000
    77 points=num.array([[0]*2]*max, num.Int)      #array default#
     77points=num.array([[0]*2]*max)
    7878print points
    7979half_max_skip=(max*skip)/2
     
    8787number_points = profile_lenght/interval
    8888y = 10000
    89 points=num.array([[0]*2]*number_points, num.Int)      #array default#
     89points=num.array([[0]*2]*number_points)
    9090print points
    9191half_profile=profile_lenght/2
  • branches/numpy/anuga/shallow_water/eqf_v2.py

    r4436 r6304  
    2626"""
    2727
     28import numpy as num
     29
     30
    2831def earthquake_tsunami(length, width, strike, depth, \
    2932                       dip, x0=0.0, y0=0.0, slip=1.0, rake=90.,\
     
    110113
    111114        from math import sin, cos, radians, exp, cosh
    112         from Numeric import zeros, Float
    113115        #from okada import okadatest
    114116
     
    142144        #z1 = okada(xr,yr,depth,length,width,dip,rake,slip)
    143145
    144         z2 = zeros(N, Float)
     146        z2 = num.zeros(N, num.float)
    145147        alp = 0.5
    146148        disl3 = 0.0
     
    182184        """                                                                   
    183185       
    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)
    187188       
    188189        F0 = 0.0
  • branches/numpy/anuga/shallow_water/shallow_water_domain.py

    r6190 r6304  
    8080# $LastChangedBy$
    8181
    82 import Numeric as num
     82import numpy as num
    8383
    8484from anuga.abstract_2d_finite_volumes.neighbour_mesh import segment_midpoints
     
    10811081        self.normals = domain.normals
    10821082
    1083         self.conserved_quantities = num.zeros(3, num.Float)
     1083        self.conserved_quantities = num.zeros(3, num.float)
    10841084
    10851085    def __repr__(self):
     
    15011501    if callable(f):
    15021502        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)
    15051505        try:
    15061506            q = f(1.0, x=x, y=y)
     
    15111511
    15121512        try:
    1513             q = num.array(q, num.Float)
     1513            q = num.array(q, num.float)
    15141514        except:
    15151515            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'
    15171517            msg += 'Specified function should return either list or array.'
    15181518            raise msg
     
    15201520        # Is this really what we want?
    15211521        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)
    15231524        assert len(q) == N, msg
    15241525
     
    16221623
    16231624            try:
    1624                 s_vec = self.speed * num.ones(N, num.Float)
     1625                s_vec = self.speed * num.ones(N, num.float)
    16251626            except:
    16261627                msg = 'Speed must be either callable or a scalar: %s' %self.s
     
    16351636
    16361637            try:
    1637                 phi_vec = self.phi * num.ones(N, num.Float)
     1638                phi_vec = self.phi * num.ones(N, num.float)
    16381639            except:
    16391640                msg = 'Angle must be either callable or a scalar: %s' %self.phi
     
    17121713                 quantity_name,
    17131714                 rate=0.0,
    1714                 center=None, radius=None,
     1715                center=None, radius=None,
    17151716                 polygon=None,
    17161717                 default_rate=None,
     
    17751776                assert is_inside_polygon(point, bounding_polygon), msg
    17761777
    1777        
    17781778        if polygon is not None:
    17791779
     
    18351835           
    18361836        # Check and store default_rate
    1837         msg = 'Keyword argument default_rate must be either None '
    1838         msg += 'or a function of time.\n I got %s' %(str(default_rate))
     1837        msg = 'Keyword argument default_rate must be either None '
     1838        msg += 'or a function of time.\n I got %s' %(str(default_rate))
    18391839        assert default_rate is None or \
    18401840               type(default_rate) in [IntType, FloatType] or \
     
    19201920       
    19211921        """
    1922         if callable(self.rate):
    1923             rate = self.rate(t)
    1924         else:
    1925             rate = self.rate
     1922        if callable(self.rate):
     1923            rate = self.rate(t)
     1924        else:
     1925            rate = self.rate
    19261926
    19271927        return rate
     
    19641964   
    19651965    Used for implementing Rainfall over the entire domain.
    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)
     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)
    19711971   
    19721972    Rainfall(rain)
     
    19741974    domain   
    19751975    rain [mm/s]:  Total rain rate over the specified domain. 
    1976                   NOTE: Raingauge Data needs to reflect the time step.
    1977                   IE: if Gauge is mm read at a time step, then the input
     1976                  NOTE: Raingauge Data needs to reflect the time step.
     1977                  IE: if Gauge is mm read at a time step, then the input
    19781978                  here is as mm/(timeStep) so 10mm in 5minutes becomes
    19791979                  10/(5x60) = 0.0333mm/s.
    1980        
    1981        
     1980
    19821981                  This parameter can be either a constant or a
    19831982                  function of time. Positive values indicate inflow,
     
    19921991    Examples
    19931992    How to put them in a run File...
    1994        
     1993
    19951994    #------------------------------------------------------------------------
    19961995    # Setup specialised forcing terms
     
    20092008    def __init__(self,
    20102009                 domain,
    2011                 rate=0.0,
    2012                 center=None, radius=None,
     2010                rate=0.0,
     2011                center=None, radius=None,
    20132012                 polygon=None,
    20142013                 default_rate=None,                 
     
    20712070    # The outflow area is 0.07**2*pi=0.0154 m^2
    20722071    # This corresponds to a rate of change of 0.003/0.0154 = 0.2 m/s
    2073     #                                    
     2072    #         
    20742073    Inflow((0.7, 0.4), 0.07, -0.003)
    20752074
     
    20982097    def __init__(self,
    20992098                 domain,
    2100                 rate=0.0,
    2101                 center=None, radius=None,
     2099                rate=0.0,
     2100                center=None, radius=None,
    21022101                 polygon=None,
    21032102                 default_rate=None,
     
    21232122        """
    21242123
    2125         if callable(self.rate):
    2126             _rate = self.rate(t)/self.exchange_area
    2127         else:
    2128             _rate = self.rate/self.exchange_area
     2124        if callable(self.rate):
     2125            _rate = self.rate(t)/self.exchange_area
     2126        else:
     2127            _rate = self.rate/self.exchange_area
    21292128
    21302129        return _rate
  • branches/numpy/anuga/shallow_water/shallow_water_ext.c

    r5967 r6304  
    1515
    1616#include "Python.h"
    17 #include "Numeric/arrayobject.h"
     17#include "numpy/arrayobject.h"
    1818#include "math.h"
    1919#include <stdio.h>
  • branches/numpy/anuga/shallow_water/smf.py

    r6157 r6304  
    4747"""
    4848
    49 import Numeric as num
     49import numpy as num
    5050
    5151
     
    388388
    389389        from math import sin, cos, radians, exp, cosh
    390 #        from Numeric import zeros, Float
    391390
    392391        #ensure vectors x and y have the same length
     
    416415        yr = ((x-x0) * sina + (y-y0) * cosa) + y0
    417416
    418         z = num.zeros(N, num.Float)
     417        z = num.zeros(N, num.float)
    419418        maxz = 0.0
    420419        minz = 0.0
  • branches/numpy/anuga/shallow_water/test_all.py

    r3691 r6304  
    7878if __name__ == '__main__':   
    7979    suite = regressionTest()
    80     runner = unittest.TextTestRunner() #(verbosity=2)
     80    runner = unittest.TextTestRunner() #verbosity=2)
    8181    runner.run(suite)
  • branches/numpy/anuga/shallow_water/test_data_manager.py

    r6224 r6304  
    77import unittest
    88import copy
    9 import Numeric as num
     9import numpy as num
    1010               
    1111from anuga.utilities.numerical_tools import mean
     
    2525from anuga.utilities.system_tools import get_pathname_from_package
    2626from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
     27from anuga.config import netcdf_float
    2728
    2829# This is needed to run the tests of local functions
     
    6768        #Initial condition - with jumps
    6869        bed = domain.quantities['elevation'].vertex_values
    69         stage = num.zeros(bed.shape, num.Float)
     70        stage = num.zeros(bed.shape, num.float)
    7071
    7172        h = 0.3
     
    109110
    110111            fid.createDimension(long_name,nx)
    111             fid.createVariable(long_name,'d',(long_name,))
     112            fid.createVariable(long_name,netcdf_float,(long_name,))
    112113            fid.variables[long_name].point_spacing='uneven'
    113114            fid.variables[long_name].units='degrees_east'
     
    115116
    116117            fid.createDimension(lat_name,ny)
    117             fid.createVariable(lat_name,'d',(lat_name,))
     118            fid.createVariable(lat_name,netcdf_float,(lat_name,))
    118119            fid.variables[lat_name].point_spacing='uneven'
    119120            fid.variables[lat_name].units='degrees_north'
     
    121122
    122123            fid.createDimension('TIME',six)
    123             fid.createVariable('TIME','d',('TIME',))
     124            fid.createVariable('TIME',netcdf_float,('TIME',))
    124125            fid.variables['TIME'].point_spacing='uneven'
    125126            fid.variables['TIME'].units='seconds'
     
    129130            name = ext[1:3].upper()
    130131            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))
    132133            fid.variables[name].units='CENTIMETERS'
    133134            fid.variables[name].missing_value=-1.e+034
     
    189190        V = fid.variables['volumes']
    190191
    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())
    194195
    195196        P = len(self.domain)
     
    521522        #Check contents
    522523        #Get NetCDF
    523         fid = NetCDFFile(sww.filename, inetcdf_mode_r)
     524        fid = NetCDFFile(sww.filename, netcdf_mode_r)
    524525
    525526        # Get the variables
     
    589590            if t == 0.0:
    590591                assert num.allclose(stage, self.initial_stage)
    591                 assert num.allclose(stage_file[:], stage.flat)
     592                assert num.allclose(stage_file[:], stage.flatten())
    592593            else:
    593594                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())
    595596
    596597            fid.close()
     
    855856        xvec = range(10)
    856857        #z = range(100)
    857         z = num.zeros(100)
     858        z = num.zeros(100, num.int)     #array default#
    858859        NODATA_value = -9999
    859860        count = -1
     
    914915
    915916        #create new reference points
    916         newz = num.zeros(19)
     917        newz = num.zeros(19, num.int)       #array default#
    917918        newz[0:2] = ref_elevation[32:34]
    918919        newz[2:5] = ref_elevation[35:38]
     
    985986        xvec = range(10)
    986987        #z = range(100)
    987         z = num.zeros(100)
     988        z = num.zeros(100, num.int)     #array default#
    988989        NODATA_value = -9999
    989990        count = -1
     
    10441045
    10451046        #create new reference points
    1046         newz = num.zeros(14)
     1047        newz = num.zeros(14, num.int)       #array default#
    10471048        newz[0:2] = ref_elevation[32:34]
    10481049        newz[2:5] = ref_elevation[35:38]
     
    25432544
    25442545        bed = domain.quantities['elevation'].vertex_values
    2545         stage = num.zeros(bed.shape, num.Float)
     2546        stage = num.zeros(bed.shape, num.float)
    25462547
    25472548        h = 0.3
     
    27932794
    27942795        # 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 )
    27962797        sww2pts(self.domain.get_name(),
    27972798                quantity = 'elevation',
     
    31713172        for fid in [fid1,fid2,fid3]:
    31723173            fid.createDimension(long_name,nx)
    3173             fid.createVariable(long_name,'d',(long_name,))
     3174            fid.createVariable(long_name,netcdf_float,(long_name,))
    31743175            fid.variables[long_name].point_spacing='uneven'
    31753176            fid.variables[long_name].units='degrees_east'
     
    31773178
    31783179            fid.createDimension(lat_name,ny)
    3179             fid.createVariable(lat_name,'d',(lat_name,))
     3180            fid.createVariable(lat_name,netcdf_float,(lat_name,))
    31803181            fid.variables[lat_name].point_spacing='uneven'
    31813182            fid.variables[lat_name].units='degrees_north'
     
    31833184
    31843185            fid.createDimension(time_name,2)
    3185             fid.createVariable(time_name,'d',(time_name,))
     3186            fid.createVariable(time_name,netcdf_float,(time_name,))
    31863187            fid.variables[time_name].point_spacing='uneven'
    31873188            fid.variables[time_name].units='seconds'
     
    31923193        for fid in [fid4]:
    31933194            fid.createDimension(long_name,nx)
    3194             fid.createVariable(long_name,'d',(long_name,))
     3195            fid.createVariable(long_name,netcdf_float,(long_name,))
    31953196            fid.variables[long_name].point_spacing='uneven'
    31963197            fid.variables[long_name].units='degrees_east'
     
    31983199
    31993200            fid.createDimension(lat_name,ny)
    3200             fid.createVariable(lat_name,'d',(lat_name,))
     3201            fid.createVariable(lat_name,netcdf_float,(lat_name,))
    32013202            fid.variables[lat_name].point_spacing='uneven'
    32023203            fid.variables[lat_name].units='degrees_north'
     
    32223223
    32233224        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))
    32253226          fid.variables[name[fid]].point_spacing='uneven'
    32263227          fid.variables[name[fid]].units=units[fid]
     
    32303231
    32313232        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))
    32333234            fid.variables[name[fid]].point_spacing='uneven'
    32343235            fid.variables[name[fid]].units=units[fid]
     
    33353336        for fid in [fid1,fid2,fid3]:
    33363337            fid.createDimension(long_name,nx)
    3337             fid.createVariable(long_name,'d',(long_name,))
     3338            fid.createVariable(long_name,netcdf_float,(long_name,))
    33383339            fid.variables[long_name].point_spacing='uneven'
    33393340            fid.variables[long_name].units='degrees_east'
     
    33413342
    33423343            fid.createDimension(lat_name,ny)
    3343             fid.createVariable(lat_name,'d',(lat_name,))
     3344            fid.createVariable(lat_name,netcdf_float,(lat_name,))
    33443345            fid.variables[lat_name].point_spacing='uneven'
    33453346            fid.variables[lat_name].units='degrees_north'
     
    33473348
    33483349            fid.createDimension(time_name,2)
    3349             fid.createVariable(time_name,'d',(time_name,))
     3350            fid.createVariable(time_name,netcdf_float,(time_name,))
    33503351            fid.variables[time_name].point_spacing='uneven'
    33513352            fid.variables[time_name].units='seconds'
     
    33563357        for fid in [fid4]:
    33573358            fid.createDimension(long_name,nx)
    3358             fid.createVariable(long_name,'d',(long_name,))
     3359            fid.createVariable(long_name,netcdf_float,(long_name,))
    33593360            fid.variables[long_name].point_spacing='uneven'
    33603361            fid.variables[long_name].units='degrees_east'
     
    33623363
    33633364            fid.createDimension(lat_name,ny)
    3364             fid.createVariable(lat_name,'d',(lat_name,))
     3365            fid.createVariable(lat_name,netcdf_float,(lat_name,))
    33653366            fid.variables[lat_name].point_spacing='uneven'
    33663367            fid.variables[lat_name].units='degrees_north'
     
    33863387
    33873388        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))
    33893390          fid.variables[name[fid]].point_spacing='uneven'
    33903391          fid.variables[name[fid]].units=units[fid]
     
    33943395
    33953396        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))
    33973398            fid.variables[name[fid]].point_spacing='uneven'
    33983399            fid.variables[name[fid]].units=units[fid]
     
    39663967        fid.createDimension('number_of_points', nrows*ncols)
    39673968
    3968         fid.createVariable('elevation', num.Float, ('number_of_points',))
     3969        fid.createVariable('elevation', netcdf_float, ('number_of_points',))
    39693970
    39703971        elevation = fid.variables['elevation']
     
    39933994
    39943995        #generate a stencil for computing the decimated values
    3995         stencil = num.ones((3,3), num.Float) / 9.0
     3996        stencil = num.ones((3,3), num.float) / 9.0
    39963997
    39973998        decimate_dem(root, stencil=stencil, cellsize_new=100)
     
    40494050        fid.createDimension('number_of_points', nrows*ncols)
    40504051
    4051         fid.createVariable('elevation', num.Float, ('number_of_points',))
     4052        fid.createVariable('elevation', netcdf_float, ('number_of_points',))
    40524053
    40534054        elevation = fid.variables['elevation']
     
    40874088
    40884089        #generate a stencil for computing the decimated values
    4089         stencil = num.ones((3,3), num.Float) / 9.0
     4090        stencil = num.ones((3,3), num.float) / 9.0
    40904091
    40914092        decimate_dem(root, stencil=stencil, cellsize_new=100)
     
    49504951
    49514952        ## 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]])
    49534954        kmin, kmax, lmin, lmax = data_manager._get_min_max_indexes(
    49544955            latitudes,longitudes,
     
    49634964        #print "longitudes_news",longitudes_news
    49644965
    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')
    49714971
    49724972    def test_get_min_max_indexes_lat_ascending(self):
     
    50105010        longitudes = [148,149,150,151]
    50115011
    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]])
    50135013
    50145014        # k - lat
     
    50315031        #print "longitudes_new",longitudes_new
    50325032
    5033         self.failUnless(latitudes_new == [-30, -35, -40] and \
     5033        self.failUnless(latitudes_new == [-30, -35, -40] and
    50345034                        longitudes_new == [148, 149,150],
    5035                          'failed')
    5036         self.failUnless(m2d == [[0,1,2],[4,5,6],[8,9,10]],
    5037                          'failed')
     5035                        'failed')
     5036        self.failUnless(num.alltrue(m2d == [[0,1,2],[4,5,6],[8,9,10]]),
     5037                        'failed')
    50385038
    50395039    def test_get_min_max_indexes3(self):
     
    54775477            quantities_init[i] = ensure_numeric(quantities_init[i])
    54785478            #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)
    54805480            for time in range(time_step_count):
    54815481                q_time[time,:] = quantities_init[i] #* time * 4
     
    55615561            quantities_init[i] = ensure_numeric(quantities_init[i])
    55625562            #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)
    55645564            for time in range(time_step_count):
    55655565                q_time[time,:] = quantities_init[i] #* time * 4
     
    60176017            if ha is None:
    60186018                this_ha = e
    6019                 quantities_init[0].append(num.ones(time_step_count,num.Float)*this_ha) # HA
     6019                quantities_init[0].append(num.ones(time_step_count,num.float)*this_ha) # HA
    60206020            else:
    60216021                quantities_init[0].append(ha[i])
    60226022            if ua is None:
    60236023                this_ua = n
    6024                 quantities_init[1].append(num.ones(time_step_count,num.Float)*this_ua) # UA
     6024                quantities_init[1].append(num.ones(time_step_count,num.float)*this_ua) # UA
    60256025            else:
    60266026                quantities_init[1].append(ua[i])
    60276027            if va is None:
    60286028                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) #
    60306030            else:
    60316031                quantities_init[2].append(va[i])           
     
    60376037        files = []       
    60386038        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)
    60406040            quantities_init[i] = ensure_numeric(quantities_init[i])
    60416041            for time in range(time_step_count):
     
    61066106        lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)]
    61076107        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)
    61146114        #-ve added to take into account mux file format where south is positive.
    61156115        base_name, files = self.write_mux2(lat_long_points,
     
    61216121                                      va=va)
    61226122
    6123         weights=num.ones(1, num.Float)
     6123        weights=num.ones(1, num.float)
    61246124        #ensure that files are indeed mux2 files
    61256125        times, latitudes, longitudes, elevation, stage, starttime = read_mux2_py([files[0]],weights)
     
    61616161        lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)]
    61626162        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)
    61676167        ha[0]=num.arange(0,time_step_count)+1
    61686168        ha[1]=time_step_count-num.arange(1,time_step_count+1)
     
    61706170        ha[2]=num.arange(2*time_step_count,3*time_step_count)
    61716171        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)
    61746174        #-ve added to take into account mux file format where south is positive.
    61756175        base_name, files = self.write_mux2(lat_long_points,
     
    61816181                                      va=va)
    61826182
    6183         weights=num.ones(1, num.Float)
     6183        weights=num.ones(1, num.float)
    61846184        #ensure that files are indeed mux2 files
    61856185        times, latitudes, longitudes, elevation, stage,starttime=read_mux2_py([files[0]],weights)
     
    62196219        lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)]
    62206220        n=len(lat_long_points)
    6221         first_tstep=num.ones(n,num.Int)
     6221        first_tstep=num.ones(n,num.int)
    62226222        first_tstep[0]+=1
    62236223        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)
    62256225        last_tstep[0]-=1
    62266226
    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)
    62296229        ha[0]=num.arange(0,time_step_count)
    62306230        ha[1]=num.arange(time_step_count,2*time_step_count)
    62316231        ha[2]=num.arange(2*time_step_count,3*time_step_count)
    62326232        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)
    62356235        #-ve added to take into account mux file format where south is positive.
    62366236        base_name, files = self.write_mux2(lat_long_points,
     
    62426242                                      va=va)
    62436243
    6244         weights=num.ones(1, num.Float)
     6244        weights=num.ones(1, num.float)
    62456245        #ensure that files are indeed mux2 files
    62466246        times, latitudes, longitudes, elevation, stage, starttime=read_mux2_py([files[0]],weights)
     
    63086308       
    63096309        # 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)
    63116311        first_tstep[0]+=2   # Point 0 starts at 2
    63126312        first_tstep[1]+=4   # Point 1 starts at 4       
    63136313        first_tstep[2]+=3   # Point 2 starts at 3
    63146314       
    6315         last_tstep=(time_step_count)*num.ones(n,num.Int)
     6315        last_tstep=(time_step_count)*num.ones(n,num.int)
    63166316        last_tstep[0]-=1    # Point 0 ends 1 step early
    63176317        last_tstep[1]-=2    # Point 1 ends 2 steps early               
     
    63196319       
    63206320        # 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)
    63226322        for i in range(n):
    63236323            gauge_depth[i] += i**2
    63246324           
    63256325        # 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)
    63276327        ha0[0]=num.arange(0,time_step_count)
    63286328        ha0[1]=num.arange(time_step_count,2*time_step_count)
    63296329        ha0[2]=num.arange(2*time_step_count,3*time_step_count)
    63306330        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)
    63336333
    63346334        # Ensure data used to write mux file to be zero when gauges are
     
    63696369        # For each quantity read the associated list of source mux2 file with
    63706370        # 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]
    63726372        OFFSET = 5
    63736373
     
    64146414       
    64156415        # 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)
    64176417        first_tstep[0]+=2   # Point 0 starts at 2
    64186418        first_tstep[1]+=4   # Point 1 starts at 4       
    64196419        first_tstep[2]+=3   # Point 2 starts at 3
    64206420       
    6421         last_tstep=(time_step_count)*num.ones(n,num.Int)
     6421        last_tstep=(time_step_count)*num.ones(n,num.int)
    64226422        last_tstep[0]-=1    # Point 0 ends 1 step early
    64236423        last_tstep[1]-=2    # Point 1 ends 2 steps early               
     
    64256425       
    64266426        # 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)
    64286428        for i in range(n):
    64296429            gauge_depth[i] += i**2
    64306430           
    64316431        # 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)
    64336433        ha1[0]=num.sin(times_ref)
    64346434        ha1[1]=2*num.sin(times_ref - 3)
     
    64376437        ha1[4]=num.sin(2*times_ref-0.7)
    64386438               
    6439         ua1=num.zeros((n,time_step_count),num.Float)
     6439        ua1=num.zeros((n,time_step_count),num.float)
    64406440        ua1[0]=3*num.cos(times_ref)       
    64416441        ua1[1]=2*num.sin(times_ref-0.7)   
     
    64436443        ua1[4]=2*num.ones(time_step_count)
    64446444       
    6445         va1=num.zeros((n,time_step_count),num.Float)
     6445        va1=num.zeros((n,time_step_count),num.float)
    64466446        va1[0]=2*num.cos(times_ref-0.87)       
    64476447        va1[1]=3*num.ones(time_step_count)
     
    65166516            if ha is None:
    65176517                this_ha = e
    6518                 quantities_init[0].append(num.ones(time_step_count,num.Float)*this_ha) # HA
     6518                quantities_init[0].append(num.ones(time_step_count,num.float)*this_ha) # HA
    65196519            else:
    65206520                quantities_init[0].append(ha[i])
    65216521            if ua is None:
    65226522                this_ua = n
    6523                 quantities_init[1].append(num.ones(time_step_count,num.Float)*this_ua) # UA
     6523                quantities_init[1].append(num.ones(time_step_count,num.float)*this_ua) # UA
    65246524            else:
    65256525                quantities_init[1].append(ua[i])
    65266526            if va is None:
    65276527                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) #
    65296529            else:
    65306530                quantities_init[2].append(va[i])
     
    65346534            #print i, q
    65356535           
    6536             q_time = num.zeros((time_step_count, points_num), num.Float)
     6536            q_time = num.zeros((time_step_count, points_num), num.float)
    65376537            quantities_init[i] = ensure_numeric(quantities_init[i])
    65386538            for time in range(time_step_count):
     
    66206620        # For each quantity read the associated list of source mux2 file with
    66216621        # 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]
    66236623        OFFSET = 5
    66246624
     
    66396639            parameters_index = data.shape[1]-OFFSET         
    66406640                 
    6641             quantity=num.zeros((number_of_selected_stations, parameters_index), num.Float)
     6641            quantity=num.zeros((number_of_selected_stations, parameters_index), num.float)
    66426642           
    66436643           
     
    66746674        lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)]
    66756675        n=len(lat_long_points)
    6676         first_tstep=num.ones(n,num.Int)
     6676        first_tstep=num.ones(n,num.int)
    66776677        first_tstep[0]+=1
    66786678        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)
    66806680        last_tstep[0]-=1
    66816681
    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)
    66846684        ha[0]=num.arange(0,time_step_count)
    66856685        ha[1]=num.arange(time_step_count,2*time_step_count)
    66866686        ha[2]=num.arange(2*time_step_count,3*time_step_count)
    66876687        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)
    66906690
    66916691        base_name, files = self.write_mux2(lat_long_points,
     
    67606760        #momentum = velocity_ua *(stage+depth)
    67616761
    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)
    67636763        for i in range(len(lat_long_points)):
    67646764            depth[i]=gauge_depth[i]+tide+ha[i]
     
    67896789        lat_long_points =[(-21.,114.5),(-21.,113.5),(-21.,114.), (-21.,115.)]
    67906790        n=len(lat_long_points)
    6791         first_tstep=num.ones(n,num.Int)
     6791        first_tstep=num.ones(n,num.int)
    67926792        first_tstep[0]+=1
    67936793        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)
    67956795        last_tstep[0]-=1
    67966796
    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)
    67996799        ha[0]=num.arange(0,time_step_count)
    68006800        ha[1]=num.arange(time_step_count,2*time_step_count)
    68016801        ha[2]=num.arange(2*time_step_count,3*time_step_count)
    68026802        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)
    68056805
    68066806        base_name, files = self.write_mux2(lat_long_points,
     
    68516851        lat_long_points =[(-21.,113.5),(-21.,114.5),(-21.,114.), (-21.,115.)]
    68526852        n=len(lat_long_points)
    6853         first_tstep=num.ones(n,num.Int)
     6853        first_tstep=num.ones(n,num.int)
    68546854        first_tstep[0]+=1
    68556855        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)
    68576857        last_tstep[0]-=1
    68586858
    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)
    68616861        ha[0]=num.arange(0,time_step_count)
    68626862        ha[1]=num.arange(time_step_count,2*time_step_count)
    68636863        ha[2]=num.arange(2*time_step_count,3*time_step_count)
    68646864        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)
    68676867
    68686868        base_name, files = self.write_mux2(lat_long_points,
     
    69146914        lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)]
    69156915        n=len(lat_long_points)
    6916         first_tstep=num.ones(n,num.Int)
     6916        first_tstep=num.ones(n,num.int)
    69176917        first_tstep[0]+=1
    69186918        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)
    69206920        last_tstep[0]-=1
    69216921
    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)
    69246924        ha[0]=num.arange(0,time_step_count)
    69256925        ha[1]=num.arange(time_step_count,2*time_step_count)
    69266926        ha[2]=num.arange(2*time_step_count,3*time_step_count)
    69276927        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)
    69306930
    69316931        # Create two identical mux files to be combined by urs2sts
     
    70167016        #momentum = velocity_ua *(stage+depth)
    70177017
    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)
    70197019        for i in range(len(lat_long_points)):
    70207020            depth[i]=gauge_depth[i]+tide+2.0*ha[i]
     
    73867386        lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)]
    73877387        n=len(lat_long_points)
    7388         first_tstep=num.ones(n,num.Int)
     7388        first_tstep=num.ones(n,num.int)
    73897389        first_tstep[0]+=1
    73907390        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)
    73927392        last_tstep[0]-=1
    73937393
    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)
    73967396        ha[0]=num.arange(0,time_step_count)
    73977397        ha[1]=num.arange(time_step_count,2*time_step_count)
    73987398        ha[2]=num.arange(2*time_step_count,3*time_step_count)
    73997399        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)
    74027402
    74037403        # Create two identical mux files to be combined by urs2sts
     
    75307530        #momentum = velocity_ua *(stage+depth)
    75317531
    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)
    75337533        for i in range(len(lat_long_points)):
    75347534            depth[i]=gauge_depth[i]+tide+2.0*ha[i]
     
    75737573        lat_long_points =[(-21.5,114.5),(-21,114.5),(-21.5,115), (-21.,115.)]
    75747574        n=len(lat_long_points)
    7575         first_tstep=num.ones(n,num.Int)
     7575        first_tstep=num.ones(n,num.int)
    75767576        first_tstep[0]+=1
    75777577        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)
    75797579        last_tstep[0]-=1
    75807580
    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)
    75837583        ha[0]=num.arange(0,time_step_count)
    75847584        ha[1]=num.arange(time_step_count,2*time_step_count)
    75857585        ha[2]=num.arange(2*time_step_count,3*time_step_count)
    75867586        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)
    75897589
    75907590        # Create two identical mux files to be combined by urs2sts
     
    76697669       
    76707670        # 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)
    76727672        first_tstep[0]+=2   # Point 0 starts at 2
    76737673        first_tstep[1]+=4   # Point 1 starts at 4       
    76747674        first_tstep[2]+=3   # Point 2 starts at 3
    76757675       
    7676         last_tstep=(time_step_count)*num.ones(n,num.Int)
     7676        last_tstep=(time_step_count)*num.ones(n,num.int)
    76777677        last_tstep[0]-=1    # Point 0 ends 1 step early
    76787678        last_tstep[1]-=2    # Point 1 ends 2 steps early               
     
    76877687       
    76887688        # 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)
    76907690        for i in range(n):
    76917691            gauge_depth[i] += i**2
     
    76947694       
    76957695        # 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)
    76977697        ha0[0]=num.arange(0,time_step_count)
    76987698        ha0[1]=num.arange(time_step_count,2*time_step_count)
    76997699        ha0[2]=num.arange(2*time_step_count,3*time_step_count)
    77007700        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)
    77037703
    77047704        # Ensure data used to write mux file to be zero when gauges are
     
    77317731                                             
    77327732        # 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)
    77347734        ha1[0]=num.sin(times_ref)
    77357735        ha1[1]=2*num.sin(times_ref - 3)
     
    77387738        ha1[4]=num.sin(2*times_ref-0.7)
    77397739               
    7740         ua1=num.zeros((n,time_step_count),num.Float)
     7740        ua1=num.zeros((n,time_step_count),num.float)
    77417741        ua1[0]=3*num.cos(times_ref)       
    77427742        ua1[1]=2*num.sin(times_ref-0.7)   
     
    77447744        ua1[4]=2*num.ones(time_step_count)
    77457745       
    7746         va1=num.zeros((n,time_step_count),num.Float)
     7746        va1=num.zeros((n,time_step_count),num.float)
    77477747        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#
    77497749        va1[3]=2*num.sin(times_ref-0.71)       
    77507750       
     
    78737873        #momentum = velocity_ua *(stage+depth)
    78747874
    7875         depth_ref = num.zeros((len(permutation), time_step_count), num.Float)
     7875        depth_ref = num.zeros((len(permutation), time_step_count), num.float)
    78767876        for i in range(len(permutation)):
    78777877            depth_ref[i]=gauge_depth_ref[i]+tide+ha_ref[i]
     
    79867986        #momentum = velocity_ua *(stage+depth)
    79877987
    7988         depth_ref = num.zeros((len(permutation), time_step_count), num.Float)
     7988        depth_ref = num.zeros((len(permutation), time_step_count), num.float)
    79897989        for i in range(len(permutation)):
    79907990            depth_ref[i]=gauge_depth_ref[i]+tide+ha_ref[i]
     
    80928092        #momentum = velocity_ua *(stage+depth)
    80938093
    8094         depth_ref = num.zeros((len(permutation), time_step_count), num.Float)
     8094        depth_ref = num.zeros((len(permutation), time_step_count), num.float)
    80958095        for i in range(len(permutation)):
    80968096            depth_ref[i]=gauge_depth_ref[i]+tide+ha_ref[i]
     
    81618161        lat_long_points =bounding_polygon[0:3]
    81628162        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)
    81658165
    81668166        h = 20       
     
    81688168        u = 10
    81698169        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)
    81748174        base_name, files = self.write_mux2(lat_long_points,
    81758175                                           time_step_count, time_step,
     
    82248224        finaltime=time_step*(time_step_count-1)
    82258225        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)
    82278227
    82288228        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
     
    82508250
    82518251        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)
    82538253
    82548254        for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep,
     
    83058305        lat_long_points = bounding_polygon[0:3]
    83068306        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)
    83098309
    83108310        h = 20       
     
    83128312        u = 10
    83138313        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)
    83188318        base_name, files = self.write_mux2(lat_long_points,
    83198319                                           time_step_count, time_step,
     
    83778377        finaltime = data_finaltime + 10 # Let model time exceed available data
    83788378        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)
    83808380
    83818381        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
     
    84098409
    84108410        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)
    84128412
    84138413        for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep,
     
    84638463        lat_long_points = bounding_polygon[0:3]
    84648464        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)
    84678467
    84688468        h = 20       
     
    84708470        u = 10
    84718471        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)
    84768476        base_name, files = self.write_mux2(lat_long_points,
    84778477                                           time_step_count, time_step,
     
    85388538        finaltime = data_finaltime + 10 # Let model time exceed available data
    85398539        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)
    85418541
    85428542        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
     
    85828582        lat_long_points.insert(0,[6.0,97.01])
    85838583        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)
    85908590        base_name, files = self.write_mux2(lat_long_points,
    85918591                                           time_step_count,
     
    86298629        finaltime=time_step*(time_step_count-1)
    86308630        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)
    86328632       
    86338633        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
     
    86418641        Bd = Dirichlet_boundary([2.0+tide,220+10*tide,-220-10*tide])
    86428642        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)
    86448644
    86458645        for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep,
     
    86888688        time_step = 2
    86898689        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)
    86968696        base_name, files = self.write_mux2(lat_long_points,
    86978697                                           time_step_count,
     
    87798779        finaltime=time_step*(time_step_count-1)
    87808780        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)
    87828782   
    87838783        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
     
    87928792        Bd = Dirichlet_boundary([2.0+tide,220+10*tide,-220-10*tide])
    87938793        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)
    87958795       
    87968796        for i, t in enumerate(domain_drchlt.evolve(yieldstep=yieldstep,
     
    88548854       
    88558855        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)
    88648864        for i in range(n):
    88658865            ha1[i]=num.sin(times_ref)
     
    89768976        finaltime=time_step*(time_step_count-1)
    89778977        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)
    89798979   
    89808980        for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep,
     
    89918991        domain_time.set_boundary({'ocean': Bw,'otherocean': Br})
    89928992       
    8993         temp_time=num.zeros(int(finaltime/yieldstep)+1,num.Float)
     8993        temp_time=num.zeros(int(finaltime/yieldstep)+1,num.float)
    89948994        for i, t in enumerate(domain_time.evolve(yieldstep=yieldstep,
    89958995                                                   finaltime=finaltime,
     
    90509050       
    90519051        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)
    90609060        for i in range(n):
    90619061            ha1[i]=num.sin(times_ref)
     
    1012710127        sww.store_header(outfile, times, number_of_volumes,
    1012810128                         number_of_points, description='fully sick testing',
    10129                          verbose=self.verbose,sww_precision=num.Float)
     10129                         verbose=self.verbose,sww_precision=netcdf_float)
    1013010130        sww.store_triangulation(outfile, points_utm, volumes,
    1013110131                                elevation,  new_origin=new_origin,
     
    1015910159        sww.store_header(outfile, times, number_of_volumes,
    1016010160                         number_of_points, description='fully sick testing',
    10161                          verbose=self.verbose,sww_precision=num.Float)
     10161                         verbose=self.verbose,sww_precision=netcdf_float)
    1016210162        sww.store_triangulation(outfile, points_utm, volumes,
    1016310163                                elevation,  new_origin=new_origin,
     
    1019510195        sww.store_header(outfile, times, number_of_volumes,
    1019610196                         number_of_points, description='fully sick testing',
    10197                          verbose=self.verbose,sww_precision=num.Float)
     10197                         verbose=self.verbose,sww_precision=netcdf_float)
    1019810198        sww.store_triangulation(outfile, points_utm, volumes,
    1019910199                                elevation,  new_origin=new_origin,
     
    1023410234        sww.store_header(outfile, times, number_of_volumes,
    1023510235                         number_of_points, description='fully sick testing',
    10236                          verbose=self.verbose,sww_precision=num.Float)
     10236                         verbose=self.verbose,sww_precision=netcdf_float)
    1023710237        sww.store_triangulation(outfile, points_utm, volumes,
    1023810238                                elevation,  new_origin=new_origin,
     
    1027010270        sww.store_header(outfile, times, number_of_volumes,
    1027110271                         number_of_points, description='fully sick testing',
    10272                          verbose=self.verbose,sww_precision=num.Float)
     10272                         verbose=self.verbose,sww_precision=netcdf_float)
    1027310273        sww.store_triangulation(outfile, points_utm, volumes,
    1027410274                                elevation,  new_origin=new_origin,
     
    1062910629
    1063010630        # 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])
    1063210632
    1063310633        runup = get_maximum_inundation_elevation(swwfile, polygon=p)
  • branches/numpy/anuga/shallow_water/test_eq.py

    r6157 r6304  
    11import unittest
    2 import Numeric as num
     2import numpy as num
    33from eqf import earthquake_tsunami, Okada_func
    44
  • branches/numpy/anuga/shallow_water/test_most2nc.py

    r6157 r6304  
    11import unittest
    2 import Numeric as num
     2import numpy as num
    33from Scientific.IO.NetCDF import NetCDFFile
    44import most2nc
  • branches/numpy/anuga/shallow_water/test_shallow_water_domain.py

    r6244 r6304  
    77from anuga.config import g, epsilon
    88from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
    9 import Numeric as num
     9import numpy as num
    1010from anuga.utilities.numerical_tools import mean
    1111from anuga.utilities.polygon import is_inside_polygon
     
    3737        assert N == len(y)
    3838
    39         z = num.zeros(N, num.Float)
     39        z = num.zeros(N, num.float)
    4040        for i in range(N):
    4141            z[i] = -x[i]/2  #General slope
     
    142142        assert N == len(y)
    143143
    144         z = num.zeros(N, num.Float)
     144        z = num.zeros(N, num.float)
    145145        for i in range(N):
    146146            z[i] = -x[i]  #General slope
     
    195195def scalar_func(t,x,y):
    196196    """Function that returns a scalar.
    197     Used to test error message when Numeric array is expected
     197    Used to test error message when numeric array is expected
    198198    """
    199199
     
    254254        #Check error check
    255255        try:
    256             rotate(r, num.array([1,1,1], num.Int))      #array default#
     256            rotate(r, num.array([1,1,1]))
    257257        except:
    258258            pass
     
    263263    # Individual flux tests
    264264    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 )
    269269        zl = zr = 0.
    270270        H0 = 0.0
     
    281281        ql = num.array([w, 0, 0])
    282282        qr = num.array([w, 0, 0])
    283         edgeflux = num.zeros(3, num.Float)       
     283        edgeflux = num.zeros(3, num.float)       
    284284        zl = zr = 0.
    285285        h = w - (zl+zr)/2
     
    312312        qr = num.array([-0.2, 2, 3])
    313313        zl = zr = -0.5
    314         edgeflux = num.zeros(3, num.Float)               
     314        edgeflux = num.zeros(3, num.float)               
    315315
    316316        H0 = 0.0
     
    329329        zl = zr = -0.375
    330330
    331         edgeflux = num.zeros(3, num.Float)               
     331        edgeflux = num.zeros(3, num.float)               
    332332        H0 = 0.0
    333333        max_speed = flux_function(normal, ql, qr, zl, zr, edgeflux, epsilon, g, H0)       
     
    343343        zl = zr = -0.375
    344344
    345         edgeflux = num.zeros(3, num.Float)               
     345        edgeflux = num.zeros(3, num.float)               
    346346        H0 = 0.0
    347347        max_speed = flux_function(normal, ql, qr, zl, zr, edgeflux, epsilon, g, H0)       
     
    357357        zl = zr = -0.375
    358358
    359         edgeflux = num.zeros(3, num.Float)               
     359        edgeflux = num.zeros(3, num.float)               
    360360        H0 = 0.0
    361361        max_speed = flux_function(normal, ql, qr, zl, zr, edgeflux, epsilon, g, H0)               
     
    433433            assert domain.quantities.has_key(name)
    434434
    435 
    436         assert domain.get_conserved_quantities(0, edge=1) == 0.
     435        assert num.alltrue(domain.get_conserved_quantities(0, edge=1) == 0.)
    437436
    438437
     
    709708        zl=zr=0. # Assume flat bed
    710709
    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)                               
    715714        H0 = 0.0       
    716715
     
    797796        zl=zr=0. #Assume flat bed
    798797
    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)                               
    803802        H0 = 0.0       
    804803       
     
    905904
    906905        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)                               
    911910        H0 = 0.0       
    912911       
    913912
    914         domain.set_quantity('elevation', zl*num.ones( (4,3) ))
     913        domain.set_quantity('elevation', zl*num.ones( (4,3), num.int )) #array default#
    915914
    916915
     
    988987
    989988        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)                               
    997996        H0 = 0.0       
    998997       
     
    10711070
    10721071        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#
    10741073        domain.set_quantity('stage', [[val0, val0-1, val0-2],
    10751074                                      [val1, val1+1, val1],
     
    11051104
    11061105        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#
    11081107        domain.set_quantity('stage', [[val0, val0-1, val0-2],
    11091108                                      [val1, val1+1, val1],
     
    26212620    def test_time_dependent_rainfall_using_starttime(self):
    26222621   
    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)   
    26242623
    26252624        a = [0.0, 0.0]
     
    26922691
    26932692       
    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)
    26952694        rainfall_poly += [x0, y0]
    26962695
     
    31423141
    31433142        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#
    31453144        domain.set_quantity('stage', [[val0, val0-1, val0-2],
    31463145                                      [val1, val1+1, val1],
     
    45604559            if V:
    45614560                #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)
    45634562                L[:32] = [7.21205592e-003, 5.35214298e-002, 1.00910824e-002,
    45644563                          5.35439433e-002, 1.00910824e-002, 5.35439433e-002,
     
    45734572                          0.00000000e+000, 5.57305948e-005]
    45744573
    4575                 X = num.zeros(2*N*N, num.Float)
     4574                X = num.zeros(2*N*N, num.float)
    45764575                X[:32] = [6.48351607e-003, 3.68571894e-002, 8.50733285e-003,
    45774576                          3.68731327e-002, 8.50733285e-003, 3.68731327e-002,
     
    45864585                          0.00000000e+000, 4.57662812e-005]
    45874586
    4588                 Y = num.zeros(2*N*N, num.Float)
     4587                Y = num.zeros(2*N*N, num.float)
    45894588                Y[:32]=[-1.39463104e-003, 6.15600298e-004, -6.03637382e-004,
    45904589                        6.18272251e-004, -6.03637382e-004, 6.18272251e-004,
     
    56915690
    56925691        #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
    56955696
    56965697
     
    58725873
    58735874        #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
    58765879
    58775880
     
    60456048
    60466049        #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
    60496055
    60506056
     
    62376243
    62386244        bed = domain.quantities['elevation'].vertex_values
    6239         stage = num.zeros(bed.shape, num.Float)
     6245        stage = num.zeros(bed.shape, num.float)
    62406246
    62416247        h = 0.3
  • branches/numpy/anuga/shallow_water/test_smf.py

    r6157 r6304  
    11import unittest
    2 import Numeric as num
     2import numpy as num
    33from smf import slide_tsunami, slump_tsunami, Double_gaussian
    44
  • branches/numpy/anuga/shallow_water/test_system.py

    r6157 r6304  
    99
    1010from Scientific.IO.NetCDF import NetCDFFile
    11 import Numeric as num
     11import numpy as num
    1212
    1313from anuga.shallow_water import Domain
     
    3434        20       13.9773
    3535        """
     36
    3637        tide = 5
    3738        boundary_filename = tempfile.mktemp(".sww")
     
    8586        boundary_filename = self.create_sww_boundary(boundary_starttime)
    8687        filename = tempfile.mktemp(".sww")
    87         #print "filename",filename
    8888        dir, base = os.path.split(filename)
    8989        senario_name = base[:-4]
  • branches/numpy/anuga/shallow_water/test_tsunami_okada.py

    r6157 r6304  
    11import unittest
    2 import Numeric as num
     2import numpy as num
    33from tsunami_okada import earthquake_tsunami,Okada_func
    44
  • branches/numpy/anuga/shallow_water/tsunami_okada.py

    r6157 r6304  
    3030"""
    3131
    32 import Numeric as num
     32import numpy as num
    3333
    3434
     
    4545    zrec=zrec0.get_vertex_values(xy=True)
    4646   
    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)
    4949    if ns ==1:
    5050        x0[0]=xi
     
    151151        zrec=self.zrec
    152152        #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)
    171171        z=[]
    172172        if ns==1:
     
    378378         
    379379          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)
    384384         
    385385         
     
    526526       WZ=self.WZ
    527527
    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)
    531531#-----                                                               
    532532       for I in range(0,12):                                                   
     
    636636#      DATA PI2/6.283185307179586D0/
    637637       
    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)
    641641       
    642642        F0=0.0
     
    811811       
    812812
    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)
    816816             
    817817      F0=0.0
     
    10051005      EPS=0.000001
    10061006       
    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)
    10161016
    10171017#-----                                                                 
     
    12111211
    12121212
    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)
    12161216      F0 =0.0
    12171217      F2=2.0
     
    13421342#      DATA  F0,F1,F2,PI2/0.D0,1.D0,2.D0,6.283185307179586D0/
    13431343
    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)
    13471347     
    13481348      F0=0.0
     
    15071507 #     DATA F0,F1,F2,F3,PI2/0.D0,1.D0,2.D0,3.D0,6.283185307179586D0/
    15081508
    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)
    15121512     
    15131513      F0=0.0
  • branches/numpy/anuga/shallow_water/urs_ext.c

    r5972 r6304  
    55
    66#include "Python.h"
    7 #include "Numeric/arrayobject.h"
     7#include "numpy/arrayobject.h"
    88#include "structure.h"
    99#include "math.h"
  • branches/numpy/anuga/test_all.py

    r6220 r6304  
    1515import time
    1616import anuga.utilities.system_tools as aust
     17from anuga.utilities.terminal_width import terminal_width
    1718
    1819
     
    3536def list_names(names, func=None, col_width=None, page_width=None):
    3637    # set defaults
    37     p_width = page_width                # set page width
     38    p_width = page_width - 1            # set page width
    3839    if p_width is None:
    3940        p_width = 132                   # default page width
     
    4647                name = func(name)
    4748            c_width = max(c_width, len(name))
    48         c_width += 2                    # padding between columns
     49    c_width += 2                        # 2 column padding
    4950
    5051    # calculate number of columns allowed
     
    5657        if func:
    5758            name = func(name)
    58         print '%-*s' % (c_width, name),
     59        print '%-*s' % (c_width-1, name),
    5960        column += 1
    6061        if column >= max_columns:
     
    102103    print 'Testing path: %s' % path
    103104
     105    # get the terminal width
     106    term_width = terminal_width()
     107
    104108    # explain what we are doing
    105109    print
    106110    print "The following directories will be skipped over:"
    107111    exclude_dirs.sort()
    108     list_names(exclude_dirs)
     112    list_names(exclude_dirs, page_width=term_width)
    109113
    110114    # get all test_*.py and enclosing directories
     
    116120    print
    117121    print 'Paths searched:'
    118     list_names(path_files, os.path.basename)
     122    list_names(path_files, os.path.basename, page_width=term_width)
    119123
    120124    print   
    121125    print 'Files tested:'
    122     list_names(files)
     126    list_names(files, page_width=term_width)
    123127    print
    124128
  • branches/numpy/anuga/utilities/cg_solve.py

    r6158 r6304  
    33class ConvergenceError(exceptions.Exception): pass
    44
    5 import Numeric as num
     5import numpy as num
    66   
    77import logging, logging.config
     
    2424   
    2525    if x0 is None:
    26         x0 = num.zeros(b.shape, typecode=num.Float)
     26        x0 = num.zeros(b.shape, dtype=num.float)
    2727    else:
    28         x0 = num.array(x0, typecode=num.Float)
     28        x0 = num.array(x0, dtype=num.float)
    2929
    30     b  = num.array(b, typecode=num.Float)
     30    b  = num.array(b, dtype=num.float)
    3131    if len(b.shape) != 1 :
    3232       
     
    5757
    5858
    59    b  = num.array(b, typecode=num.Float)
     59   b  = num.array(b, dtype=num.float)
    6060   if len(b.shape) != 1 :
    6161      raise VectorShapeError, 'input vector should consist of only one column'
    6262
    6363   if x0 is None:
    64       x0 = num.zeros(b.shape, typecode=num.Float)
     64      x0 = num.zeros(b.shape, dtype=num.float)
    6565   else:
    66       x0 = num.array(x0, typecode=num.Float)
     66      x0 = num.array(x0, dtype=num.float)
    6767
    6868
  • branches/numpy/anuga/utilities/compile.py

    r6057 r6304  
    1010   Ole Nielsen, Duncan Gray Oct 2001     
    1111"""     
     12
     13#NumPy ------------------------------------
     14# Something like these lines recommended in "Converting from NUMARRAY to NUMPY"
     15import numpy
     16I_dirs = '-I"%s" ' % numpy.get_include()
     17#NumPy ------------------------------------
    1218
    1319# FIXME (Ole): Although this script says it works with a range of compilers,
     
    255261    else:
    256262      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)
    259265      elif FN == "polygon_ext.c":
    260266        # 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)
    263269      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)
    266272
    267273    if os.name == 'posix' and os.uname()[4] in ['x86_64', 'ia64']:
  • branches/numpy/anuga/utilities/interp.py

    r5897 r6304  
    7575
    7676    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.
    7878      Can have missing values.  Floating or integer type.
    7979
    80     * x:  Abscissa values of data.  Rank 1 Numeric vector.  Required.
     80    * x:  Abscissa values of data.  Rank 1 numeric vector.  Required.
    8181      Can have no missing values.  Must be monotonically ascending. 
    8282      Floating or integer type.
    8383
    8484    * 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. 
    8686      Can have no missing values.  Can be in any order.  Floating or
    8787      integer type.
     
    9494
    9595    Output Result:
    96     * 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
     96    * 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
    9999      value of argument missing.  Type is Float, even if argument
    100100      missing and inputs are all integer.
     
    111111
    112112    >>> from interp import interp
    113     >>> import Numeric as N
     113    >>> import numpy as N
    114114    >>> x = N.array([1., 2., 3., 4., 5.])
    115115    >>> y = N.array([3., 6., 2.,-5.,-3.])
     
    138138    """
    139139    import arrayfns
    140     import MA
    141     import Numeric as N
     140    import numpy.ma MA
     141    import numpy as N
    142142    from where_close import where_close
    143143
     
    216216
    217217    >>> from interp import interp
    218     >>> import Numeric as N
     218    >>> import numpy as N
    219219    >>> x = N.array([1.,    2., 3.,  4.,  5.,  6.])
    220220    >>> y = N.array([3., 1e+20, 2., -5., -3., -4.])
     
    284284    >>> ['%.7g' % yint[i] for i in range(len(yint))]
    285285    ['3.4', '2.3']
    286     >>> yint.typecode()
     286    >>> yint.dtype.char
    287287    'd'
    288288    >>> x = N.arange(6)
     
    292292    >>> ['%.7g' % yint[i] for i in range(len(yint))]
    293293    ['3', '2']
    294     >>> yint.typecode()
     294    >>> yint.dtype.char
    295295    'd'
    296296    """}
  • branches/numpy/anuga/utilities/numerical_tools.py

    r6174 r6304  
    77from warnings import warn
    88
    9 import Numeric as num
     9import numpy as num
    1010
    1111NAN = (num.array([1])/0.)[0]
     
    7070    """
    7171 
    72     # Prepare two Numeric vectors
     72    # Prepare two numeric vectors
    7373    if v2 is None:
    7474        v2 = [1.0, 0.0] # Unit vector along the x-axis
    7575       
    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)   
    7878   
    7979    # Normalise
     
    8282
    8383    # Compute angle
    84     p = num.innerproduct(v1, v2)
    85     c = num.innerproduct(v1, normal_vector(v2)) # Projection onto normal
     84    p = num.inner(v1, v2)
     85    c = num.inner(v1, normal_vector(v2)) # Projection onto normal
    8686                                            # (negative cross product)
    8787       
     
    125125    """
    126126   
    127     return num.array([-v[1], v[0]], num.Float)
     127    return num.array([-v[1], v[0]], num.float)
    128128
    129129   
     
    156156    cy = y - mean(y) 
    157157
    158     p = num.innerproduct(cx,cy)/N
     158    p = num.inner(cx,cy)/N
    159159    return(p)
    160160
     
    206206 
    207207    y = num.ravel(x)
    208     p = num.sqrt(num.innerproduct(y,y))
     208    p = num.sqrt(num.inner(y,y))
    209209    return p
    210210   
     
    230230
    231231
    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.
     238def ensure_numeric(A, typecode=None):
     239    """Ensure that sequence is a numeric array.
    235240    Inputs:
    236         A: Sequence. If A is already a Numeric array it will be returned
     241        A: Sequence. If A is already a numeric array it will be returned
    237242                     unaltered
    238                      If not, an attempt is made to convert it to a Numeric
     243                     If not, an attempt is made to convert it to a numeric
    239244                     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.
    244252
    245253    This function is necessary as array(A) can cause memory overflow.
    246254    """
    247255
     256    if isinstance(A, basestring):
     257        msg = 'Sorry, cannot handle string in ensure_numeric()'
     258        raise Exception, msg
     259
    248260    if typecode is None:
    249         if type(A) == num.ArrayType:
     261        if isinstance(A, num.ndarray):
    250262            return A
    251263        else:
    252264            return num.array(A)
    253265    else:
    254         if type(A) == num.ArrayType:
    255             if A.typecode == typecode:
     266        if isinstance(A, num.ndarray):
     267            if A.dtype == typecode:
    256268#                return num.array(A)  #FIXME: Shouldn't this just return A?
    257269                return A
    258270            else:
    259                 return num.array(A,typecode)
     271                return num.array(A, dtype=typecode)
    260272        else:
    261             return num.array(A,typecode)
     273            return num.array(A, dtype=typecode)
    262274
    263275
     
    265277
    266278def histogram(a, bins, relative=False):
    267     """Standard histogram straight from the Numeric manual
     279    """Standard histogram straight from the numeric manual
    268280
    269281    If relative is True, values will be normalised againts the total and
     
    358370    return a, b       
    359371
     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.
     382def 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.
     394def 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
    360402
    361403#-----------------
  • branches/numpy/anuga/utilities/polygon.py

    r6223 r6304  
    33"""
    44
    5 import Numeric as num
     5import numpy as num
    66
    77from math import sqrt
    88from anuga.utilities.numerical_tools import ensure_numeric
    99from anuga.geospatial_data.geospatial_data import ensure_absolute, Geospatial_data
     10from anuga.config import netcdf_float
    1011
    1112
     
    1516    Input:
    1617        point is given by [x, y]
    17         line is given by [x0, y0], [x1, y1]] or
    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.
    1920
    2021    Output:
     
    100101    # FIXME (Ole): Write this in C
    101102
    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)   
    104105
    105106    x0 = line0[0,0]; y0 = line0[0,1]
     
    176177
    177178
    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)   
    180181
    181182    status, value = _intersection(line0[0,0], line0[0,1],
     
    203204    else:
    204205        msg = 'is_inside_polygon must be invoked with one point only'
    205         raise msg
     206        raise Exception, msg
    206207   
    207208
     
    228229        # If this fails it is going to be because the points can't be
    229230        # converted to a numeric array.
    230         msg = 'Points could not be converted to Numeric array'
    231         raise msg
     231        msg = 'Points could not be converted to numeric array'
     232        raise Exception, msg
    232233
    233234    try:
     
    238239        # If this fails it is going to be because the points can't be
    239240        # converted to a numeric array.
    240         msg = 'Polygon %s could not be converted to Numeric array' %(str(polygon))
    241         raise msg
     241        msg = 'Polygon %s could not be converted to numeric array' %(str(polygon))
     242        raise Exception, msg
    242243
    243244    if len(points.shape) == 1:
    244245        # Only one point was passed in. Convert to array of points
    245         points = num.reshape(points, (1,2))
     246        points = num.reshape(points, (1,2))
    246247
    247248    indices, count = separate_points_by_polygon(points, polygon,
     
    270271    else:
    271272        msg = 'is_outside_polygon must be invoked with one point only'
    272         raise msg
     273        raise Exception, msg
    273274   
    274275
     
    285286    #if verbose: print 'Checking input to outside_polygon'
    286287    try:
    287         points = ensure_numeric(points, num.Float)
     288        points = ensure_numeric(points, num.float)
    288289    except NameError, e:
    289290        raise NameError, e
    290291    except:
    291         msg = 'Points could not be converted to Numeric array'
    292         raise msg
     292        msg = 'Points could not be converted to numeric array'
     293        raise Exception, msg
    293294
    294295    try:
    295         polygon = ensure_numeric(polygon, num.Float)
     296        polygon = ensure_numeric(polygon, num.float)
    296297    except NameError, e:
    297298        raise NameError, e
    298299    except:
    299         msg = 'Polygon could not be converted to Numeric array'
    300         raise msg
     300        msg = 'Polygon could not be converted to numeric array'
     301        raise Exception, msg
    301302
    302303
    303304    if len(points.shape) == 1:
    304305        # Only one point was passed in. Convert to array of points
    305         points = num.reshape(points, (1,2))
     306        points = num.reshape(points, (1,2))
    306307
    307308    indices, count = separate_points_by_polygon(points, polygon,
     
    327328    #if verbose: print 'Checking input to outside_polygon'
    328329    try:
    329         points = ensure_numeric(points, num.Float)
     330        points = ensure_numeric(points, num.float)
    330331    except NameError, e:
    331332        raise NameError, e
    332333    except:
    333         msg = 'Points could not be converted to Numeric array'
    334         raise msg
     334        msg = 'Points could not be converted to numeric array'
     335        raise Exception, msg
    335336
    336337    try:
    337         polygon = ensure_numeric(polygon, num.Float)
     338        polygon = ensure_numeric(polygon, num.float)
    338339    except NameError, e:
    339340        raise NameError, e
    340341    except:
    341         msg = 'Polygon could not be converted to Numeric array'
    342         raise msg
     342        msg = 'Polygon could not be converted to numeric array'
     343        raise Exception, msg
    343344
    344345    if len(points.shape) == 1:
    345346        # Only one point was passed in. Convert to array of points
    346         points = num.reshape(points, (1,2))
     347        points = num.reshape(points, (1,2))
    347348
    348349
     
    413414
    414415
     416#    points = ensure_numeric(points, num.float)
    415417    try:
    416         points = ensure_numeric(points, num.Float)
     418        points = ensure_numeric(points, num.float)
    417419    except NameError, e:
    418420        raise NameError, e
    419421    except:
    420         msg = 'Points could not be converted to Numeric array'
    421         raise msg
     422        msg = 'Points could not be converted to numeric array'
     423        raise Exception, msg
    422424
    423425    #if verbose: print 'Checking input to separate_points_by_polygon 2'
    424426    try:
    425         polygon = ensure_numeric(polygon, num.Float)
     427        polygon = ensure_numeric(polygon, num.float)
    426428    except NameError, e:
    427429        raise NameError, e
    428430    except:
    429         msg = 'Polygon could not be converted to Numeric array'
    430         raise msg
     431        msg = 'Polygon could not be converted to numeric array'
     432        raise Exception, msg
    431433
    432434    msg = 'Polygon array must be a 2d array of vertices'
     
    449451   
    450452    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]
    452454    assert points.shape[1] == 2, msg
    453455
     
    464466
    465467
    466     indices = num.zeros( M, num.Int )
     468    indices = num.zeros( M, num.int )
    467469
    468470    count = _separate_points_by_polygon(points, polygon, indices,
     
    599601
    600602    try:
    601         polygon = ensure_numeric(polygon, num.Float)
     603        polygon = ensure_numeric(polygon, num.float)
    602604    except NameError, e:
    603605        raise NameError, e
    604606    except:
    605         msg = 'Polygon %s could not be converted to Numeric array' %(str(polygon))
    606         raise msg
     607        msg = 'Polygon %s could not be converted to numeric array' %(str(polygon))
     608        raise Exception, msg
    607609
    608610    x = polygon[:,0]
     
    666668                 geo_reference=None):
    667669
    668         try:
    669             len(regions)
    670         except:
     670        try:
     671            len(regions)
     672        except:
    671673            msg = 'Polygon_function takes a list of pairs (polygon, value).'
    672674            msg += 'Got %s' %regions
    673             raise msg
     675            raise Exception, msg
    674676
    675677
     
    682684            raise Exception, msg
    683685       
    684         try:
     686        try:
    685687            a = len(T)
    686         except:
     688        except:
    687689            msg = 'Polygon_function takes a list of pairs (polygon, value).'
    688690            msg += 'Got %s' %str(T)
    689             raise msg
     691            raise Exception, msg
    690692
    691693        msg = 'Each entry in regions have two components: (polygon, value).'
    692694        msg +='I got %s' %str(T)
    693         assert a == 2, msg
     695        assert a == 2, msg
    694696
    695697
     
    711713
    712714    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]])
    735740                    z[i] = value(xx, yy)[0]
    736             else:
    737                 for i in indices:
    738                     z[i] = value
     741            else:
     742                for i in indices:
     743                    z[i] = value
    739744
    740745        if len(z) == 0:
     
    9981003      interpolation_points: Interpolate polyline data to these positions.
    9991004          List of coordinate pairs [x, y] of
    1000           data points or an nx2 Numeric array or a Geospatial_data object
     1005          data points or an nx2 numeric array or a Geospatial_data object
    10011006      rtol, atol: Used to determine whether a point is on the polyline or not. See point_on_line.
    10021007
     
    10081013        interpolation_points = interpolation_points.get_data_points(absolute=True)
    10091014
    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)
    10161021
    10171022    n = polyline_nodes.shape[0] # Number of nodes in polyline       
  • branches/numpy/anuga/utilities/polygon_ext.c

    r6189 r6304  
    1010// Ole Nielsen, GA 2004
    1111//
    12 // NOTE: We use long* instead of int* for Numeric arrays as this will work both
     12// NOTE: We use long* instead of int* for numeric arrays as this will work both
    1313//       for 64 as well as 32 bit systems
    1414
    1515
    1616#include "Python.h"
    17 #include "Numeric/arrayobject.h"
     17#include "numpy/arrayobject.h"
    1818#include "math.h"
    1919
  • branches/numpy/anuga/utilities/sparse.py

    r6162 r6304  
    22"""
    33
    4 import Numeric as num
     4import numpy as num
    55
    66
     
    2222                A = num.array(args[0])
    2323            except:
    24                 raise 'Input must be convertable to a Numeric array'
     24                raise 'Input must be convertable to a numeric array'
    2525
    2626            assert len(A.shape) == 2, 'Input must be a 2d matrix'
     
    9393
    9494    def todense(self):
    95         D = num.zeros( (self.M, self.N), num.Float)
     95        D = num.zeros( (self.M, self.N), num.float)
    9696       
    9797        for i in range(self.M):
     
    105105    def __mul__(self, other):
    106106        """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.
    108108        """
    109109
     
    111111            B = num.array(other)
    112112        except:
    113             msg = 'FIXME: Only Numeric types implemented so far'
     113            msg = 'FIXME: Only numeric types implemented so far'
    114114            raise msg
    115115           
     
    127127            assert B.shape[0] == self.N, msg
    128128
    129             R = num.zeros(self.M, num.Float) #Result
     129            R = num.zeros(self.M, num.float) #Result
    130130           
    131131            # Multiply nonzero elements
     
    137137       
    138138           
    139             R = num.zeros((self.M, B.shape[1]), num.Float) #Result matrix
     139            R = num.zeros((self.M, B.shape[1]), num.float) #Result matrix
    140140
    141141            # Multiply nonzero elements
     
    190190    def trans_mult(self, other):
    191191        """Multiply the transpose of matrix with 'other' which can be
    192         a Numeric vector.
     192        a numeric vector.
    193193        """
    194194
     
    196196            B = num.array(other)
    197197        except:
    198             print 'FIXME: Only Numeric types implemented so far'
     198            print 'FIXME: Only numeric types implemented so far'
    199199
    200200
     
    205205            assert B.shape[0] == self.M, 'Mismatching dimensions'
    206206
    207             R = num.zeros((self.N,), num.Float) #Result
     207            R = num.zeros((self.N,), num.float) #Result
    208208
    209209            #Multiply nonzero elements
     
    247247            keys.sort()
    248248            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)
    252252            current_row = -1
    253253            k = 0
     
    287287
    288288    def todense(self):
    289         D = num.zeros( (self.M, self.N), num.Float)
     289        D = num.zeros( (self.M, self.N), num.float)
    290290       
    291291        for i in range(self.M):
     
    297297    def __mul__(self, other):
    298298        """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.
    300300        """
    301301
     
    303303            B = num.array(other)
    304304        except:
    305             print 'FIXME: Only Numeric types implemented so far'
     305            print 'FIXME: Only numeric types implemented so far'
    306306
    307307        return csr_mv(self,B)
     
    355355
    356356    #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]])
    358358
    359359    u = A*v[:,0]
  • branches/numpy/anuga/utilities/sparse_ext.c

    r5897 r6304  
    1111       
    1212#include "Python.h"
    13 #include "Numeric/arrayobject.h"
     13#include "numpy/arrayobject.h"
    1414#include "math.h"
    1515#include "stdio.h"
  • branches/numpy/anuga/utilities/test_cg_solve.py

    r6158 r6304  
    66
    77
    8 import Numeric as num
     8import numpy as num
    99from anuga.utilities.cg_solve import *
    1010from anuga.utilities.cg_solve import _conjugate_gradient
     
    6868                A[i,i+1] = -0.5
    6969
    70         xe = num.ones( (n,), num.Float)
     70        xe = num.ones( (n,), num.float)
    7171
    7272        b  = A*xe
     
    9696                    A[I,I+1] = -1.0
    9797
    98         xe = num.ones( (n*m,), num.Float)
     98        xe = num.ones( (n*m,), num.float)
    9999
    100100        b  = A*xe
     
    125125                    A[I,I+1] = -1.0
    126126
    127         xe = num.ones( (n*m,), num.Float)
     127        xe = num.ones( (n*m,), num.float)
    128128
    129129        # Convert to csr format
     
    158158                    A[I,I+1] = -1.0
    159159
    160         xe = num.ones( (n*m,), num.Float)
     160        xe = num.ones( (n*m,), num.float)
    161161
    162162        b  = A*xe
  • branches/numpy/anuga/utilities/test_numerical_tools.py

    r6174 r6304  
    33
    44import unittest
    5 import Numeric as num
     5import numpy as num
    66
    77from math import sqrt, pi
     
    6868        A = [1,2,3,4]
    6969        B = ensure_numeric(A)
    70         assert type(B) == num.ArrayType
    71         assert B.typecode() == 'l'
     70        assert isinstance(B, num.ndarray)
     71        assert B.dtype.char == 'l'
    7272        assert B[0] == 1 and B[1] == 2 and B[2] == 3 and B[3] == 4
    7373
    7474        A = [1,2,3.14,4]
    7575        B = ensure_numeric(A)
    76         assert type(B) == num.ArrayType
    77         assert B.typecode() == 'd'
     76        assert isinstance(B, num.ndarray)
     77        assert B.dtype.char == 'd'
    7878        assert B[0] == 1 and B[1] == 2 and B[2] == 3.14 and B[3] == 4
    7979
    8080        A = [1,2,3,4]
    81         B = ensure_numeric(A, num.Float)
    82         assert type(B) == num.ArrayType
    83         assert B.typecode() == 'd'
     81        B = ensure_numeric(A, num.float)
     82        assert isinstance(B, num.ndarray)
     83        assert B.dtype.char == 'd'
    8484        assert B[0] == 1.0 and B[1] == 2.0 and B[2] == 3.0 and B[3] == 4.0
    8585
    8686        A = [1,2,3,4]
    87         B = ensure_numeric(A, num.Float)
    88         assert type(B) == num.ArrayType
    89         assert B.typecode() == 'd'
     87        B = ensure_numeric(A, num.float)
     88        assert isinstance(B, num.ndarray)
     89        assert B.dtype.char == 'd'
    9090        assert B[0] == 1.0 and B[1] == 2.0 and B[2] == 3.0 and B[3] == 4.0
    9191
    92         A = num.array([1,2,3,4], num.Int)      #array default#
     92        A = num.array([1,2,3,4])
    9393        B = ensure_numeric(A)
    94         assert type(B) == num.ArrayType
    95         assert B.typecode() == 'l'       
     94        assert isinstance(B, num.ndarray)
     95        assert B.dtype.char == 'l'       
    9696        assert num.alltrue(A == B)   
    9797        assert A is B   #Same object
    9898
    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'       
    103111        assert num.alltrue(A == B)   
    104         assert A is not B   #Not the same object
     112        assert A is not B   # Not the same object
    105113
    106114        # Check scalars
    107115        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)
    111117        assert num.alltrue(A == B)
    112 
    113         B = ensure_numeric(A, num.Int)       
    114         #print A, B
    115         #print B.shape
     118#        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)       
    116122        assert num.alltrue(A == B)
    117123
     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
    118135        # Error situation
    119 
    120         B = ensure_numeric('hello', num.Int)               
     136        B = ensure_numeric('hello', num.int)               
    121137        assert num.allclose(B, [104, 101, 108, 108, 111])
    122138
     
    343359        assert x == 5.
    344360
    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
    346468
    347469#-------------------------------------------------------------
    348470if __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_')
    351473    runner = unittest.TextTestRunner()
    352474    runner.run(suite)
  • branches/numpy/anuga/utilities/test_polygon.py

    r6215 r6304  
    11#!/usr/bin/env python
    22
    3 
    43import unittest
    5 import Numeric as num
     4import numpy as num
    65from math import sqrt, pi
    76from anuga.utilities.numerical_tools import ensure_numeric
     
    1211from anuga.geospatial_data.geospatial_data import Geospatial_data
    1312
     13
    1414def test_function(x, y):
    1515    return x+y
     16
    1617
    1718class Test_Polygon(unittest.TestCase):
     
    2122    def tearDown(self):
    2223        pass
    23 
    2424
    2525    def test_that_C_extension_compiles(self):
     
    3333                compile(FN)
    3434            except:
    35                 raise 'Could not compile %s' %FN
     35                raise Exception, 'Could not compile %s' %FN
    3636            else:
    3737                import polygon_ext
    38 
    3938
    4039    # Polygon stuff
     
    4342        p2 = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
    4443
    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])
    5956
    6057    def test_polygon_function_csvfile(self):
    6158        from os import sep, getenv
    6259
    63 
    6460        # Get path where this test is run
    6561        path = get_pathname_from_package('anuga.utilities')
    6662
    6763        # Form absolute filename and read
    68         filename = path + sep +  'mainland_only.csv'
    69         p1 = read_polygon(filename)       
    70 
    71         f = Polygon_function( [(p1, 10.0)] )
    72         z = f([430000,480000], [490000,7720000]) # first outside, second inside
    73        
    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])
    7571
    7672    def test_polygon_function_georef(self):
    77         """Check that georeferencing works
    78         """
     73        """Check that georeferencing works"""
    7974
    8075        from anuga.coordinate_transforms.geo_reference import Geo_reference
     
    8782              [230,1010], [240,990]]
    8883
    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])
    112102
    113103    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
    117106        p1 = [[0,0], [10,0], [10,10], [0,10]]
    118107        p2 = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
    119108
    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])
    143128
    144129    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]])
    166153
    167154        # 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]])
    172157
    173158    def test_is_inside_polygon_main(self):
    174 
    175 
    176159        # Simplest case: Polygon is the unit square
    177160        polygon = [[0,0], [1,0], [1,1], [0,1]]
    178161
    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)
    196178
    197179    def test_inside_polygon_main(self):
    198 
    199180        # 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]]
    201182
    202183        # 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
    217196        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
    227205        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)
    239215        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
    262234        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)
    269239
    270240    def test_duplicate_points_being_ok(self):
    271 
    272 
    273241        # Simplest case: Polygon is the unit square
    274242        polygon = [[0,0], [1,0], [1,0], [1,0], [1,1], [0,1], [0,0]]
    275243
    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         # Try point on borders
    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)
    292260
    293261        # 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
    300266
    301267    def test_inside_polygon_vector_version(self):
    302         # Now try the vector formulation returning indices
     268        # Now try the vector formulation returning indices
    303269        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] )
    308273
    309274    def test_outside_polygon(self):
    310         U = [[0,0], [1,0], [1,1], [0,1]] #Unit square   
    311 
    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
    313278        # 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
    316281        # 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
    321287        # One more test of vector formulation returning indices
    322288        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])
    329292
    330293        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
    336300    def test_outside_polygon2(self):
    337         U = [[0,0], [1,0], [1,1], [0,1]] #Unit square   
    338    
    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
    340304        # 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
    343307        # 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)
    344309
    345310    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
    353317
    354318        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])
    358321
    359322        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])
    361324
    362325        indices = inside_polygon(points, U, closed = True)
    363         assert num.allclose(indices, [])               
    364 
     326        assert num.allclose(indices, [])
    365327
    366328    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)
    374335
    375336        indices, count = separate_points_by_polygon(points, U)
    376         assert count == 3 #All inside
    377         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)
    380341        assert num.allclose(indices, [])
    381342
    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
    385346
    386347    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] )
    391356        assert count == 2
    392        
    393         #One more test of vector formulation returning indices
     357
     358        # One more test of vector formulation returning indices
    394359        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
    401365
    402366        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 == 3
    408        
     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
    409373
    410374    def test_populate_polygon(self):
    411 
    412375        polygon = [[0,0], [1,0], [1,1], [0,1]]
    413376        points = populate_polygon(polygon, 5)
     
    417380            assert is_inside_polygon(point, polygon)
    418381
    419 
    420         #Very convoluted polygon
     382        # Very convoluted polygon
    421383        polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
    422 
    423384        points = populate_polygon(polygon, 5)
    424 
    425385        assert len(points) == 5
    426386        for point in points:
    427387            assert is_inside_polygon(point, polygon)
    428388
    429 
    430389    def test_populate_polygon_with_exclude(self):
    431        
    432 
    433390        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 quarter
    435         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])
    436393
    437394        assert len(points) == 5
    438395        for point in points:
    439396            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
    444400        polygon = [[0,0], [1,0], [1,1], [0,1]]
    445401        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])
    447403
    448404        assert len(points) == 5
    449405        for point in points:
    450406            assert is_inside_polygon(point, polygon)
    451             assert not is_inside_polygon(point, ex_poly)                       
    452        
    453         #Multiple
     407            assert not is_inside_polygon(point, ex_poly)
     408
     409        # Multiple
    454410        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 quarter
    456         ex_poly2 = [[0.5,0.5], [0.5,1], [1, 1], [1,0.5]] #NE quarter       
    457        
    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])
    459415
    460416        assert len(points) == 20
     
    462418            assert is_inside_polygon(point, polygon)
    463419            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
    468423        polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
    469424        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
    472427        assert len(points) == 20
    473428        for point in points:
    474429            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)
    477431
    478432    def test_populate_polygon_with_exclude2(self):
    479        
    480 
    481         min_outer = 0
     433        min_outer = 0
    482434        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]]
    485437
    486438        delta = 10
    487439        min_inner1 = min_outer + delta
    488440        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 = 1000
    494         min_inner2 = min_outer + 2*delta
    495         max_inner2 = max_outer -  2*delta
    496         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])
    500452
    501453        assert len(points) == 20
     
    503455            assert is_inside_polygon(point, polygon_outer)
    504456            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
    509460        polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
    510461        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
    513464        assert len(points) == 20
    514465        for point in points:
    515466            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)
    517468
    518469    def test_point_in_polygon(self):
     
    521472        assert is_inside_polygon(point, polygon)
    522473
    523         #this may get into a vicious loop
    524         #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
    526477        polygon = [[1e15,1e7], [1,0], [1,1], [0,1]]
    527478        point = point_in_polygon(polygon)
    528479        assert is_inside_polygon(point, polygon)
    529480
    530 
    531481        polygon = [[0,0], [1,0], [1,1], [1e8,1e8]]
    532482        point = point_in_polygon(polygon)
    533483        assert is_inside_polygon(point, polygon)
    534484
    535        
    536485        polygon = [[1e32,1e54], [-1e32,1e54], [1e32,-1e54]]
    537486        point = point_in_polygon(polygon)
    538487        assert is_inside_polygon(point, polygon)
    539488
    540        
    541489        polygon = [[1e18,1e15], [1,0], [0,1]]
    542490        point = point_in_polygon(polygon)
     
    544492
    545493    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
    549495        polygon = [[0,0], [1,0], [1,1], [0,1]]
    550496
    551         inside, outside =  in_and_outside_polygon( (0.5, 0.5), polygon )
    552         assert inside[0] == 0
    553         assert len(outside) == 0
    554        
    555         inside, outside =  in_and_outside_polygon(  (1., 0.5), polygon, closed=True)
    556         assert inside[0] == 0
    557         assert len(outside) == 0
    558        
    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])
    583529
    584530    def test_intersection1(self):
     
    608554        status, value = intersection(line1, line0)
    609555        assert status == 1
    610         assert num.allclose(value, [12.0, 6.0])       
    611        
     556        assert num.allclose(value, [12.0, 6.0])
     557
    612558    def test_intersection3(self):
    613559        line0 = [[0,0], [24,12]]
     
    623569        status, value = intersection(line0, line1)
    624570        assert status == 1
    625         assert num.allclose(value, [14.068965517, 7.0344827586])       
     571        assert num.allclose(value, [14.068965517, 7.0344827586])
    626572
    627573        # Swap order of lines
    628574        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])
    632577
    633578    def test_intersection_endpoints(self):
     
    636581        Test that coinciding endpoints are picked up
    637582        """
     583
    638584        line0 = [[0,0], [1,1]]
    639585        line1 = [[1,1], [2,1]]
     
    643589        assert num.allclose(value, [1.0, 1.0])
    644590
    645 
    646591        line0 = [[1,1], [2,0]]
    647592        line1 = [[1,1], [2,1]]
     
    649594        status, value = intersection(line0, line1)
    650595        assert status == 1
    651         assert num.allclose(value, [1.0, 1.0])       
    652 
     596        assert num.allclose(value, [1.0, 1.0])
    653597
    654598    # This function is a helper function for
     
    660604        # 0:         ---->----
    661605        # 1:                     --------->-----------
    662         line0 = [P1,P2]
    663         line1 = [P3,P4]
     606        line0 = [P1, P2]
     607        line1 = [P3, P4]
    664608        status, value = intersection(line0, line1)
    665609        self.failIf(status!=3, 'Expected status 3, got status=%s, value=%s' %
     
    671615        # 0:         ----<----
    672616        # 1:                     ---------<-----------
    673         line0 = [P2,P1]
    674         line1 = [P4,P3]
     617        line0 = [P2, P1]
     618        line1 = [P4, P3]
    675619        status, value = intersection(line0, line1)
    676620        self.failIf(status!=3, 'Expected status 3, got status=%s, value=%s' %
     
    682626        # 0:         ----<----
    683627        # 1:                     --------->-----------
    684         line0 = [P2,P1]
    685         line1 = [P3,P4]
     628        line0 = [P2, P1]
     629        line1 = [P3, P4]
    686630        status, value = intersection(line0, line1)
    687631        self.failIf(status!=3, 'Expected status 3, got status=%s, value=%s' %
     
    693637        # 0:         ---->----
    694638        # 1:                     ---------<-----------
    695         line0 = [P1,P2]
    696         line1 = [P4,P3]
     639        line0 = [P1, P2]
     640        line1 = [P4, P3]
    697641        status, value = intersection(line0, line1)
    698642        self.failIf(status!=3, 'Expected status 3, got status=%s, value=%s' %
     
    701645                                       str(value))
    702646
    703         #----------------------------------------------------------------------
     647        # ----------------------------------------------------------------------
    704648
    705649        # line0 fully within line1, same direction
     
    708652        # value should be line0:
    709653        #            ---->----
    710         line0 = [P2,P3]
    711         line1 = [P1,P4]
     654        line0 = [P2, P3]
     655        line1 = [P1, P4]
    712656        status, value = intersection(line0, line1)
    713657        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    720664        # value should be line0:
    721665        #            ----<----
    722         line0 = [P3,P2]
    723         line1 = [P4,P1]
     666        line0 = [P3, P2]
     667        line1 = [P4, P1]
    724668        status, value = intersection(line0, line1)
    725669        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    732676        # value should be line0:
    733677        #            ----<----
    734         line0 = [P3,P2]
    735         line1 = [P1,P4]
     678        line0 = [P3, P2]
     679        line1 = [P1, P4]
    736680        status, value = intersection(line0, line1)
    737681        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    744688        # value should be line0:
    745689        #            ---->----
    746         line0 = [P2,P3]
    747         line1 = [P4,P1]
     690        line0 = [P2, P3]
     691        line1 = [P4, P1]
    748692        status, value = intersection(line0, line1)
    749693        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    751695        self.failUnless(num.allclose(value, line0))
    752696
    753         #----------------------------------------------------------------------
     697        # ----------------------------------------------------------------------
    754698
    755699        # line1 fully within line0, same direction
     
    758702        # value should be line1:
    759703        #            ---->----
    760         line0 = [P1,P4]
    761         line1 = [P2,P3]
     704        line0 = [P1, P4]
     705        line1 = [P2, P3]
    762706        status, value = intersection(line0, line1)
    763707        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    770714        # value should be line1:
    771715        #            ----<----
    772         line0 = [P4,P1]
    773         line1 = [P3,P2]
     716        line0 = [P4, P1]
     717        line1 = [P3, P2]
    774718        status, value = intersection(line0, line1)
    775719        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    782726        # value should be line1:
    783727        #            ---->----
    784         line0 = [P4,P1]
    785         line1 = [P2,P3]
     728        line0 = [P4, P1]
     729        line1 = [P2, P3]
    786730        status, value = intersection(line0, line1)
    787731        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    794738        # value should be line1:
    795739        #            ----<----
    796         line0 = [P1,P4]
    797         line1 = [P3,P2]
     740        line0 = [P1, P4]
     741        line1 = [P3, P2]
    798742        status, value = intersection(line0, line1)
    799743        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    801745        self.failUnless(num.allclose(value, line1))
    802746
    803         #----------------------------------------------------------------------
     747        # ----------------------------------------------------------------------
    804748
    805749        # line in same direction, partial overlap
     
    808752        # value should be segment line1_start->line0_end:
    809753        #          --->----
    810         line0 = [P1,P3]
    811         line1 = [P2,P4]
     754        line0 = [P1, P3]
     755        line1 = [P2, P4]
    812756        status, value = intersection(line0, line1)
    813757        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    820764        # value should be segment line0_start->line1_end:
    821765        #          ---<----
    822         line0 = [P3,P1]
    823         line1 = [P4,P2]
     766        line0 = [P3, P1]
     767        line1 = [P4, P2]
    824768        status, value = intersection(line0, line1)
    825769        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    832776        # value should be segment line0_start->line1_start:
    833777        #          ---<----
    834         line0 = [P3,P1]
    835         line1 = [P2,P4]
     778        line0 = [P3, P1]
     779        line1 = [P2, P4]
    836780        status, value = intersection(line0, line1)
    837781        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    844788        # value should be segment line1_end->line0_end:
    845789        #          --->----
    846         line0 = [P1,P3]
    847         line1 = [P4,P2]
     790        line0 = [P1, P3]
     791        line1 = [P4, P2]
    848792        status, value = intersection(line0, line1)
    849793        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    851795        self.failUnless(num.allclose(value, [line1[1],line0[1]]))
    852796
    853         #----------------------------------------------------------------------
     797        # ----------------------------------------------------------------------
    854798
    855799        # line in same direction, partial overlap
     
    858802        # value should be segment line0_start->line1_end:
    859803        #          --->----
    860         line0 = [P2,P4]
    861         line1 = [P1,P3]
     804        line0 = [P2, P4]
     805        line1 = [P1, P3]
    862806        status, value = intersection(line0, line1)
    863807        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    870814        # value should be segment line1_start->line0_end:
    871815        #          ----<-----
    872         line0 = [P4,P2]
    873         line1 = [P3,P1]
     816        line0 = [P4, P2]
     817        line1 = [P3, P1]
    874818        status, value = intersection(line0, line1)
    875819        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    882826        # value should be segment line1_end->line0_end:
    883827        #          --->----
    884         line0 = [P4,P2]
    885         line1 = [P1,P3]
     828        line0 = [P4, P2]
     829        line1 = [P1, P3]
    886830        status, value = intersection(line0, line1)
    887831        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    894838        # value should be segment line0_start->line1_start:
    895839        #          ---<----
    896         line0 = [P2,P4]
    897         line1 = [P3,P1]
     840        line0 = [P2, P4]
     841        line1 = [P3, P1]
    898842        status, value = intersection(line0, line1)
    899843        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    901845        self.failUnless(num.allclose(value, [line0[0],line1[0]]))
    902846
    903         #----------------------------------------------------------------------
     847        # ----------------------------------------------------------------------
    904848
    905849        # line in same direction, same left point, line1 longer
     
    908852        # value should be line0:
    909853        #       ----->------
    910         line0 = [P1,P3]
    911         line1 = [P1,P4]
     854        line0 = [P1, P3]
     855        line1 = [P1, P4]
    912856        status, value = intersection(line0, line1)
    913857        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    920864        # value should be line0:
    921865        #       -----<------
    922         line0 = [P3,P1]
    923         line1 = [P4,P1]
     866        line0 = [P3, P1]
     867        line1 = [P4, P1]
    924868        status, value = intersection(line0, line1)
    925869        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    932876        # value should be line0:
    933877        #       ----->------
    934         line0 = [P1,P3]
    935         line1 = [P4,P1]
     878        line0 = [P1, P3]
     879        line1 = [P4, P1]
    936880        status, value = intersection(line0, line1)
    937881        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    944888        # value should be line0:
    945889        #       -----<------
    946         line0 = [P3,P1]
    947         line1 = [P1,P4]
     890        line0 = [P3, P1]
     891        line1 = [P1, P4]
    948892        status, value = intersection(line0, line1)
    949893        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    951895        self.failUnless(num.allclose(value, line0))
    952896
    953         #----------------------------------------------------------------------
     897        # ----------------------------------------------------------------------
    954898
    955899        # line in same direction, same left point, same right point
     
    958902        # value should be line0 or line1:
    959903        #       ------->--------
    960         line0 = [P1,P3]
    961         line1 = [P1,P3]
     904        line0 = [P1, P3]
     905        line1 = [P1, P3]
    962906        status, value = intersection(line0, line1)
    963907        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    970914        # value should be line0 (or line1):
    971915        #       -------<--------
    972         line0 = [P3,P1]
    973         line1 = [P3,P1]
     916        line0 = [P3, P1]
     917        line1 = [P3, P1]
    974918        status, value = intersection(line0, line1)
    975919        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    982926        # value should be line0:
    983927        #       ------->--------
    984         line0 = [P1,P3]
    985         line1 = [P3,P1]
     928        line0 = [P1, P3]
     929        line1 = [P3, P1]
    986930        status, value = intersection(line0, line1)
    987931        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    994938        # value should be line0:
    995939        #       -------<--------
    996         line0 = [P3,P1]
    997         line1 = [P1,P3]
     940        line0 = [P3, P1]
     941        line1 = [P1, P3]
    998942        status, value = intersection(line0, line1)
    999943        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    1001945        self.failUnless(num.allclose(value, line0))
    1002946
    1003         #----------------------------------------------------------------------
     947        # ----------------------------------------------------------------------
    1004948
    1005949        # line in same direction, same right point, line1 longer
     
    1008952        # value should be line0:
    1009953        #           ----->------
    1010         line0 = [P2,P4]
    1011         line1 = [P1,P4]
     954        line0 = [P2, P4]
     955        line1 = [P1, P4]
    1012956        status, value = intersection(line0, line1)
    1013957        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    1020964        # value should be line0:
    1021965        #           -----<------
    1022         line0 = [P4,P2]
    1023         line1 = [P4,P1]
     966        line0 = [P4, P2]
     967        line1 = [P4, P1]
    1024968        status, value = intersection(line0, line1)
    1025969        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    1032976        # value should be line0:
    1033977        #           ----->------
    1034         line0 = [P2,P4]
    1035         line1 = [P4,P1]
     978        line0 = [P2, P4]
     979        line1 = [P4, P1]
    1036980        status, value = intersection(line0, line1)
    1037981        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    1044988        # value should be line0:
    1045989        #           -----<------
    1046         line0 = [P4,P2]
    1047         line1 = [P1,P4]
     990        line0 = [P4, P2]
     991        line1 = [P1, P4]
    1048992        status, value = intersection(line0, line1)
    1049993        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    1051995        self.failUnless(num.allclose(value, line0))
    1052996
    1053         #----------------------------------------------------------------------
     997        # ----------------------------------------------------------------------
    1054998
    1055999        # line in same direction, same left point, line0 longer
     
    10581002        # value should be line1:
    10591003        #       ----->------
    1060         line0 = [P1,P4]
    1061         line1 = [P1,P3]
     1004        line0 = [P1, P4]
     1005        line1 = [P1, P3]
    10621006        status, value = intersection(line0, line1)
    10631007        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    10701014        # value should be line1:
    10711015        #       -----<------
    1072         line0 = [P4,P1]
    1073         line1 = [P3,P1]
     1016        line0 = [P4, P1]
     1017        line1 = [P3, P1]
    10741018        status, value = intersection(line0, line1)
    10751019        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    10821026        # value should be line1:
    10831027        #       -----<------
    1084         line0 = [P1,P4]
    1085         line1 = [P3,P1]
     1028        line0 = [P1, P4]
     1029        line1 = [P3, P1]
    10861030        status, value = intersection(line0, line1)
    10871031        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    10941038        # value should be line1:
    10951039        #       ----->------
    1096         line0 = [P4,P1]
    1097         line1 = [P1,P3]
     1040        line0 = [P4, P1]
     1041        line1 = [P1, P3]
    10981042        status, value = intersection(line0, line1)
    10991043        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    11011045        self.failUnless(num.allclose(value, line1))
    11021046
    1103         #----------------------------------------------------------------------
     1047        # ----------------------------------------------------------------------
    11041048
    11051049        # line in same direction, same right point, line0 longer
     
    11081052        # value should be line1:
    11091053        #           ----->------
    1110         line0 = [P1,P4]
    1111         line1 = [P2,P4]
     1054        line0 = [P1, P4]
     1055        line1 = [P2, P4]
    11121056        status, value = intersection(line0, line1)
    11131057        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    11201064        # value should be line1:
    11211065        #           -----<------
    1122         line0 = [P4,P1]
    1123         line1 = [P4,P2]
     1066        line0 = [P4, P1]
     1067        line1 = [P4, P2]
    11241068        status, value = intersection(line0, line1)
    11251069        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    11321076        # value should be line1:
    11331077        #           -----<------
    1134         line0 = [P1,P4]
    1135         line1 = [P4,P2]
     1078        line0 = [P1, P4]
     1079        line1 = [P4, P2]
    11361080        status, value = intersection(line0, line1)
    11371081        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    11441088        # value should be line1:
    11451089        #           ----->------
    1146         line0 = [P4,P1]
    1147         line1 = [P2,P4]
     1090        line0 = [P4, P1]
     1091        line1 = [P2, P4]
    11481092        status, value = intersection(line0, line1)
    11491093        self.failIf(status!=2, 'Expected status 2, got status=%s, value=%s' %
     
    11511095        self.failUnless(num.allclose(value, line1))
    11521096
    1153        
     1097
    11541098    def test_intersection_bug_20081110_TR(self):
    11551099        """test_intersection_bug_20081110(self)
     
    11641108        P3 = [3.0, 3.0]
    11651109        P4 = [4.0, 4.0]
    1166        
     1110
    11671111        self.helper_test_parallel_intersection_code(P1, P2, P3, P4)
    11681112        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)
    11701114        P1 = [1.0, 1.0]
    11711115        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)
    11731117        P2 = [2.0, 2.0]
    11741118        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)
    11761120        P3 = [3.0, 3.0]
    11771121        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)
    11791123
    11801124    def test_intersection_bug_20081110_TL(self):
     
    11901134        P3 = [-3.0, 3.0]
    11911135        P4 = [-4.0, 4.0]
    1192        
     1136
    11931137        self.helper_test_parallel_intersection_code(P1, P2, P3, P4)
    11941138        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)
    11961140        P1 = [-1.0, 1.0]
    11971141        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)
    11991143        P2 = [-2.0, 2.0]
    12001144        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)
    12021146        P3 = [-3.0, 3.0]
    12031147        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)
    12051149
    12061150    def test_intersection_bug_20081110_BL(self):
     
    12161160        P3 = [-3.0, -3.0]
    12171161        P4 = [-4.0, -4.0]
    1218        
     1162
    12191163        self.helper_test_parallel_intersection_code(P1, P2, P3, P4)
    12201164        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)
    12221166        P1 = [-1.0, -1.0]
    12231167        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)
    12251169        P2 = [-2.0, -2.0]
    12261170        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)
    12281172        P3 = [-3.0, -3.0]
    12291173        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)
    12311175
    12321176    def test_intersection_bug_20081110_BR(self):
     
    12421186        P3 = [3.0, -3.0]
    12431187        P4 = [4.0, -4.0]
    1244        
     1188
    12451189        self.helper_test_parallel_intersection_code(P1, P2, P3, P4)
    12461190        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)
    12481192        P1 = [1.0, -1.0]
    12491193        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)
    12511195        P2 = [2.0, -2.0]
    12521196        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)
    12541198        P3 = [3.0, -3.0]
    12551199        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)
    12571201
    12581202    def test_intersection_bug_20081110_TR_TL(self):
     
    12631207
    12641208        # define 4 collinear points, 1 in TL, 3 in TR
    1265         #    P1---P2---P3---P4
     1209        #    P1-+-P2---P3---P4
    12661210        P1 = [-3.0, 1.0]
    12671211        P2 = [ 1.0, 5.0]
     
    12711215
    12721216        # define 4 collinear points, 2 in TL, 2 in TR
    1273         #    P1---P2---P3---P4
     1217        #    P1---P2-+-P3---P4
    12741218        P1 = [-3.0, 1.0]
    12751219        P2 = [-2.0, 2.0]
     
    12781222        self.helper_test_parallel_intersection_code(P1, P2, P3, P4)
    12791223
    1280         # define 4 collinear points, 2 in TL, 1 in TR
    1281         #    P1---P2---P3---P4
     1224        # define 4 collinear points, 3 in TL, 1 in TR
     1225        #    P1---P2---P3-+-P4
    12821226        P1 = [-3.0, 1.0]
    12831227        P2 = [-2.0, 2.0]
     
    12931237
    12941238        # define 4 collinear points, 1 in BL, 3 in TR
    1295         #    P1---P2---P3---P4
     1239        #    P1-+-P2---P3---P4
    12961240        P1 = [-4.0, -3.0]
    12971241        P2 = [ 1.0,  2.0]
     
    13011245
    13021246        # define 4 collinear points, 2 in TL, 2 in TR
    1303         #    P1---P2---P3---P4
     1247        #    P1---P2-+-P3---P4
    13041248        P1 = [-4.0, -3.0]
    13051249        P2 = [-3.0, -2.0]
     
    13091253
    13101254        # define 4 collinear points, 3 in TL, 1 in TR
    1311         #    P1---P2---P3---P4
     1255        #    P1---P2---P3-+-P4
    13121256        P1 = [-4.0, -3.0]
    13131257        P2 = [-3.0, -2.0]
     
    13231267
    13241268        # define 4 collinear points, 1 in BR, 3 in TR
    1325         #    P1---P2---P3---P4
     1269        #    P1-+-P2---P3---P4
    13261270        P1 = [ 1.0, -3.0]
    13271271        P2 = [ 5.0,  1.0]
     
    13311275
    13321276        # define 4 collinear points, 2 in BR, 2 in TR
    1333         #    P1---P2---P3---P4
     1277        #    P1---P2-+-P3---P4
    13341278        P1 = [ 1.0, -3.0]
    13351279        P2 = [ 2.0, -2.0]
     
    13391283
    13401284        # define 4 collinear points, 3 in BR, 1 in TR
    1341         #    P1---P2---P3---P4
     1285        #    P1---P2---P3-+-P4
    13421286        P1 = [ 1.0, -3.0]
    13431287        P2 = [ 2.0, -2.0]
     
    13481292
    13491293    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.
    13511296        """
    1352              
     1297
    13531298        line0 = [[0,0], [100,100]]
    13541299
    13551300        common_end_point = [20, 150]
    1356        
     1301
    13571302        for i in range(100):
    13581303            x = 20 + i * 1.0/100
     
    13621307            assert status == 1
    13631308
    1364 
    13651309            # Swap direction of line1
    1366             line1 = [common_end_point, [x,0]]           
     1310            line1 = [common_end_point, [x,0]]
    13671311            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)
    13761318            assert num.allclose(p1, p2), msg
    13771319
    13781320            # Swap order of lines
    13791321            status, p3 = intersection(line1, line0)
    1380             assert status == 1                       
     1322            assert status == 1
    13811323            msg = 'Order of lines gave different results'
    13821324            assert num.allclose(p1, p3), msg
    1383            
    13841325
    13851326    def test_no_intersection(self):
     
    13901331        assert status == 0
    13911332        assert value is None
    1392        
    13931333
    13941334    def test_intersection_parallel(self):
     
    13971337
    13981338        status, value = intersection(line0, line1)
    1399         assert status == 4       
     1339        assert status == 4
    14001340        assert value is None
    1401 
    14021341
    14031342        line0 = [[0,0], [10,100]]
     
    14051344
    14061345        status, value = intersection(line0, line1)
    1407         assert status == 4               
    1408         assert value is None       
    1409 
     1346        assert status == 4
     1347        assert value is None
    14101348
    14111349    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"""
    14151351
    14161352        # Overlap 1
     
    14281364        status, value = intersection(line0, line1)
    14291365        assert status == 2
    1430         assert num.allclose(value, [[-3, 0], [5,0]])       
     1366        assert num.allclose(value, [[-3, 0], [5,0]])
    14311367
    14321368        # Inclusion 1
     
    14351371
    14361372        status, value = intersection(line0, line1)
    1437         assert status == 2       
     1373        assert status == 2
    14381374        assert num.allclose(value, line1)
    14391375
     
    14431379
    14441380        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)
    14481383
    14491384        # Exclusion (no intersection)
     
    14521387
    14531388        status, value = intersection(line0, line1)
    1454         assert status == 3       
     1389        assert status == 3
    14551390        assert value is None
    1456        
    14571391
    14581392        # Try examples with some slope (y=2*x+5)
     
    14621396        line1 = [[1,7], [10,25]]
    14631397        status, value = intersection(line0, line1)
    1464         assert status == 2               
     1398        assert status == 2
    14651399        assert num.allclose(value, [[1, 7], [7, 19]])
    14661400
     
    14801414        status, value = intersection(line0, line1)
    14811415        assert status == 2
    1482         assert num.allclose(value, [[1, 7], [7, 19]])       
    1483        
     1416        assert num.allclose(value, [[1, 7], [7, 19]])
    14841417
    14851418        # Inclusion
     
    14871420        line1 = [[0,5], [10,25]]
    14881421        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]])
    14911424
    14921425        line0 = [[0,5], [10,25]]
    14931426        line1 = [[1,7], [7,19]]
    14941427        status, value = intersection(line0, line1)
    1495         assert status == 2                       
     1428        assert status == 2
    14961429        assert num.allclose(value, [[1,7], [7, 19]])
    1497 
    14981430
    14991431        line0 = [[0,5], [10,25]]
    15001432        line1 = [[7,19], [1,7]]
    15011433        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?
    15091440        print "inside",inside
    15101441        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])
    15411470
    15421471    def test_polygon_area(self):
    1543 
    1544         #Simplest case: Polygon is the unit square
     1472        # Simplest case: Polygon is the unit square
    15451473        polygon = [[0,0], [1,0], [1,1], [0,1]]
    1546         assert polygon_area(polygon) == 1
    1547 
    1548         #Simple case: Polygon is a rectangle
     1474        assert polygon_area(polygon) == 1
     1475
     1476        # Simple case: Polygon is a rectangle
    15491477        polygon = [[0,0], [1,0], [1,4], [0,4]]
    1550         assert polygon_area(polygon) == 4
    1551 
    1552         #Simple case: Polygon is a unit triangle
     1478        assert polygon_area(polygon) == 4
     1479
     1480        # Simple case: Polygon is a unit triangle
    15531481        polygon = [[0,0], [1,0], [0,1]]
    1554         assert polygon_area(polygon) == 0.5
    1555 
    1556         #Simple case: Polygon is a diamond
     1482        assert polygon_area(polygon) == 0.5
     1483
     1484        # Simple case: Polygon is a diamond
    15571485        polygon = [[0,0], [1,1], [2,0], [1, -1]]
    1558         assert polygon_area(polygon) == 2.0
    1559        
     1486        assert polygon_area(polygon) == 2.0
     1487
    15601488        # Complex case where numerical errors might occur
    15611489        polygon = [[314037.58727982, 6224952.2960092],
    1562                    [314038.58727982, 6224952.2960092], 
     1490                   [314038.58727982, 6224952.2960092],
    15631491                   [314038.58727982, 6224953.2960092],
    15641492                   [314037.58727982, 6224953.2960092]]
    1565         assert polygon_area(polygon) == 1.0                   
    1566 
     1493        assert polygon_area(polygon) == 1.0
    15671494
    15681495    def test_poly_xy(self):
    1569  
    1570         #Simplest case: Polygon is the unit square
     1496        # Simplest case: Polygon is the unit square
    15711497        polygon = [[0,0], [1,0], [1,1], [0,1]]
    15721498        x, y = poly_xy(polygon)
    1573         assert len(x) == len(polygon)+1
    1574         assert len(y) == len(polygon)+1
    1575         assert x[0] == 0
    1576         assert x[1] == 1
    1577         assert x[2] == 1
    1578         assert x[3] == 0
    1579         assert y[0] == 0
    1580         assert y[1] == 0
    1581         assert y[2] == 1
    1582         assert y[3] == 1
    1583 
    1584         #Arbitrary polygon
     1499        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
    15851511        polygon = [[1,5], [1,1], [100,10], [1,10], [3,6]]
    15861512        x, y = poly_xy(polygon)
    1587         assert len(x) == len(polygon)+1
    1588         assert len(y) == len(polygon)+1
    1589         assert x[0] == 1
    1590         assert x[1] == 1
    1591         assert x[2] == 100
    1592         assert x[3] == 1
    1593         assert x[4] == 3
    1594         assert y[0] == 5
    1595         assert y[1] == 1
    1596         assert y[2] == 10
    1597         assert y[3] == 10
    1598         assert y[4] == 6
    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
    16011527    def xtest_plot_polygons(self):
    1602        
    16031528        import os
    1604        
    1605         #Simplest case: Polygon is the unit square
     1529
     1530        # Simplest case: Polygon is the unit square
    16061531        polygon1 = [[0,0], [1,0], [1,1], [0,1]]
    16071532        polygon2 = [[1,1], [2,1], [3,2], [2,2]]
    1608         v = plot_polygons([polygon1, polygon2],'test1')
    1609         assert len(v) == 4
    1610         assert v[0] == 0
    1611         assert v[1] == 3
    1612         assert v[2] == 0
    1613         assert v[3] == 2
    1614 
    1615         #Another case
     1533        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
    16161541        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
    16281552    def test_inside_polygon_geospatial(self):
    1629 
    1630 
     1553        # Simplest case: Polygon is the unit square
    16311554        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)
    16401556        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),
    16521565                                 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)
    16591572
    16601573    def NOtest_decimate_polygon(self):
    1661 
    16621574        polygon = [[0,0], [10,10], [15,5], [20, 10],
    16631575                   [25,0], [30,10], [40,-10], [35, -5]]
    16641576
    1665         #plot_polygons([polygon], figname='test')
    1666        
    16671577        dpoly = decimate_polygon(polygon, factor=2)
    16681578
    16691579        print dpoly
    1670        
     1580
    16711581        assert len(dpoly)*2==len(polygon)
    16721582
     
    16751585        for point in polygon[1:]:
    16761586            x, y = point
    1677            
     1587
    16781588            if x < minx: minx = x
    16791589            if x > maxx: maxx = x
    16801590            if y < miny: miny = y
    16811591            if y > maxy: maxy = y
    1682            
    16831592
    16841593        assert [minx, miny] in polygon
     
    16861595        assert [minx, maxy] in polygon
    16871596        assert [maxx, miny] in polygon
    1688         assert [maxx, maxy] in polygon               
    1689        
    1690 
    1691        
     1597        assert [maxx, maxy] in polygon
     1598
    16921599    def test_interpolate_polyline(self):
    16931600        """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.
    16971606        """
    1698        
     1607
    16991608        f = num.array([58.06150614, 58.06150614, 58.06150614])
    17001609        vertex_coordinates = num.array([[0., 0., ],
     
    17091618                                       [5.11996623e+02, -1.85956061e+00],
    17101619                                       [2.02046270e+00, 5.53055373e+02]])
    1711                              
     1620
    17121621        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)
    17151625        assert num.allclose(z, z_ref)
    1716        
     1626
    17171627        # Another f
    17181628        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)
    17231633
    17241634        # Other and simpler numbers
    1725         f = num.array([1, 5, 13])       
     1635        f = num.array([1, 5, 13])
    17261636        vertex_coordinates = num.array([[0., 0., ],
    17271637                                        [4., 4.],
    1728                                         [8., 8.]])       
     1638                                        [8., 8.]])
    17291639        point_coordinates = num.array([[0.1, 0.1],
    17301640                                       [3.5, 3.5],
     
    17341644                                       [8.3, 8.3]])
    17351645        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)
    17381649        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
    17421652        # 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)
    17471658        except Exception:
    17481659            pass
    17491660        else:
    17501661            raise Exception, 'One point should have raised exception'
    1751        
    17521662
    17531663        # More polyline nodes
    1754         data = num.array([1, 5, 13, 12, 6, 29])       
     1664        data = num.array([1, 5, 13, 12, 6, 29])
    17551665        polyline_nodes = num.array([[0., 0.],
    17561666                                    [4., 4.],
     
    17591669                                    [10., 5.],
    17601670                                    [10., 0.]])
    1761                                                
    17621671        point_coordinates = num.array([[0.1, 0.1],
    17631672                                       [3.5, 3.5],
     
    17711680                                       [10., 4.3],
    17721681                                       [10., 1.0]])
    1773                                        
    17741682        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)
    17771685        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# -------------------------------------------------------------
    17831690if __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')
    17851693    runner = unittest.TextTestRunner()
    17861694    runner.run(suite)
    1787 
    1788 
    1789 
    1790 
  • branches/numpy/anuga/utilities/test_quad.py

    r6158 r6304  
    11import unittest
    2 import Numeric as num
     2import numpy as num
    33
    44from quad import Cell, build_quadtree
  • branches/numpy/anuga/utilities/test_sparse.py

    r6174 r6304  
    55
    66from sparse import *
    7 import Numeric as num
     7import numpy as num
    88
    99
     
    8686
    8787        #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]])
    8989
    9090        u = A*v[:,0]
     
    104104
    105105        #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]])
    107107
    108108        u = A*v
  • branches/numpy/anuga/utilities/test_system_tools.py

    r6158 r6304  
    33
    44import unittest
    5 import Numeric as num
     5import numpy as num
    66import zlib
    77from os.path import join, split, sep
    88from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
     9from anuga.config import netcdf_float
    910
    1011
     
    8283            pass
    8384        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)
    8587
    8688            # First file
     
    8890            fid = NetCDFFile(filename1, netcdf_mode_w)
    8991            fid.createDimension('two', 2)
    90             fid.createVariable('test_array', num.Float,
     92            fid.createVariable('test_array', netcdf_float,
    9193                               ('two', 'two'))
    9294            fid.variables['test_array'][:] = test_array
     
    9799            fid = NetCDFFile(filename2, netcdf_mode_w)
    98100            fid.createDimension('two', 2)
    99             fid.createVariable('test_array', num.Float,
     101            fid.createVariable('test_array', netcdf_float,
    100102                               ('two', 'two'))
    101103            fid.variables['test_array'][:] = test_array
  • branches/numpy/anuga/utilities/util_ext.c

    r5897 r6304  
    1010// Ole Nielsen, GA 2004
    1111//
    12 //NOTE: On 64 bit systems use long* instead of int* for Numeric arrays
     12//NOTE: On 64 bit systems use long* instead of int* for numeric arrays
    1313//this will also work on 32 bit systems
    1414
     
    1616
    1717#include "Python.h"
    18 #include "Numeric/arrayobject.h"
     18#include "numpy/arrayobject.h"
    1919#include "math.h"
    2020
  • branches/numpy/anuga/utilities/util_ext.h

    r5897 r6304  
    1111       
    1212#include "Python.h"     
    13 #include "Numeric/arrayobject.h"
     13#include "numpy/arrayobject.h"
    1414#include "math.h"
    1515
  • branches/numpy/anuga/utilities/where_close.py

    r5681 r6304  
    6262    y are "equal", and 0 otherwise.  If x or y are floating point,
    6363    "equal" means where abs(x-y) <= atol + rtol * abs(y).  This is
    64     essentially the same algorithm used in the Numeric function
     64    essentially the same algorithm used in the numeric function
    6565    allclose.  If x and y are integer, "equal" means strict equality. 
    6666    Shape and size of output is the same as x and y; if one is an
    6767    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 inputs
     68    same as the array.  Output is a numeric array, unless both inputs
    6969    are scalar in which the output is a Python integer scalar.
    7070
    7171    Positional Input Arguments:
    72     * x:  Scalar or Numeric array, Python list/tuple of any size and
     72    * x:  Scalar or numeric array, Python list/tuple of any size and
    7373      shape.  Floating or integer type.
    74     * y:  Scalar or Numeric array, Python list/tuple of any size and
     74    * y:  Scalar or numeric array, Python list/tuple of any size and
    7575      shape.  Floating or integer type.
    7676
     
    8484
    8585    Examples:
    86     >>> import Numeric as N
     86    >>> import numpy as N
    8787    >>> from where_close import where_close
    8888    >>> x = [20.,  -32., -1., 2.            , 5., 29.]
     
    9898    ['1', '0', '0', '1', '0']
    9999    """
    100     import Numeric as N
     100    import numpy as N
    101101    abs = N.absolute
    102102
    103103
    104     #- Make sure input is Numeric type:
     104    #- Make sure input is numeric type:
    105105
    106106    xN = N.array(x)
     
    111111    #  type returns an error:
    112112
    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']):
    115115        return N.less_equal(abs(xN-yN), atol+rtol*abs(yN))
    116116
    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']):
    119119        return N.equal(xN, yN)
    120120
     
    132132    """
    133133    >>> from where_close import where_close
    134     >>> import Numeric as N
     134    >>> import numpy as N
    135135    >>> x = [20.,  -32., -1., 2.            , 5., 29.]
    136136    >>> y = [20.1, -31., -1., 2.000000000001, 3., 28.99]
     
    144144    >>> ind.shape
    145145    (2, 3)
    146     >>> ind.typecode()
    147     'l'
     146    >>> ind.dtype.char
     147    '?'
    148148    >>> type(ind)
    149     <type 'array'>
     149    <type 'numpy.ndarray'>
    150150
    151151    >>> x = [20.,  -32., -1., 2.            , 5., 29.]
     
    179179    0
    180180    >>> type(ind)
    181     <type 'int'>
     181    <type 'numpy.bool_'>
    182182    >>> x = -33
    183183    >>> y = -33.
  • branches/numpy/anuga/visualiser/commandline_viewer.py

    r3963 r6304  
    4141        o.colour_height_quantity('stage', (lambda q: q['stage'], 0, 10))
    4242        # Or with the magnitude of the momentum at that point:
    43         # Needs the sqrt function from Numeric. Again, 0 and 10
     43        # Needs the sqrt function from numeric. Again, 0 and 10
    4444        # define the colour range.
    4545        # o.colour_height_quantity('stage',
Note: See TracChangeset for help on using the changeset viewer.