Changeset 6360


Ignore:
Timestamp:
Feb 18, 2009, 2:44:41 PM (15 years ago)
Author:
rwilson
Message:

Ongoing conversion changes.

Location:
branches/numpy/anuga
Files:
24 edited

Legend:

Unmodified
Added
Removed
  • branches/numpy/anuga/coordinate_transforms/geo_reference.py

    r6304 r6360  
    99import types, sys
    1010from anuga.utilities.numerical_tools import ensure_numeric
    11 from anuga.utilities.anuga_exceptions import ANUGAError, TitleError, ParsingError, \
    12      ShapeError
     11from anuga.utilities.anuga_exceptions import ANUGAError, TitleError, \
     12                                             ParsingError, ShapeError
    1313from anuga.config import netcdf_float, netcdf_int, netcdf_float32
    1414
     
    1717
    1818DEFAULT_ZONE = -1
    19 TITLE = '#geo reference' + "\n" #this title is referred to in the test format
     19TITLE = '#geo reference' + "\n" # this title is referred to in the test format
    2020
    2121DEFAULT_PROJECTION = 'UTM'
     
    2323DEFAULT_UNITS = 'm'
    2424DEFAULT_FALSE_EASTING = 500000
    25 DEFAULT_FALSE_NORTHING = 10000000 #Default for southern hemisphere
    26 
     25DEFAULT_FALSE_NORTHING = 10000000    # Default for southern hemisphere
     26
     27
     28##
     29# @brief A class for ...
    2730class Geo_reference:
    2831    """
     32    Attributes of the Geo_reference class:
     33        .zone           The UTM zone (default is -1)
     34        .false_easting  ??
     35        .false_northing ??
     36        .datum          The Datum used (default is wgs84)
     37        .projection     The projection used (default is 'UTM')
     38        .units          The units of measure used (default metres)
     39        .xllcorner      The X coord of origin (default is 0.0 wrt UTM grid)
     40        .yllcorner      The y coord of origin (default is 0.0 wrt UTM grid)
     41        .is_absolute    ??
     42
    2943    """
    3044
     45    ##
     46    # @brief Instantiate an instance of class Geo_reference.
     47    # @param zone The UTM zone.
     48    # @param xllcorner X coord of origin of georef.
     49    # @param yllcorner Y coord of origin of georef.
     50    # @param datum ??
     51    # @param projection The projection used (default UTM).
     52    # @param units Units used in measuring distance (default m).
     53    # @param false_easting ??
     54    # @param false_northing ??
     55    # @param NetCDFObject NetCDF file *handle* to write to.
     56    # @param ASCIIFile ASCII text file *handle* to write to.
     57    # @param read_title Title of the georeference text.
    3158    def __init__(self,
    32                  zone = DEFAULT_ZONE,
    33                  xllcorner = 0.0,
    34                  yllcorner = 0.0,
    35                  datum = DEFAULT_DATUM,
    36                  projection = DEFAULT_PROJECTION,
    37                  units = DEFAULT_UNITS,
    38                  false_easting = DEFAULT_FALSE_EASTING,
    39                  false_northing = DEFAULT_FALSE_NORTHING,
     59                 zone=DEFAULT_ZONE,
     60                 xllcorner=0.0,
     61                 yllcorner=0.0,
     62                 datum=DEFAULT_DATUM,
     63                 projection=DEFAULT_PROJECTION,
     64                 units=DEFAULT_UNITS,
     65                 false_easting=DEFAULT_FALSE_EASTING,
     66                 false_northing=DEFAULT_FALSE_NORTHING,
    4067                 NetCDFObject=None,
    4168                 ASCIIFile=None,
     
    4370        """
    4471        input:
    45         NetCDFObject - a handle to the netCDF file to be written to 
     72        NetCDFObject - a handle to the netCDF file to be written to
    4673        ASCIIFile - a handle to the text file
    4774        read_title - the title of the georeference text, if it was read in.
     
    5481         must be the default info, since ANUGA assumes it isn't
    5582         changing.
    56          """
     83        """
     84
    5785        if zone is None:
    5886            zone = DEFAULT_ZONE
    5987        self.false_easting = false_easting
    60         self.false_northing = false_northing       
     88        self.false_northing = false_northing
    6189        self.datum = datum
    6290        self.projection = projection
    63         self.zone = zone       
     91        self.zone = zone
    6492        self.units = units
    6593        self.xllcorner = xllcorner
    66         self.yllcorner = yllcorner       
    67         #self.is_absolute = num.allclose([self.xllcorner, self.yllcorner], 0) 
    68            
     94        self.yllcorner = yllcorner
     95        #self.is_absolute = num.allclose([self.xllcorner, self.yllcorner], 0)
     96
    6997        if NetCDFObject is not None:
    7098            self.read_NetCDF(NetCDFObject)
    71  
     99
    72100        if ASCIIFile is not None:
    73101            self.read_ASCII(ASCIIFile, read_title=read_title)
    74102
     103#    # Might be better to have this method instead of the following 3.
     104#    def get_origin(self):
     105#        return (self.zone, self.xllcorner, self.yllcorner)
     106
     107    ##
     108    # @brief Get the X coordinate of the origin of this georef.
    75109    def get_xllcorner(self):
    76110        return self.xllcorner
    77    
     111
     112    ##
     113    # @brief Get the Y coordinate of the origin of this georef.
    78114    def get_yllcorner(self):
    79115        return self.yllcorner
    80    
     116
     117    ##
     118    # @brief Get the zone of this georef.
    81119    def get_zone(self):
    82120        return self.zone
    83        
     121
     122    ##
     123    # @brief Write <something> to an open NetCDF file.
     124    # @param outfile Handle to open NetCDF file.
    84125    def write_NetCDF(self, outfile):
    85         outfile.xllcorner = self.xllcorner 
     126        outfile.xllcorner = self.xllcorner
    86127        outfile.yllcorner = self.yllcorner
    87128        outfile.zone = self.zone
     
    90131        outfile.false_northing = self.false_northing
    91132
    92         outfile.datum = self.datum       
     133        outfile.datum = self.datum
    93134        outfile.projection = self.projection
    94135        outfile.units = self.units
    95136
     137    ##
     138    # @brief Read data from an open NetCDF file.
     139    # @param infile Handle to open NetCDF file.
    96140    def read_NetCDF(self, infile):
    97141        self.xllcorner = infile.xllcorner[0]
    98         self.yllcorner = infile.yllcorner[0] 
     142        self.yllcorner = infile.yllcorner[0]
    99143        self.zone = infile.zone[0]
    100144
    101        
    102145        # Fix some assertion failures
    103146        if isinstance(self.zone, num.ndarray) and self.zone.shape == ():
    104147            self.zone = self.zone[0]
    105         if isinstance(self.xllcorner, num.ndarray) and self.xllcorner.shape == ():
     148        if (isinstance(self.xllcorner, num.ndarray) and
     149                self.xllcorner.shape == ()):
    106150            self.xllcorner = self.xllcorner[0]
    107         if isinstance(self.yllcorner, num.ndarray) and self.yllcorner.shape == ():
     151        if (isinstance(self.yllcorner, num.ndarray) and
     152                self.yllcorner.shape == ()):
    108153            self.yllcorner = self.yllcorner[0]
    109154
     
    113158                self.yllcorner.dtype.kind in num.typecodes['Integer'])
    114159        assert (self.zone.dtype.kind in num.typecodes['Integer'])
    115        
     160
    116161        try:
    117162            self.false_easting = infile.false_easting[0]
    118163            self.false_northing = infile.false_northing[0]
    119        
    120             self.datum = infile.datum       
     164
     165            self.datum = infile.datum
    121166            self.projection = infile.projection
    122167            self.units = infile.units
    123168        except:
    124169            pass
    125         if (self.false_easting != DEFAULT_FALSE_EASTING):
    126             print "WARNING: False easting of %f specified." %self.false_easting
    127             print "Default false easting is %f." %DEFAULT_FALSE_EASTING
     170
     171        if self.false_easting != DEFAULT_FALSE_EASTING:
     172            print "WARNING: False easting of %f specified." % self.false_easting
     173            print "Default false easting is %f." % DEFAULT_FALSE_EASTING
    128174            print "ANUGA does not correct for differences in False Eastings."
    129            
    130         if (self.false_northing != DEFAULT_FALSE_NORTHING):
    131             print "WARNING: False northing of %f specified." \
    132                   %self.false_northing
    133             print "Default false northing is %f." %DEFAULT_FALSE_NORTHING
     175
     176        if self.false_northing != DEFAULT_FALSE_NORTHING:
     177            print ("WARNING: False northing of %f specified."
     178                   % self.false_northing)
     179            print "Default false northing is %f." % DEFAULT_FALSE_NORTHING
    134180            print "ANUGA does not correct for differences in False Northings."
    135            
    136         if (self.datum.upper() != DEFAULT_DATUM.upper()):
    137             print "WARNING: Datum of %s specified." \
    138                   %self.datum
    139             print "Default Datum is %s." %DEFAULT_DATUM
     181
     182        if self.datum.upper() != DEFAULT_DATUM.upper():
     183            print "WARNING: Datum of %s specified." % self.datum
     184            print "Default Datum is %s." % DEFAULT_DATUM
    140185            print "ANUGA does not correct for differences in datums."
    141            
    142         if (self.projection.upper() != DEFAULT_PROJECTION.upper()):
    143             print "WARNING: Projection of %s specified." \
    144                   %self.projection
    145             print "Default Projection is %s." %DEFAULT_PROJECTION
     186
     187        if self.projection.upper() != DEFAULT_PROJECTION.upper():
     188            print "WARNING: Projection of %s specified." % self.projection
     189            print "Default Projection is %s." % DEFAULT_PROJECTION
    146190            print "ANUGA does not correct for differences in Projection."
    147            
    148         if (self.units.upper() != DEFAULT_UNITS.upper()):
    149             print "WARNING: Units of %s specified." \
    150                   %self.units
    151             print "Default units is %s." %DEFAULT_UNITS
     191
     192        if self.units.upper() != DEFAULT_UNITS.upper():
     193            print "WARNING: Units of %s specified." % self.units
     194            print "Default units is %s." % DEFAULT_UNITS
    152195            print "ANUGA does not correct for differences in units."
    153        
    154     ### ASCII files with geo-refs are currently not used   
     196
     197################################################################################
     198# ASCII files with geo-refs are currently not used
     199################################################################################
     200
     201    ##
     202    # @brief Write georef data to an open text file.
     203    # @param fd Handle to open text file.
    155204    def write_ASCII(self, fd):
    156205        fd.write(TITLE)
    157         fd.write(str(self.zone) + "\n") 
    158         fd.write(str(self.xllcorner) + "\n") 
     206        fd.write(str(self.zone) + "\n")
     207        fd.write(str(self.xllcorner) + "\n")
    159208        fd.write(str(self.yllcorner) + "\n")
    160209
    161     def read_ASCII(self, fd,read_title=None):
     210    ##
     211    # @brief Read georef data from an open text file.
     212    # @param fd Handle to open text file.
     213    def read_ASCII(self, fd, read_title=None):
    162214        try:
    163215            if read_title == None:
    164                 read_title = fd.readline() # remove the title line
     216                read_title = fd.readline()     # remove the title line
    165217            if read_title[0:2].upper() != TITLE[0:2].upper():
    166                 msg = 'File error.  Expecting line: %s.  Got this line: %s' \
    167                       %(TITLE, read_title)
    168                 raise TitleError, msg 
     218                msg = ('File error.  Expecting line: %s.  Got this line: %s'
     219                       % (TITLE, read_title))
     220                raise TitleError, msg
    169221            self.zone = int(fd.readline())
    170222            self.xllcorner = float(fd.readline())
    171223            self.yllcorner = float(fd.readline())
    172224        except SyntaxError:
    173                 msg = 'File error.  Got syntax error while parsing geo reference'
    174                 raise ParsingError, msg
    175            
     225            msg = 'File error.  Got syntax error while parsing geo reference'
     226            raise ParsingError, msg
     227
    176228        # Fix some assertion failures
    177229        if isinstance(self.zone, num.ndarray) and self.zone.shape == ():
    178230            self.zone = self.zone[0]
    179         if isinstance(self.xllcorner, num.ndarray) and self.xllcorner.shape == ():
     231        if (isinstance(self.xllcorner, num.ndarray) and
     232                self.xllcorner.shape == ()):
    180233            self.xllcorner = self.xllcorner[0]
    181         if isinstance(self.yllcorner, num.ndarray) and self.yllcorner.shape == ():
     234        if (isinstance(self.yllcorner, num.ndarray) and
     235                self.yllcorner.shape == ()):
    182236            self.yllcorner = self.yllcorner[0]
    183237
    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 
    189        
    190     def change_points_geo_ref(self, points,
    191                               points_geo_ref=None):
     238################################################################################
     239
     240    def change_points_geo_ref(self, points, points_geo_ref=None):
    192241        """
    193242        Change the geo reference of a list or numeric array of points to
     
    201250
    202251        points = ensure_numeric(points, num.float)
    203        
     252
    204253        if len(points.shape) == 1:
    205             #One point has been passed
     254            # One point has been passed
    206255            msg = 'Single point must have two elements'
    207256            assert len(points) == 2, msg
    208257            points = num.reshape(points, (1,2))
    209258
    210         msg = 'Points array must be two dimensional.\n'
    211         msg += 'I got %d dimensions' %len(points.shape)
     259        msg = ('Points array must be two dimensional.\n'
     260               'I got %d dimensions' % len(points.shape))
    212261        assert len(points.shape) == 2, msg
    213262
    214         msg = 'Input must be an N x 2 array or list of (x,y) values. '
    215         msg += 'I got an %d x %d array' %points.shape   
    216         assert points.shape[1] == 2, msg               
    217 
    218        
    219         # FIXME (Ole): Could also check if zone, xllcorner, yllcorner
    220         # are identical in the two geo refs.   
     263        msg = ('Input must be an N x 2 array or list of (x,y) values. '
     264               'I got an %d x %d array' % points.shape)
     265        assert points.shape[1] == 2, msg
     266
     267        # FIXME (Ole): Could also check if zone, xllcorner, yllcorner
     268        # are identical in the two geo refs.
    221269        if points_geo_ref is not self:
    222270            # If georeferences are different
    223        
    224271            if not points_geo_ref is None:
    225272                # Convert points to absolute coordinates
    226                 points[:,0] += points_geo_ref.xllcorner 
    227                 points[:,1] += points_geo_ref.yllcorner 
    228        
     273                points[:,0] += points_geo_ref.xllcorner
     274                points[:,1] += points_geo_ref.yllcorner
     275
    229276            # Make points relative to primary geo reference
    230             points[:,0] -= self.xllcorner 
     277            points[:,0] -= self.xllcorner
    231278            points[:,1] -= self.yllcorner
    232279
    233            
     280        # if we got a list, return a list
    234281        if is_list:
    235282            points = points.tolist()
    236            
     283
    237284        return points
    238285
    239    
     286    ##
     287    # @brief Is this georef absolute?
     288    # @return True if ???
    240289    def is_absolute(self):
    241         """Return True if xllcorner==yllcorner==0 indicating that points
    242         in question are absolute.
    243         """
    244 
    245         return num.allclose([self.xllcorner, self.yllcorner], 0)
    246 
    247        
    248     ##
    249     # @brief
    250     # @param points
    251     # @return
    252     # @note
     290        """Return True if xllcorner==yllcorner==0
     291        indicating that points in question are absolute.
     292        """
     293
     294        return num.allclose([self.xllcorner, self.yllcorner], 0)
     295
     296    ##
     297    # @brief Convert points to absolute points in this georef instance.
     298    # @param points
     299    # @return
     300    # @note
    253301    def get_absolute(self, points):
    254302        """Given a set of points geo referenced to this instance,
     
    259307        #    return points
    260308
     309        # remember if we got a list
    261310        is_list = False
    262311        if type(points) == types.ListType:
     
    266315        if len(points.shape) == 1:
    267316            #One point has been passed
    268             msg = 'Single point must have two elements'
    269317            if not len(points) == 2:
    270                 raise ShapeError, msg   
     318                msg = 'Single point must have two elements'
     319                raise ShapeError, msg
    271320                #points = reshape(points, (1,2))
    272321
    273         msg = 'Input must be an N x 2 array or list of (x,y) values. '
    274         msg += 'I got an %d x %d array' %points.shape   
    275322        if not points.shape[1] == 2:
    276             raise ShapeError, msg   
    277        
     323            msg = ('Input must be an N x 2 array or list of (x,y) values. '
     324                   'I got an %d x %d array' % points.shape)
     325            raise ShapeError, msg
     326
    278327        # Add geo ref to points
    279328        #if not self.is_absolute:
    280329        if not self.is_absolute():
    281             points[:,0] += self.xllcorner 
     330            points[:,0] += self.xllcorner
    282331            points[:,1] += self.yllcorner
    283332            #self.is_absolute = True
    284        
     333
     334        # if we got a list, return a list
    285335        if is_list:
    286336            points = points.tolist()
    287              
     337
    288338        return points
    289339
    290 
     340    ##
     341    # @brief Convert points to relative measurement.
     342    # @param points Points to convert to relative measurements.
     343    # @return A set of points relative to the geo_reference instance.
    291344    def get_relative(self, points):
    292         """
    293         Given a set of points in absolute UTM coordinates,
     345        """Given a set of points in absolute UTM coordinates,
    294346        make them relative to this geo_reference instance,
    295347        return the points as relative values.
     
    305357        if len(points.shape) == 1:
    306358            #One point has been passed
    307             msg = 'Single point must have two elements'
    308359            if not len(points) == 2:
    309                 raise ShapeError, msg   
     360                msg = 'Single point must have two elements'
     361                raise ShapeError, msg
    310362                #points = reshape(points, (1,2))
    311363
    312 
    313         msg = 'Input must be an N x 2 array or list of (x,y) values. '
    314         msg += 'I got an %d x %d array' %points.shape   
    315364        if not points.shape[1] == 2:
    316             raise ShapeError, msg   
    317            
    318        
     365            msg = ('Input must be an N x 2 array or list of (x,y) values. '
     366                   'I got an %d x %d array' % points.shape)
     367            raise ShapeError, msg
     368
    319369        # Subtract geo ref from points
    320370        if not self.is_absolute():
    321             points[:,0] -= self.xllcorner 
     371            points[:,0] -= self.xllcorner
    322372            points[:,1] -= self.yllcorner
    323373
    324        
     374        # if we got a list, return a list
    325375        if is_list:
    326376            points = points.tolist()
    327              
     377
    328378        return points
    329379
    330 
    331 
     380    ##
     381    # @brief ??
     382    # @param other ??
    332383    def reconcile_zones(self, other):
    333384        if other is None:
    334385            other = Geo_reference()
    335         if self.zone == other.zone or\
    336                self.zone == DEFAULT_ZONE and other.zone == DEFAULT_ZONE:
     386        if (self.zone == other.zone or
     387            self.zone == DEFAULT_ZONE and
     388            other.zone == DEFAULT_ZONE):
    337389            pass
    338390        elif self.zone == DEFAULT_ZONE:
    339391            self.zone = other.zone
    340392        elif other.zone == DEFAULT_ZONE:
    341             other.zone = self.zone           
    342         else:   
    343             msg = 'Geospatial data must be in the same '+\
    344                   'ZONE to allow reconciliation. I got zone %d and %d'\
    345                   %(self.zone, other.zone)
     393            other.zone = self.zone
     394        else:
     395            msg = ('Geospatial data must be in the same '
     396                   'ZONE to allow reconciliation. I got zone %d and %d'
     397                   % (self.zone, other.zone))
    346398            raise ANUGAError, msg
    347    
     399
    348400    #def easting_northing2geo_reffed_point(self, x, y):
    349401    #    return [x-self.xllcorner, y - self.xllcorner]
     
    352404    #    return [x-self.xllcorner, y - self.xllcorner]
    353405
     406    ##
     407    # @brief Get origin of this geo_reference.
     408    # @return (zone, xllcorner, yllcorner).
    354409    def get_origin(self):
    355410        return (self.zone, self.xllcorner, self.yllcorner)
    356    
     411
     412    ##
     413    # @brief Get a string representation of this geo_reference instance.
    357414    def __repr__(self):
    358         return "(zone=%i easting=%f, northing=%f)" %(self.zone, self.xllcorner, self.yllcorner)
    359    
    360     def __cmp__(self,other):
     415        return ('(zone=%i easting=%f, northing=%f)'
     416                % (self.zone, self.xllcorner, self.yllcorner))
     417
     418    ##
     419    # @brief Compare two geo_reference instances.
     420    # @param self This geo_reference instance.
     421    # @param other Another geo_reference instance to compare against.
     422    # @return 0 if instances have the same attributes, else 1.
     423    # @note Attributes are: zone, xllcorner, yllcorner.
     424    def __cmp__(self, other):
    361425        # FIXME (DSG) add a tolerence
    362426        if other is None:
     
    371435        return cmp
    372436
     437
     438##
     439# @brief Write a geo_reference to a NetCDF file (usually SWW).
     440# @param origin A georef instance or parameters to create a georef instance.
     441# @param outfile Path to file to write.
     442# @return A normalized geo_reference.
    373443def write_NetCDF_georeference(origin, outfile):
    374     """
    375     Write georeferrence info to a netcdf file, usually sww.
    376 
    377     The origin can be a georef instance or parrameters for a geo_ref instance
     444    """Write georeference info to a netcdf file, usually sww.
     445
     446    The origin can be a georef instance or parameters for a geo_ref instance
    378447
    379448    outfile is the name of the file to be written to.
    380449    """
     450
    381451    geo_ref = ensure_geo_reference(origin)
    382452    geo_ref.write_NetCDF(outfile)
    383453    return geo_ref
    384454
     455
     456##
     457# @brief Convert an object to a georeference instance.
     458# @param origin A georef instance or (zone, xllcorner, yllcorner)
     459# @return A georef object, or None if 'origin' was None.
    385460def ensure_geo_reference(origin):
    386461    """
     
    391466    effect code logic
    392467    """
    393     if isinstance(origin, Geo_reference):
     468
     469    if isinstance(origin, Geo_reference):
    394470        geo_ref = origin
    395471    elif origin is None:
    396472        geo_ref = None
    397473    else:
    398         geo_ref = apply(Geo_reference, origin)       
     474        geo_ref = apply(Geo_reference, origin)
     475
    399476    return geo_ref
    400477
    401    
     478
    402479#-----------------------------------------------------------------------
    403480
  • branches/numpy/anuga/coordinate_transforms/test_geo_reference.py

    r6304 r6360  
    326326        self.failUnless(isinstance(new_points, num.ndarray), 'failed')
    327327        self.failUnless(type(new_points) == type(points), 'failed')
    328         msg = ('Second call of .get_absolute() returned %s\nexpected %s'
     328        msg = ('Second call of .get_absolute() returned\n%s\nexpected\n%s'
    329329               % (str(new_points), str(expected_new_points)))
    330330        self.failUnless(num.alltrue(expected_new_points == new_points), msg)
     
    507507if __name__ == "__main__":
    508508
    509     #suite = unittest.makeSuite(geo_referenceTestCase,'test')
    510     suite = unittest.makeSuite(geo_referenceTestCase,'test_get_absolute')
     509    suite = unittest.makeSuite(geo_referenceTestCase,'test')
     510    #suite = unittest.makeSuite(geo_referenceTestCase,'test_get_absolute')
    511511    runner = unittest.TextTestRunner() #verbosity=2)
    512512    runner.run(suite)
  • branches/numpy/anuga/coordinate_transforms/test_point.py

    r2253 r6360  
    117117                        %(self.RSISE.BearingTo(self.Kobenhavn), B))
    118118
     119#-------------------------------------------------------------
    119120
    120 
    121 #-------------------------------------------------------------
    122121if __name__ == "__main__":
    123 
    124122    mysuite = unittest.makeSuite(TestCase,'test')
    125123    runner = unittest.TextTestRunner()
    126124    runner.run(mysuite)
    127125
    128 
    129 
    130 
    131 
    132 
    133 
    134 
  • branches/numpy/anuga/fit_interpolate/test_all.py

    r2766 r6360  
    7676    return unittest.TestSuite(map(load, modules))
    7777
     78################################################################################
     79
    7880if __name__ == '__main__':
    79 
    80     from os import sep
    81 
    82     #Attempt to compile all extensions
    83     #execfile('..' + sep + 'utilities' + sep + 'compile.py')
    84 
    85     #FIXME: Temporary measure
    86     #os.chdir('..' + sep + 'utilities')
    87     #execfile('compile.py')
    88     #os.chdir('..' + sep + 'pyvolution')   
    89    
    90     #FIXME: Temporary measure
    91     #os.chdir('..' + sep + 'triangle')
    92     #execfile('compile.py')
    93     #os.chdir('..' + sep + 'pyvolution')   
    94    
    95     #os.system('python compile.py')
    96 
    97     #print regressionTest()
    98     #unittest.main(defaultTest='regressionTest')
    99    
    10081    suite = regressionTest()
    10182    runner = unittest.TextTestRunner() #(verbosity=2)
  • branches/numpy/anuga/fit_interpolate/test_interpolate.py

    r6304 r6360  
    919919        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
    920920
    921 
    922921        point_coords_absolute = [[-2.0, 2.0],
    923                         [-1.0, 1.0],
    924                         [0.0, 2.0],
    925                         [1.0, 1.0],
    926                         [2.0, 1.0],
    927                         [0.0, 0.0],
    928                         [1.0, 0.0],
    929                         [0.0, -1.0],
    930                         [-0.2, -0.5],
    931                         [-0.9, -1.5],
    932                         [0.5, -1.9],
    933                         [3.0, 1.0]]
    934 
    935         geo = Geo_reference(57,100, 500)
     922                                 [-1.0, 1.0],
     923                                 [0.0, 2.0],
     924                                 [1.0, 1.0],
     925                                 [2.0, 1.0],
     926                                 [0.0, 0.0],
     927                                 [1.0, 0.0],
     928                                 [0.0, -1.0],
     929                                 [-0.2, -0.5],
     930                                 [-0.9, -1.5],
     931                                 [0.5, -1.9],
     932                                 [3.0, 1.0]]
     933
     934        geo = Geo_reference(57, 100, 500)
    936935        point_coords = geo.change_points_geo_ref(point_coords_absolute)
    937         point_coords = Geospatial_data(point_coords,geo_reference = geo)
     936        point_coords = Geospatial_data(point_coords, geo_reference=geo)
    938937       
    939938        interp = Interpolate(vertices, triangles)
    940         f = num.array([linear_function(vertices),2*linear_function(vertices)])
     939        f = num.array([linear_function(vertices), 2*linear_function(vertices)])
    941940        f = num.transpose(f)
    942         #print "f",f
     941        print 'f=\n%s' % str(f)
    943942        z = interp.interpolate_block(f, point_coords)
    944         answer = [linear_function(point_coords.get_data_points( \
    945                       absolute = True)),
    946                   2*linear_function(point_coords.get_data_points( \
    947                       absolute = True)) ]
     943        answer = [linear_function(point_coords.get_data_points(absolute=True)),
     944                  2*linear_function(point_coords.get_data_points(absolute=True))
     945                 ]
     946        print 'After creation, answer=\n%s' % str(answer)
    948947        answer = num.transpose(answer)
    949         #print "z",z
    950         #print "answer",answer
    951         assert num.allclose(z, answer)
     948        print "z=\n%s" % str(z)
     949        print "answer=\n%s" % str(answer)
     950        msg = ('Expected z\n%s\nto be close to answer\n%s'
     951               % (str(z), str(answer)))
     952        assert num.allclose(z, answer), msg
    952953           
    953954        z = interp.interpolate(f, point_coords, start_blocking_len = 2)
    954955
    955         #print "z",z
    956         #print "answer",answer
     956        msg = ('Expected z\n%s\nto be close to answer\n%s'
     957               % (str(z), str(answer)))
    957958        assert num.allclose(z, answer)
    958959
     
    18451846        #print "answer",answer
    18461847        assert num.allclose(z, answer)
    1847        
    1848                        
    1849 #-------------------------------------------------------------
     1848
     1849################################################################################
     1850
    18501851if __name__ == "__main__":
    18511852    suite = unittest.makeSuite(Test_Interpolate,'test')
     1853    #suite = unittest.makeSuite(Test_Interpolate,'test_interpolate_geo_spatial')
    18521854    runner = unittest.TextTestRunner() #verbosity=1)
    18531855    runner.run(suite)
    18541856
    1855 
    1856 
    1857 
    1858 
  • branches/numpy/anuga/fit_interpolate/test_search_functions.py

    r6304 r6360  
    207207        assert k == 1
    208208       
    209 
    210 #-------------------------------------------------------------
     209################################################################################
     210
    211211if __name__ == "__main__":
    212212    suite = unittest.makeSuite(Test_search_functions,'test')
  • branches/numpy/anuga/geospatial_data/geospatial_data.py

    r6304 r6360  
    2020     TitleError, DEFAULT_ZONE, ensure_geo_reference, write_NetCDF_georeference
    2121from anuga.coordinate_transforms.redfearn import convert_from_latlon_to_utm
     22from anuga.utilities.system_tools import clean_line
    2223from anuga.utilities.anuga_exceptions import ANUGAError
    2324from anuga.config import points_file_block_line_size as MAX_READ_LINES
     
    14031404                           points_dictionary['attributelist'],
    14041405                           geo_reference = geo)
    1405 
    1406 
    1407 ##
    1408 # @brief Split a string into 'clean' fields.
    1409 # @param str The string to process.
    1410 # @param delimiter The delimiter string to split 'line' with.
    1411 # @return A list of 'cleaned' field strings.
    1412 # @note Any fields that were initially zero length will be removed.
    1413 # @note If a field contains '\n' it isn't zero length.
    1414 def clean_line(str, delimiter):
    1415     """Split string on given delimiter, remove whitespace from each field."""
    1416 
    1417     return [x.strip() for x in str.split(delimiter) if x != '']
    14181406
    14191407
  • branches/numpy/anuga/geospatial_data/test_geospatial_data.py

    r6304 r6360  
    18361836
    18371837################################################################################
    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', ''])
    18871838
    18881839if __name__ == "__main__":
  • branches/numpy/anuga/load_mesh/loadASCII.py

    r6304 r6360  
    5353    Following lines:  <segment #> <vertex #>  <vertex #> [boundary tag]
    5454"""
     55
    5556##FIXME (DSG-DSG) Is the dict format mentioned above a list of a numeric array?
    5657#  Needs to be defined
     
    5859
    5960from string import  find, rfind
    60 import numpy as num
    6161from os.path import splitext
     62import exceptions
    6263
    6364from anuga.coordinate_transforms.geo_reference import Geo_reference, TITLE, \
    6465                                                      TitleError
    65 
    66 from Scientific.IO.NetCDF import NetCDFFile
    6766from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
    6867from anuga.config import netcdf_float, netcdf_char, netcdf_int
    6968
    70 import exceptions
     69from Scientific.IO.NetCDF import NetCDFFile
     70
     71import numpy as num
    7172
    7273
     
    8788
    8889    Note: will throw an IOError if it can't load the file.
    89     Catch these!
    9090    """
    9191
     
    149149# @brief Read a mesh file into a dictionary.
    150150# @param ofile Path of the file to read.
    151 # @return Data dictionary from the mesh (.tsh) file.
     151# @return Points dictionary from the mesh (.tsh) file.
    152152def _read_tsh_file(ofile):
    153153    """Read the text file format for meshes"""
     
    164164
    165165##
    166 # @brief ??
     166# @brief Read triangulation data from a file, leave file open.
    167167# @param fd An open descriptor of the file to read.
    168168# @return A dictionary ...
     
    264264
    265265##
    266 # @brief
     266# @brief Read a mesh outline file.
    267267# @param fd An open descriptor of the file to read.
    268 # @return A dictionary ...
     268# @return A Points dictionary.
    269269# @note If file has no mesh info, an empty dict will be returned.
    270270def _read_outline(fd):
     
    393393
    394394    return meshDict
    395 
    396 
    397 ##
    398 # @brief Clean up a line with delimited fields.
    399 # @param line The string to be cleaned.
    400 # @param delimiter String used a delimiter when splitting 'line'.
    401 # @return A list of delimited fields with white-space removed from ends.
    402 # @note Will also remove any field that was originally ''.
    403 def clean_line(line, delimiter):
    404     """Clean up a line - return fields with end space removed."""
    405 
    406     line = line.strip()
    407     numbers = line.split(delimiter)
    408     i = len(numbers) - 1
    409     while i >= 0:
    410         if numbers[i] == '':
    411             numbers.pop(i)
    412         else:
    413             numbers[i] = numbers[i].strip()
    414 
    415         i += -1
    416 
    417     return numbers
    418395
    419396
     
    649626        num.array(mesh['vertex_attribute_titles'], num.character)
    650627    mesh['segments'] = num.array(mesh['segments'], IntType)
     628    print ("Before num.array(), mesh['segment_tags']=%s"
     629           % str(mesh['segment_tags']))
    651630    mesh['segment_tags'] = num.array(mesh['segment_tags'], num.character)
     631    print ("After num.array(), mesh['segment_tags']=%s"
     632           % str(mesh['segment_tags']))
     633    print "mesh['segment_tags'].shape=%s" % str(mesh['segment_tags'].shape)
    652634    mesh['triangles'] = num.array(mesh['triangles'], IntType)
    653635    mesh['triangle_tags'] = num.array(mesh['triangle_tags'])
     
    967949    fd.close()
    968950
    969 
    970951################################################################################
    971952#  IMPORT/EXPORT POINTS FILES
  • branches/numpy/anuga/load_mesh/test_all.py

    r2405 r6360  
    7676    return unittest.TestSuite(map(load, modules))
    7777
     78################################################################################
     79
    7880if __name__ == '__main__':
    79 
    8081    from os import sep
    8182
  • branches/numpy/anuga/load_mesh/test_loadASCII.py

    r6304 r6360  
    33import tempfile
    44import unittest
    5 
    65import os
    76import tempfile
    8 
    97from os.path import splitext
    108
    119import numpy as num
    12    
     10
    1311from anuga.load_mesh.loadASCII import *
    1412from anuga.coordinate_transforms.geo_reference import Geo_reference
     
    1816class loadASCIITestCase(unittest.TestCase):
    1917    def setUp(self):
    20         self.dict ={}
     18        self.dict = {}
    2119        self.dict['outline_segments'] = [(0, 1), (1, 2), (0, 2), (0, 3)]
    2220        self.dict['outline_segment_tags'] = ['50', '40', '30', '20']
    2321        self.dict['holes'] = [(0.2, 0.6)]
    24         self.dict['point_attributes'] = [[5, 2], [4, 2], [3, 2], [2,2]]
    25         self.dict['regions'] = [(0.3, 0.3),(0.3, 0.4)]
     22        self.dict['point_attributes'] = [[5, 2], [4, 2], [3, 2], [2, 2]]
     23        self.dict['regions'] = [(0.3, 0.3), (0.3, 0.4)]
    2624        self.dict['region_tags'] = ['1.3', 'yeah']
    2725        self.dict['region_max_areas'] = [36.0, -7.1]
    2826        self.dict['points'] = [(0.0, 0.0), (0.0, 4.0), (4.0, 0.0), (1.0, 1.0)]
    29         self.dict['vertices'] = [(0.0, 0.0), (0.0, 4.0),
    30                                  (4.0, 0.0), (1.0, 1.0), (2.0, 2.0)]
    31         self.dict['triangles'] = [(3, 2, 4), (1, 0, 3),
    32                                              (3, 4,1), (2, 3, 0)]
    33         self.dict['segments'] = [(0, 1), (1, 4), (2, 0),
    34                                             (0, 3), (4, 2)]
    35         self.dict['triangle_tags'] = ['1.3', '1.3',
    36                                       '1.3', '1.3']
    37         self.dict['vertex_attributes'] = [[1.2, 2.], [1.2, 2.],
    38                                           [1.2, 2.], [1.2, 2.], [1.2, 3.]]
     27        self.dict['vertices'] = [(0.0, 0.0), (0.0, 4.0), (4.0, 0.0),
     28                                 (1.0, 1.0), (2.0, 2.0)]
     29        self.dict['triangles'] = [(3, 2, 4), (1, 0, 3), (3, 4,1), (2, 3, 0)]
     30        self.dict['segments'] = [(0, 1), (1, 4), (2, 0), (0, 3), (4, 2)]
     31        self.dict['triangle_tags'] = ['1.3', '1.3', '1.3', '1.3']
     32        self.dict['vertex_attributes'] = [[1.2, 2.], [1.2, 2.], [1.2, 2.],
     33                                          [1.2, 2.], [1.2, 3.]]
    3934        self.dict['triangle_neighbors'] = [[-1, 2, 3], [3, 2, -1],
    4035                                           [-1, 1, 0], [1, -1, 0]]
     
    4237        self.dict['vertex_attribute_titles'] = ['bed elevation', 'height']
    4338        self.dict['geo_reference'] = Geo_reference(56, 1.9, 1.9)
    44        
    45         self.sparse_dict ={}
     39
     40        self.sparse_dict = {}
    4641        self.sparse_dict['outline_segments'] = []
    4742        self.sparse_dict['outline_segment_tags'] = []
     
    6257        self.sparse_dict['segment_tags'] = []
    6358        self.sparse_dict['vertex_attribute_titles'] = []
    64        
    65         self.blank_dict ={}
     59
     60        self.blank_dict = {}
    6661        self.blank_dict['outline_segments'] = []
    6762        self.blank_dict['outline_segment_tags'] = []
    6863        self.blank_dict['holes'] = []
    6964        self.blank_dict['points'] = []
    70         self.blank_dict['point_attributes'] = [] 
     65        self.blank_dict['point_attributes'] = []
    7166        self.blank_dict['regions'] = []
    7267        self.blank_dict['region_tags'] = []
     
    8075        self.blank_dict['segment_tags'] = []
    8176        self.blank_dict['vertex_attribute_titles'] = []
    82        
    83         self.tri_dict ={}
     77
     78        self.tri_dict = {}
    8479        self.tri_dict['outline_segments'] = [[0, 1]]
    8580        self.tri_dict['outline_segment_tags'] = ['']
    8681        self.tri_dict['holes'] = []
    8782        self.tri_dict['points'] = [(9, 8), (7, 8)]
    88         self.tri_dict['point_attributes'] = [[],[]]
     83        self.tri_dict['point_attributes'] = [[], []]
    8984        self.tri_dict['regions'] = []
    9085        self.tri_dict['region_tags'] = []
     
    9893        self.tri_dict['segment_tags'] = ['']
    9994        self.tri_dict['vertex_attribute_titles'] = []
    100        
    101         self.seg_dict ={}
     95
     96        self.seg_dict = {}
    10297        self.seg_dict['outline_segments'] = [[0, 1]]
    10398        self.seg_dict['outline_segment_tags'] = ['']
    10499        self.seg_dict['holes'] = []
    105100        self.seg_dict['points'] = [(9, 8), (7, 8)]
    106         self.seg_dict['point_attributes'] = [[], []] 
     101        self.seg_dict['point_attributes'] = [[], []]
    107102        self.seg_dict['regions'] = [(5, 4)]
    108         self.seg_dict['region_tags'] = [''] 
     103        self.seg_dict['region_tags'] = ['']
    109104        self.seg_dict['region_max_areas'] = [-999]
    110105        self.seg_dict['vertices'] = [(9, 8), (7, 8)]
     
    116111        self.seg_dict['segment_tags'] = ['']
    117112        self.seg_dict['vertex_attribute_titles'] = []
    118        
    119         self.reg_dict ={}
     113
     114        self.reg_dict = {}
    120115        self.reg_dict['outline_segments'] = [[0, 1]]
    121116        self.reg_dict['outline_segment_tags'] = ['']
    122117        self.reg_dict['holes'] = []
    123118        self.reg_dict['points'] = [(9, 8), (7, 8)]
    124         self.reg_dict['point_attributes'] = [[], []] 
     119        self.reg_dict['point_attributes'] = [[], []]
    125120        self.reg_dict['regions'] = [(5, 4)]
    126121        self.reg_dict['region_tags'] = ['']
     
    134129        self.reg_dict['segment_tags'] = ['']
    135130        self.reg_dict['vertex_attribute_titles'] = []
    136        
    137         self.triangle_tags_dict ={}
     131
     132        self.triangle_tags_dict = {}
    138133        self.triangle_tags_dict['outline_segments'] = [(0, 1), (1, 2),
    139134                                                       (0, 2), (0, 3)]
     
    143138        self.triangle_tags_dict['point_attributes'] = [[5, 2], [4, 2],
    144139                                                       [3, 2], [2,2]]
    145         self.triangle_tags_dict['regions'] = [(0.3, 0.3),(0.3, 0.4)]
     140        self.triangle_tags_dict['regions'] = [(0.3, 0.3), (0.3, 0.4)]
    146141        self.triangle_tags_dict['region_tags'] = ['1.3', 'yeah']
    147142        self.triangle_tags_dict['region_max_areas'] = [36.0, -7.1]
     
    152147                                               (2.0, 2.0)]
    153148        self.triangle_tags_dict['triangles'] = [(3, 2, 4), (1, 0, 3),
    154                                                 (3, 4,1), (2, 3, 0)]
     149                                                (3, 4, 1), (2, 3, 0)]
    155150        self.triangle_tags_dict['segments'] = [(0, 1), (1, 4), (2, 0),
    156151                                               (0, 3), (4, 2)]
     
    165160                                                              'height']
    166161        self.triangle_tags_dict['geo_reference'] = Geo_reference(56, 1.9, 1.9)
    167        
     162
    168163    def tearDown(self):
    169164        pass
    170165
    171   ############### .TSH ##########     
     166  ############### .TSH ##########
    172167    def test_export_mesh_file(self):
    173         import os
    174         import tempfile
    175        
    176168        meshDict = self.dict
    177169        fileName = tempfile.mktemp('.tsh')
    178170        export_mesh_file(fileName, meshDict)
    179171        loadedDict = import_mesh_file(fileName)
    180        
     172
    181173        self.failUnless(num.alltrue(num.array(meshDict['vertices']) ==
    182174                                    num.array(loadedDict['vertices'])),
     
    207199                                    num.array(loadedDict['geo_reference'])),
    208200                        'test_export_mesh_file failed. Test 9')
    209            
    210         os.remove(fileName)
    211  
     201
     202        os.remove(fileName)
     203
    212204    def test_read_write_tsh_file(self):
    213205        dict = self.dict.copy()
     
    218210        dict = self.dict
    219211        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file')
    220        
     212
    221213    def test_read_write_tsh_fileII(self):
    222214        dict = self.sparse_dict.copy()
     
    224216        export_mesh_file(fileName, dict)
    225217        loaded_dict = import_mesh_file(fileName)
    226         dict = self.sparse_dict   
    227         self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file')
    228         os.remove(fileName)
    229        
     218        dict = self.sparse_dict
     219        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_tsh_fileII')
     220        os.remove(fileName)
     221
    230222    def test_read_write_tsh_fileIII(self):
    231223        dict = self.blank_dict.copy()
     
    235227        os.remove(fileName)
    236228        dict = self.blank_dict
    237         #print "*********************"
    238         #print dict
    239         #print "**loaded_dict*******************"
    240         #print loaded_dict
    241         #print "*********************"       
    242229        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileIII')
    243230
     
    248235        loaded_dict = import_mesh_file(fileName)
    249236        os.remove(fileName)
    250         dict = self.seg_dict   
     237        dict = self.seg_dict
    251238        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file4')
    252239
     
    257244        loaded_dict = import_mesh_file(fileName)
    258245        dict = self.triangle_tags_dict
    259         #print "*********************"
    260         #print dict
    261         #print "**loaded_dict*******************"
    262         #print loaded_dict
    263         #print "*********************"       
    264         self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file5') 
     246        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file5')
    265247        os.remove(fileName)
    266248
     
    271253        loaded_dict = import_mesh_file(fileName)
    272254        dict = self.tri_dict
    273         self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file6') 
    274         os.remove(fileName)
    275        
     255        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file6')
     256        os.remove(fileName)
     257
    276258########################## BAD .TSH ##########################
    277259
    278260    def test_load_bad_no_file_tsh(self):
    279         import os
    280         import tempfile
    281        
    282261        fileName = tempfile.mktemp('.tsh')
    283262        try:
     
    287266        else:
    288267            self.failUnless(0 == 1, 'imaginary file did not raise error!')
    289          
     268
    290269    def test_read_write_tsh_file_bad(self):
    291270        dict = self.tri_dict.copy()
     
    296275            pass
    297276        else:
    298             self.failUnless(0 == 1, 'bad tsh file did not raise error!')       
    299        
     277            self.failUnless(0 == 1, 'bad tsh file did not raise error!')
     278
    300279    def test_import_tsh_bad(self):
    301         import os
    302         import tempfile
    303        
    304280        fileName = tempfile.mktemp('.tsh')
    305281        file = open(fileName, 'w')
     
    3102861.0 !!! \n')
    311287        file.close()
    312         #print fileName
    313288        try:
    314289            dict = import_mesh_file(fileName)
     
    320295
    321296    def test_import_tsh3(self):
    322         import os
    323         import tempfile
    324        
    325297        fileName = tempfile.mktemp('.tsh')
    326298        file = open(fileName, 'w')
     
    336308        else:
    337309            self.failUnless(0 == 1, 'bad tsh file did not raise error!')
    338        
    339         os.remove(fileName)         
    340 
    341            
     310        os.remove(fileName)
     311
    342312  ############### .MSH ##########
    343        
     313
    344314    def test_read_write_msh_file(self):
    345315        dict = self.dict.copy()
     
    349319        os.remove(fileName)
    350320        dict = self.dict
    351         #print "*********************"
    352         #print dict
    353         #print "**loaded_dict*******************"
    354         #print loaded_dict
    355         #print "*********************"
    356321        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file')
    357322
     
    363328        os.remove(fileName)
    364329        dict = self.sparse_dict
    365         #print "*********************"
    366         #print dict
    367         #print "**loaded_dict*******************"
    368         #print loaded_dict
    369         #print "*********************"       
    370330        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileII')
    371              
     331
    372332    def test_read_write_msh_fileIII(self):
    373333        dict = self.blank_dict.copy()
     
    377337        os.remove(fileName)
    378338        dict = self.blank_dict
    379         #print "*********************"
    380         #print dict
    381         #print "**loaded_dict*******************"
    382         #print loaded_dict
    383         #print "*********************"       
    384339        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_fileIII')
    385        
     340
    386341    def test_read_write_msh_file4(self):
    387342        dict = self.seg_dict.copy()
     
    391346        os.remove(fileName)
    392347        dict = self.seg_dict
    393         #print "*********************"
    394         #print dict
    395         #print "**loaded_dict*******************"
    396         #print loaded_dict
    397         #print "*********************"
    398348        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file4')
    399        
     349
    400350    def test_read_write_msh_file5(self):
    401351        dict = self.triangle_tags_dict.copy()
     
    405355        os.remove(fileName)
    406356        dict = self.triangle_tags_dict
    407         #print "msh_file5*********************"
    408         #print dict
    409         #print "**loaded_dict*******************"
    410         #print loaded_dict
    411         #print "*********************"
    412357        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file5')
    413        
     358
    414359    def test_read_write_msh_file6(self):
    415360        dict = self.tri_dict.copy()
     
    419364        os.remove(fileName)
    420365        dict = self.tri_dict
    421         print "*********************"
    422         print dict
    423         print "**loaded_dict*******************"
    424         print loaded_dict
    425         print "*********************"
    426366        self.check_mesh_dicts(loaded_dict, dict, 'test_read_write_msh_file6')
    427                          
     367
    428368    def check_mesh_dicts(self, loaded_dict, dict, fail_string):
    429369        assert num.allclose(num.array(loaded_dict['points']),
     
    433373        assert num.allclose(num.array(loaded_dict['outline_segments']),
    434374                            num.array(dict['outline_segments']))
    435        
     375
    436376        self.failUnless(loaded_dict['outline_segment_tags'] ==
    437377                        dict['outline_segment_tags'],
    438378                        fail_string + ' failed!! Test 4')
    439            
     379
    440380        assert num.allclose(num.array(loaded_dict['regions']),
    441381                            num.array(dict['regions']))
    442                        
     382
    443383        self.failUnless(loaded_dict['region_tags'] == dict['region_tags'],
    444384                        fail_string + ' failed!! Test 5')
    445        
     385
    446386        assert num.allclose(num.array(loaded_dict['region_max_areas']),
    447387                            num.array(dict['region_max_areas']))
    448  
     388
    449389        assert num.allclose(num.array(loaded_dict['holes']),
    450390                            num.array(dict['holes']))
    451  
     391
    452392        assert num.allclose(num.array(dict['vertices']),
    453393                            num.array(loaded_dict['vertices']))
    454  
     394
    455395        assert num.allclose(num.array(dict['triangles']),
    456396                            num.array(loaded_dict['triangles']))
    457  
     397
    458398        assert num.allclose(num.array(dict['segments']),
    459399                            num.array(loaded_dict['segments']))
    460400
    461         for ob, ldob in map(None,dict['triangle_tags'],
    462                               loaded_dict['triangle_tags']):
     401        for ob, ldob in map(None, dict['triangle_tags'],
     402                            loaded_dict['triangle_tags']):
    463403            self.failUnless(ob == ldob,
    464404                            fail_string + ' failed!! Test triangle_tags')
     
    470410                         dict['vertex_attributes'] == []),
    471411                        fail_string + ' failed!! Test vertex_attributes')
    472  
     412
    473413        assert num.allclose(num.array(dict['triangle_neighbors']),
    474414                            num.array(loaded_dict['triangle_neighbors']))
    475415
    476         for seg, ldseg in map(None,dict['segment_tags'],
     416        for seg, ldseg in map(None, dict['segment_tags'],
    477417                              loaded_dict['segment_tags']):
    478418            self.failUnless(seg == ldseg,
    479419                            fail_string + ' failed!! Test 8')
    480         try:
    481             assert num.allclose(num.array(dict['vertex_attribute_titles']),
    482                                 num.array(loaded_dict['vertex_attribute_titles']))
    483         except TypeError:
    484             self.failUnless(num.alltrue(num.array(loaded_dict['vertex_attribute_titles']) ==
    485                                         num.array(dict['vertex_attribute_titles'])),
     420
     421        dict_array = num.array(dict['vertex_attribute_titles'])
     422        loaded_dict_array = num.array(loaded_dict['vertex_attribute_titles'])
     423        try:
     424            assert num.allclose(dict_array, loaded_dict_array)
     425        #except TypeError:      #??#
     426        except IndexError:
     427            self.failUnless(num.alltrue(loaded_dict_array == dict_array),
    486428                            fail_string + ' failed!! Test 8')
    487         try:   
     429
     430        try:
    488431            self.failUnless(loaded_dict['geo_reference'] ==
    489432                            dict['geo_reference'],
    490433                            fail_string + ' failed!! Test geo_reference')
    491         except KeyError:         
    492             self.failUnless(not dict.has_key('geo_reference' and
    493                                 loaded_dict['geo_reference'] == None),
     434        except KeyError:        #??# 2 lines below??
     435#           self.failUnless(not dict.has_key('geo_reference' and
     436#                               loaded_dict['geo_reference'] == None),
     437#                           fail_string + ' failed!! Test geo_reference')
     438            self.failUnless(not dict.has_key('geo_reference') and
     439                                loaded_dict['geo_reference'] == None,
    494440                            fail_string + ' failed!! Test geo_reference')
    495  
    496 ########################## BAD .MSH ##########################         
     441
     442########################## BAD .MSH ##########################
    497443
    498444    def test_load_bad_no_file_msh(self):
    499         import os
    500         import tempfile
    501        
    502445        fileName = tempfile.mktemp('.msh')
    503446        try:
     
    507450        else:
    508451            self.failUnless(0 == 1, 'imaginary file did not raise error!')
    509            
     452
    510453    def throws_error_2_screen_test_import_mesh_bad(self):
    511         import os
    512         import tempfile
    513        
    514454        fileName = tempfile.mktemp('.msh')
    515455        file = open(fileName, 'w')
     
    526466        else:
    527467            self.failUnless(0 == 1, 'bad msh file did not raise error!')
    528         os.remove(fileName)         
    529 
    530 #-------------------------------------------------------------
     468        os.remove(fileName)
     469
     470################################################################################
     471
    531472if __name__ == '__main__':
    532 
    533473    suite = unittest.makeSuite(loadASCIITestCase,'test')
     474    #suite = unittest.makeSuite(loadASCIITestCase,'test_read_write_msh_file6')
    534475    runner = unittest.TextTestRunner() #verbosity=2)
    535476    runner.run(suite)
    536    
     477
  • branches/numpy/anuga/pmesh/test_all.py

    r4663 r6360  
    7676    return unittest.TestSuite(map(load, modules))
    7777
     78################################################################################
     79
    7880if __name__ == '__main__':
    7981    # Assume everything is compiled
  • branches/numpy/anuga/pmesh/test_mesh.py

    r6304 r6360  
    23112311            yes = False
    23122312    return yes
    2313            
    2314 #-------------------------------------------------------------
     2313   
     2314################################################################################
     2315
    23152316if __name__ == "__main__":
    23162317    suite = unittest.makeSuite(meshTestCase,'test')
     2318    #suite = unittest.makeSuite(meshTestCase,'test_import_mesh')
    23172319    runner = unittest.TextTestRunner() #verbosity=2)
    23182320    runner.run(suite)
  • branches/numpy/anuga/pmesh/test_mesh_interface.py

    r6304 r6360  
    7070        # poly_point values are relative to the mesh geo-ref
    7171        # make them absolute
     72        msg = ('Expected point (%s,%s) to be inside polygon %s'
     73               % (str(poly_point.x+x), str(poly_point.y+y),
     74                  str(polygon_absolute)))
    7275        self.failUnless(is_inside_polygon([poly_point.x+x, poly_point.y+y],
    7376                                          polygon_absolute, closed=False),
    74                         'FAILED!')
     77                        msg)
     78#                        'FAILED!')
    7579
    7680        # Assuming the order of the region points is known.
     
    833837            raise Exception, msg
    834838
    835 
    836 #-------------------------------------------------------------
     839################################################################################
     840
    837841if __name__ == "__main__":
    838842    suite = unittest.makeSuite(TestCase,'test')
  • branches/numpy/anuga/utilities/polygon.py

    r6304 r6360  
    196196    """
    197197
     198#    print 'polygon.py: 198, is_inside_polygon: point=%s' % str(point)
     199#    print 'polygon.py: 198, is_inside_polygon: polygon=%s' % str(polygon)
     200
    198201    indices = inside_polygon(point, polygon, closed, verbose)
    199202
     
    250253                                                verbose=verbose)
    251254
     255#    print 'polygon.py: 255, inside_polygon: indices=%s' % str(indices)
     256#    print 'polygon.py: 255, inside_polygon: count=%s' % str(count)
    252257    # Return indices of points inside polygon
    253258    return indices[:count]
  • branches/numpy/anuga/utilities/system_tools.py

    r5921 r6360  
    246246    #    p1 = read_polygon(path)
    247247       
    248            
    249 
    250 
     248       
     249##
     250# @brief Split a string into 'clean' fields.
     251# @param str The string to process.
     252# @param delimiter The delimiter string to split 'line' with.
     253# @return A list of 'cleaned' field strings.
     254# @note Any fields that were initially zero length will be removed.
     255# @note If a field contains '\n' it isn't zero length.
     256def clean_line(str, delimiter):
     257    """Split string on given delimiter, remove whitespace from each field."""
     258
     259    return [x.strip() for x in str.split(delimiter) if x != '']
     260
     261
  • branches/numpy/anuga/utilities/test_cg_solve.py

    r6304 r6360  
    204204        assert num.allclose(x,xe)
    205205
    206 #-------------------------------------------------------------
     206################################################################################
     207
    207208if __name__ == "__main__":
    208      suite = unittest.makeSuite(Test_CG_Solve,'test')
     209     suite = unittest.makeSuite(Test_CG_Solve, 'test')
    209210     #runner = unittest.TextTestRunner(verbosity=2)
    210211     runner = unittest.TextTestRunner(verbosity=1)
  • branches/numpy/anuga/utilities/test_data_audit.py

    r6158 r6360  
    385385        os.remove(data_filename2)
    386386
    387        
    388 
    389                
    390        
    391 #-------------------------------------------------------------
     387################################################################################
     388
    392389if __name__ == "__main__":
    393390    suite = unittest.makeSuite(Test_data_audit, 'test')
     
    395392    runner.run(suite)
    396393
    397 
    398 
    399 
  • branches/numpy/anuga/utilities/test_numerical_tools.py

    r6304 r6360  
    466466#        t(num.array('abc', num.float), False)
    467467
    468 
    469 #-------------------------------------------------------------
     468################################################################################
     469
    470470if __name__ == "__main__":
    471     #suite = unittest.makeSuite(Test_Numerical_Tools,'test')
    472     suite = unittest.makeSuite(Test_Numerical_Tools,'test_is_')
     471    suite = unittest.makeSuite(Test_Numerical_Tools,'test')
     472    #suite = unittest.makeSuite(Test_Numerical_Tools,'test_is_')
    473473    runner = unittest.TextTestRunner()
    474474    runner.run(suite)
  • branches/numpy/anuga/utilities/test_polygon.py

    r6304 r6360  
    15611561        point_spatial = Geospatial_data(point, geo_reference=points_geo_ref)
    15621562
    1563         assert is_inside_polygon(point_absolute, polygon_absolute)
     1563        msg = ('point_absolute\n%s\nis not inside polygon_absolute\n%s'
     1564               % (str(point_absolute), str(polygon_absolute)))
     1565        assert is_inside_polygon(point_absolute, polygon_absolute), msg
     1566
     1567        msg = ('ensure_numeric(point_absolute)\n%s\n'
     1568               'is not inside ensure_numeric(polygon_absolute)\n%s'
     1569               % (str(ensure_numeric(ensure_numeric(point_absolute))),
     1570                  str(polygon_absolute)))
    15641571        assert is_inside_polygon(ensure_numeric(point_absolute),
    1565                                  ensure_numeric(polygon_absolute))
    1566         msg = ('point_absolute %s is not inside poly_spatial %s'
     1572                                 ensure_numeric(polygon_absolute)), msg
     1573
     1574        msg = ('point_absolute\n%s\nis not inside poly_spatial\n%s'
    15671575               % (str(point_absolute), str(poly_spatial)))
    15681576        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)
     1577
     1578        msg = ('point_spatial\n%s\nis not inside poly_spatial\n%s'
     1579               % (str(point_spatial), str(poly_spatial)))
     1580        assert is_inside_polygon(point_spatial, poly_spatial), msg
     1581
     1582        msg = ('point_spatial\n%s\nis not inside polygon_absolute\n%s'
     1583               % (str(point_spatial), str(polygon_absolute)))
     1584        assert is_inside_polygon(point_spatial, polygon_absolute), msg
     1585
     1586        msg = ('point_absolute\n%s\nis not inside polygon_absolute\n%s'
     1587               % (str(point_absolute), str(polygon_absolute)))
     1588        assert is_inside_polygon(point_absolute, polygon_absolute), msg
    15721589
    15731590    def NOtest_decimate_polygon(self):
     
    16861703        assert num.allclose(z, z_ref)
    16871704
    1688 
    1689 # -------------------------------------------------------------
     1705################################################################################
     1706
    16901707if __name__ == "__main__":
    1691     #suite = unittest.makeSuite(Test_Polygon,'test')
    1692     suite = unittest.makeSuite(Test_Polygon,'test_inside_polygon_geospatial')
     1708    suite = unittest.makeSuite(Test_Polygon,'test')
     1709    #suite = unittest.makeSuite(Test_Polygon,'test_inside_polygon_geospatial')
    16931710    runner = unittest.TextTestRunner()
    16941711    runner.run(suite)
  • branches/numpy/anuga/utilities/test_quad.py

    r6304 r6360  
    258258         #                               [[ 4.,  1.], [ 5.,  4.], [ 4.,  4.]]])
    259259       
    260        
    261 #-------------------------------------------------------------
     260################################################################################
     261
    262262if __name__ == "__main__":
    263 
    264263    mysuite = unittest.makeSuite(Test_Quad,'test')
    265264    #mysuite = unittest.makeSuite(Test_Quad,'test_interpolate_one_point_many_triangles')
  • branches/numpy/anuga/utilities/test_sparse.py

    r6304 r6360  
    199199        assert num.allclose(B*C2, [[15.0, 30.0],[10.0, 20.0],[8.0, 16.0],[0.0, 0.0]])
    200200
    201 
    202 
    203 #-------------------------------------------------------------
     201################################################################################
     202
    204203if __name__ == "__main__":
    205204    suite = unittest.makeSuite(Test_Sparse, 'test')
  • branches/numpy/anuga/utilities/test_system_tools.py

    r6304 r6360  
    135135        assert checksum == ref_crc, msg
    136136        #print checksum
    137        
    138        
    139 #-------------------------------------------------------------
     137
     138################################################################################
     139# Test the clean_line() utility function.
     140################################################################################
     141
     142    # helper routine to test clean_line()
     143    def clean_line_test(self, instr, delim, expected):
     144        result = clean_line(instr, delim)
     145        self.failUnless(result == expected,
     146                        "clean_line('%s', '%s'), expected %s, got %s"
     147                        % (str(instr), str(delim), str(expected), str(result)))
     148
     149    def test_clean_line_01(self):
     150        self.clean_line_test('abc, ,,xyz,123', ',', ['abc', '', 'xyz', '123'])
     151
     152    def test_clean_line_02(self):
     153        self.clean_line_test(' abc , ,, xyz  , 123  ', ',',
     154                             ['abc', '', 'xyz', '123'])
     155
     156    def test_clean_line_03(self):
     157        self.clean_line_test('1||||2', '|', ['1', '2'])
     158
     159    def test_clean_line_04(self):
     160        self.clean_line_test('abc, ,,xyz,123, ', ',',
     161                             ['abc', '', 'xyz', '123', ''])
     162
     163    def test_clean_line_05(self):
     164        self.clean_line_test('abc, ,,xyz,123, ,    ', ',',
     165                             ['abc', '', 'xyz', '123', '', ''])
     166
     167    def test_clean_line_06(self):
     168        self.clean_line_test(',,abc, ,,xyz,123, ,    ', ',',
     169                             ['abc', '', 'xyz', '123', '', ''])
     170
     171    def test_clean_line_07(self):
     172        self.clean_line_test('|1||||2', '|', ['1', '2'])
     173
     174    def test_clean_line_08(self):
     175        self.clean_line_test(' ,a,, , ,b,c , ,, , ', ',',
     176                             ['', 'a', '', '', 'b', 'c', '', '', ''])
     177
     178    def test_clean_line_09(self):
     179        self.clean_line_test('a:b:c', ':', ['a', 'b', 'c'])
     180
     181    def test_clean_line_10(self):
     182        self.clean_line_test('a:b:c:', ':', ['a', 'b', 'c'])
     183
     184    # new version of function should leave last field if contains '\n'.
     185    # cf. test_clean_line_10() above.
     186    def test_clean_line_11(self):
     187        self.clean_line_test('a:b:c:\n', ':', ['a', 'b', 'c', ''])
     188
     189################################################################################
     190
    140191if __name__ == "__main__":
    141192    suite = unittest.makeSuite(Test_system_tools, 'test')
     
    143194    runner.run(suite)
    144195
    145 
    146 
    147 
  • branches/numpy/anuga/utilities/test_xml_tools.py

    r6158 r6360  
    307307        os.remove(tmp_name)
    308308
    309        
    310        
    311 #-------------------------------------------------------------
     309################################################################################
     310
    312311if __name__ == "__main__":
    313312    suite = unittest.makeSuite(Test_xml_tools, 'test')
Note: See TracChangeset for help on using the changeset viewer.