Changeset 1018


Ignore:
Timestamp:
Mar 7, 2005, 9:32:07 AM (20 years ago)
Author:
steve
Message:

Cleaned up test function

Location:
inundation/ga/storm_surge/pyvolution
Files:
17 edited

Legend:

Unmodified
Added
Removed
  • inundation/ga/storm_surge/pyvolution/data_manager.py

    r995 r1018  
    55  2: Variable data: Conserved quantities. Stored once per timestep.
    66
    7 All data is assumed to reside at vertex locations. 
     7All data is assumed to reside at vertex locations.
    88
    99
     
    3838PTS + TSH -> TSH with elevation: Least squares fit
    3939
    40 TSH -> SWW:  Conversion of TSH to sww viewable using Swollen 
     40TSH -> SWW:  Conversion of TSH to sww viewable using Swollen
    4141
    4242TSH + Boundary SWW -> SWW: SImluation using pyvolution
     
    4545"""
    4646
    47 from Numeric import concatenate       
     47from Numeric import concatenate
    4848
    4949
     
    5656    s = s.replace('(', '')
    5757    s = s.replace(')', '')
    58     s = s.replace('__', '_')               
    59        
     58    s = s.replace('__', '_')
     59
    6060    return s
    6161
     
    6363def check_dir(path, verbose=None):
    6464    """Check that specified path exists.
    65     If path does not exist it will be created if possible   
     65    If path does not exist it will be created if possible
    6666
    6767    USAGE:
     
    7474    RETURN VALUE:
    7575        Verified path including trailing separator
    76        
     76
    7777    """
    7878
     
    8686
    8787
    88     if path[-1] != os.sep: 
     88    if path[-1] != os.sep:
    8989        path = path + os.sep  # Add separator for directories
    9090
     
    100100            else:
    101101                pass  # FIXME: What about acces rights under Windows?
    102            
     102
    103103            if verbose: print 'MESSAGE: Directory', path, 'created.'
    104          
     104
    105105        except:
    106106            print 'WARNING: Directory', path, 'could not be created.'
     
    109109            else:
    110110                path = 'C:'
    111                
     111
    112112            print 'Using directory %s instead' %path
    113113
    114114    return(path)
    115115
    116    
     116
    117117
    118118def del_dir(path):
     
    128128
    129129            if os.path.isdir(X) and not os.path.islink(X):
    130                 del_dir(X) 
     130                del_dir(X)
    131131            else:
    132132                try:
     
    138138
    139139
    140        
     140
    141141def create_filename(datadir, filename, format, size=None, time=None):
    142142
    143143    import os
    144144    #from config import data_dir
    145            
     145
    146146    FN = check_dir(datadir) + filename
    147    
    148     if size is not None:           
     147
     148    if size is not None:
    149149        FN += '_size%d' %size
    150150
    151151    if time is not None:
    152152        FN += '_time%.2f' %time
    153        
     153
    154154    FN += '.' + format
    155155    return FN
    156    
     156
    157157
    158158def get_files(datadir, filename, format, size):
     
    164164    import os
    165165    #from config import data_dir
    166            
     166
    167167    dir = check_dir(datadir)
    168168
     
    177177    """
    178178
    179        
     179
    180180    def __init__(self, domain, extension, mode = 'w'):
    181181        assert mode in ['r', 'w', 'a'], '''Mode %s must be either:''' %mode +\
    182182                                        '''   'w' (write)'''+\
    183183                                        '''   'r' (read)''' +\
    184                                         '''   'a' (append)'''   
     184                                        '''   'a' (append)'''
    185185
    186186        #Create filename
    187         #self.filename = create_filename(domain.get_datadir(), 
    188         #       domain.get_name(), extension, len(domain))
    189 
    190        
    191         self.filename = create_filename(domain.get_datadir(), 
    192                         domain.get_name(), extension)   
     187        #self.filename = create_filename(domain.get_datadir(),
     188        #domain.get_name(), extension, len(domain))
     189
     190
     191        self.filename = create_filename(domain.get_datadir(),
     192                        domain.get_name(), extension)
    193193
    194194        #print 'F', self.filename
     
    196196        self.number_of_volumes = len(domain)
    197197        self.domain = domain
    198    
    199    
    200     #FIXME: Should we have a general set_precision function?
    201    
     198
     199
     200        #FIXME: Should we have a general set_precision function?
     201
    202202
    203203
     
    207207    """
    208208
    209        
     209
    210210    def __init__(self, domain, mode = 'w'):
    211211        from Scientific.IO.NetCDF import NetCDFFile
    212         from Numeric import Int, Float, Float32 
     212        from Numeric import Int, Float, Float32
    213213
    214214        self.precision = Float32 #Use single precision
    215        
     215
    216216        Data_format.__init__(self, domain, 'sww', mode)
    217217
     
    219219        # NetCDF file definition
    220220        fid = NetCDFFile(self.filename, mode)
    221        
     221
    222222        if mode == 'w':
    223            
     223
    224224            #Create new file
    225225            fid.institution = 'Geoscience Australia'
    226226            fid.description = 'Output from pyvolution suitable for plotting'
    227            
     227
    228228            if domain.smooth:
    229229                fid.smoothing = 'Yes'
    230             else:   
     230            else:
    231231                fid.smoothing = 'No'
    232232
    233             fid.order = domain.default_order   
    234 
    235             #Reference point
    236             #Start time in seconds since the epoch (midnight 1/1/1970)
    237             fid.starttime = domain.starttime
     233            fid.order = domain.default_order
     234
     235            #Reference point
     236            #Start time in seconds since the epoch (midnight 1/1/1970)
     237            fid.starttime = domain.starttime
    238238            fid.xllcorner = domain.xllcorner
    239239            fid.yllcorner = domain.yllcorner
     
    241241
    242242            # dimension definitions
    243             fid.createDimension('number_of_volumes', self.number_of_volumes) 
     243            fid.createDimension('number_of_volumes', self.number_of_volumes)
    244244            fid.createDimension('number_of_vertices', 3)
    245245
    246246            if domain.smooth is True:
    247247                fid.createDimension('number_of_points', len(domain.vertexlist))
    248             else:   
     248            else:
    249249                fid.createDimension('number_of_points', 3*self.number_of_volumes)
    250                
     250
    251251            fid.createDimension('number_of_timesteps', None) #extensible
    252252
     
    255255            fid.createVariable('y', self.precision, ('number_of_points',))
    256256            fid.createVariable('elevation', self.precision, ('number_of_points',))
    257            
     257
    258258            #FIXME: Backwards compatibility
    259259            fid.createVariable('z', self.precision, ('number_of_points',))
    260260            #################################
    261        
     261
    262262            fid.createVariable('volumes', Int, ('number_of_volumes',
    263263                                                'number_of_vertices'))
     
    265265            fid.createVariable('time', self.precision,
    266266                               ('number_of_timesteps',))
    267        
     267
    268268            fid.createVariable('stage', self.precision,
    269269                               ('number_of_timesteps',
     
    279279
    280280        #Close
    281         fid.close()               
     281        fid.close()
    282282
    283283
     
    297297        #Get NetCDF
    298298        fid = NetCDFFile(self.filename, 'a')  #Open existing file for append
    299        
     299
    300300        # Get the variables
    301301        x = fid.variables['x']
    302302        y = fid.variables['y']
    303303        z = fid.variables['elevation']
    304        
     304
    305305        volumes = fid.variables['volumes']
    306306
     
    309309        X,Y,Z,V = Q.get_vertex_values(xy=True,
    310310                                      precision = self.precision)
    311                                      
     311
    312312
    313313
     
    315315        y[:] = Y.astype(self.precision)
    316316        z[:] = Z.astype(self.precision)
    317        
     317
    318318        #FIXME: Backwards compatibility
    319319        z = fid.variables['z']
    320         z[:] = Z.astype(self.precision) 
     320        z[:] = Z.astype(self.precision)
    321321        ################################
    322322
    323323        volumes[:] = V.astype(volumes.typecode())
    324        
     324
    325325        #Close
    326326        fid.close()
     
    334334        from time import sleep
    335335
    336                
     336
    337337        #Get NetCDF
    338338        retries = 0
    339339        file_open = False
    340340        while not file_open and retries < 10:
    341             try:       
     341            try:
    342342                fid = NetCDFFile(self.filename, 'a') #Open existing file
    343343            except IOError:
     
    352352            else:
    353353               file_open = True
    354                
     354
    355355        if not file_open:
    356356            msg = 'File %s could not be opened for append' %self.filename
    357357            raise msg
    358                
    359            
     358
     359
    360360        domain = self.domain
    361        
     361
    362362        # Get the variables
    363363        time = fid.variables['time']
    364364        stage = fid.variables['stage']
    365365        xmomentum = fid.variables['xmomentum']
    366         ymomentum = fid.variables['ymomentum']                       
     366        ymomentum = fid.variables['ymomentum']
    367367        i = len(time)
    368368
     
    374374            names = [names]
    375375
    376         for name in names:   
     376        for name in names:
    377377            # Get quantity
    378378            Q = domain.quantities[name]
     
    386386                xmomentum[i,:] = A.astype(self.precision)
    387387            elif name == 'ymomentum':
    388                 ymomentum[i,:] = A.astype(self.precision)   
    389                                      
     388                ymomentum[i,:] = A.astype(self.precision)
     389
    390390            #As in....
    391391            #eval( name + '[i,:] = A.astype(self.precision)' )
    392392            #FIXME: But we need a UNIT test for that before refactoring
    393            
    394            
     393
     394
    395395
    396396        #Flush and close
     
    404404    """
    405405
    406        
     406
    407407    def __init__(self, domain, mode = 'w'):
    408408        from Scientific.IO.NetCDF import NetCDFFile
    409         from Numeric import Int, Float, Float 
     409        from Numeric import Int, Float, Float
    410410
    411411        self.precision = Float #Use full precision
    412        
     412
    413413        Data_format.__init__(self, domain, 'sww', mode)
    414414
     
    416416        # NetCDF file definition
    417417        fid = NetCDFFile(self.filename, mode)
    418        
     418
    419419        if mode == 'w':
    420420            #Create new file
    421421            fid.institution = 'Geoscience Australia'
    422422            fid.description = 'Checkpoint data'
    423             #fid.smooth = domain.smooth               
    424             fid.order = domain.default_order   
     423            #fid.smooth = domain.smooth
     424            fid.order = domain.default_order
    425425
    426426            # dimension definitions
    427             fid.createDimension('number_of_volumes', self.number_of_volumes) 
     427            fid.createDimension('number_of_volumes', self.number_of_volumes)
    428428            fid.createDimension('number_of_vertices', 3)
    429429
     
    438438            fid.createVariable('y', self.precision, ('number_of_points',))
    439439
    440        
     440
    441441            fid.createVariable('volumes', Int, ('number_of_volumes',
    442442                                                'number_of_vertices'))
     
    452452
    453453        #Close
    454         fid.close()               
     454        fid.close()
    455455
    456456
     
    471471        #Get NetCDF
    472472        fid = NetCDFFile(self.filename, 'a')  #Open existing file for append
    473        
     473
    474474        # Get the variables
    475475        x = fid.variables['x']
    476476        y = fid.variables['y']
    477        
     477
    478478        volumes = fid.variables['volumes']
    479479
     
    482482        X,Y,Z,V = Q.get_vertex_values(xy=True,
    483483                                      precision = self.precision)
    484                                      
     484
    485485
    486486
     
    490490
    491491        volumes[:] = V
    492        
     492
    493493        #Close
    494494        fid.close()
     
    500500        from Scientific.IO.NetCDF import NetCDFFile
    501501        from time import sleep
    502                
     502
    503503        #Get NetCDF
    504504        retries = 0
    505505        file_open = False
    506506        while not file_open and retries < 10:
    507             try:       
     507            try:
    508508                fid = NetCDFFile(self.filename, 'a') #Open existing file
    509509            except IOError:
     
    518518            else:
    519519               file_open = True
    520                
     520
    521521        if not file_open:
    522522            msg = 'File %s could not be opened for append' %self.filename
    523523            raise msg
    524                
    525            
     524
     525
    526526        domain = self.domain
    527        
     527
    528528        # Get the variables
    529529        time = fid.variables['time']
    530         stage = fid.variables['stage']       
     530        stage = fid.variables['stage']
    531531        i = len(time)
    532532
     
    538538        A,V = Q.get_vertex_values(xy=False,
    539539                                  precision = self.precision)
    540        
     540
    541541        stage[i,:] = A.astype(self.precision)
    542542
     
    560560    def __init__(self, domain, mode = 'w'):
    561561        from Scientific.IO.NetCDF import NetCDFFile
    562         from Numeric import Int, Float, Float32 
     562        from Numeric import Int, Float, Float32
    563563
    564564        self.precision = Float32 #Use single precision
    565        
     565
    566566        Data_format.__init__(self, domain, 'xya', mode)
    567        
    568    
    569    
    570     #FIXME -This is the old xya format 
     567
     568
     569
     570    #FIXME -This is the old xya format
    571571    def store_all(self):
    572572        """Specialisation of store all for xya format
     
    579579
    580580        domain = self.domain
    581        
     581
    582582        fd = open(self.filename, 'w')
    583583
     
    585585        if domain.smooth is True:
    586586            number_of_points =  len(domain.vertexlist)
    587         else:   
     587        else:
    588588            number_of_points = 3*self.number_of_volumes
    589589
     
    613613            s = '%.6f %.6f %.6f %.6f %.6f\n' %(x, y, bed_ele, stage, frict)
    614614            fd.write(s)
    615            
     615
    616616        #close
    617617        fd.close()
     
    622622        """
    623623        pass
    624    
     624
    625625
    626626#Auxiliary
     
    634634
    635635       e.g. the x coordinate of vertex 1 of element i is in x[i,1]
    636        
     636
    637637    """
    638638    #print 'Writing obj to %s' % filename
     
    645645    else:
    646646        FN = filename + '.obj'
    647        
     647
    648648
    649649    outfile = open(FN, 'wb')
     
    669669    """Convert netcdf based data output to obj
    670670    """
    671     from Scientific.IO.NetCDF import NetCDFFile       
     671    from Scientific.IO.NetCDF import NetCDFFile
    672672
    673673    from Numeric import Float, zeros
     
    678678    fid = NetCDFFile(FN, 'r')  #Open existing file for read
    679679
    680        
     680
    681681    # Get the variables
    682682    x = fid.variables['x']
    683683    y = fid.variables['y']
    684     z = fid.variables['elevation']       
     684    z = fid.variables['elevation']
    685685    time = fid.variables['time']
    686686    stage = fid.variables['stage']
    687        
     687
    688688    M = size  #Number of lines
    689689    xx = zeros((M,3), Float)
     
    696696            yy[i,j] = y[i+j*M]
    697697            zz[i,j] = z[i+j*M]
    698        
     698
    699699    #Write obj for bathymetry
    700     FN = create_filename('.', basefilename, 'obj', size)       
     700    FN = create_filename('.', basefilename, 'obj', size)
    701701    write_obj(FN,xx,yy,zz)
    702702
     
    716716        #Write obj for variable data
    717717        #FN = create_filename(basefilename, 'obj', size, time=t)
    718         FN = create_filename('.', basefilename[:5], 'obj', size, time=t)   
     718        FN = create_filename('.', basefilename[:5], 'obj', size, time=t)
    719719        write_obj(FN,xx,yy,zz)
    720720
     
    727727    import glob, os
    728728    from config import data_dir
    729    
    730    
     729
     730
    731731    #Get bathymetry and x,y's
    732732    lines = open(data_dir+os.sep+basefilename+'_geometry.dat', 'r').readlines()
    733    
     733
    734734    from Numeric import zeros, Float
    735735
     
    742742    for i, line in enumerate(lines):
    743743        tokens = line.split()
    744         values = map(float,tokens)       
     744        values = map(float,tokens)
    745745
    746746        for j in range(3):
    747747            x[i,j] = values[j*3]
    748748            y[i,j] = values[j*3+1]
    749             z[i,j] = values[j*3+2]       
    750        
     749            z[i,j] = values[j*3+2]
     750
    751751        ##i += 1
    752752
     
    774774            #Skip bathymetry file
    775775            continue
    776        
    777         i0 += 6  #Position where time starts           
    778         i1 = filename.find('.dat')         
     776
     777        i0 += 6  #Position where time starts
     778        i1 = filename.find('.dat')
    779779
    780780        if i1 > i0:
     
    782782        else:
    783783            raise 'Hmmmm'
    784                
    785        
    786        
     784
     785
     786
    787787        ##i = 0
    788788        for i, line in enumerate(lines):
    789789            tokens = line.split()
    790             values = map(float,tokens)       
     790            values = map(float,tokens)
    791791
    792792            for j in range(3):
    793                 z[i,j] = values[j]       
    794        
     793                z[i,j] = values[j]
     794
    795795            ##i += 1
    796796
     
    803803    nettcdf file filename2
    804804    """
    805     from Scientific.IO.NetCDF import NetCDFFile       
    806    
     805    from Scientific.IO.NetCDF import NetCDFFile
     806
    807807    #Get NetCDF
    808808    infile = NetCDFFile(filename1, 'r')  #Open existing file for read
    809809    outfile = NetCDFFile(filename2, 'w')  #Open new file
    810    
     810
    811811
    812812    #Copy dimensions
     
    817817        var = infile.variables[name]
    818818        outfile.createVariable(name, var.typecode(), var.dimensions)
    819        
    820    
     819
     820
    821821    #Copy the static variables
    822822    for name in infile.variables:
     
    825825        else:
    826826            #Copy
    827             outfile.variables[name][:] = infile.variables[name][:]           
    828 
    829     #Copy selected timesteps 
     827            outfile.variables[name][:] = infile.variables[name][:]
     828
     829    #Copy selected timesteps
    830830    time = infile.variables['time']
    831831    stage = infile.variables['stage']
    832832
    833833    newtime = outfile.variables['time']
    834     newstage = outfile.variables['stage']   
     834    newstage = outfile.variables['stage']
    835835
    836836    if last is None:
     
    841841        print 'Copying timestep %d of %d (%f)' %(j, last-first, time[j])
    842842        newtime[i] = time[j]
    843         newstage[i,:] = stage[j,:]       
    844        
     843        newstage[i,:] = stage[j,:]
     844
    845845    #Close
    846846    infile.close()
     
    873873    points:  (Nx2) Float array
    874874    elevation: N Float array
    875     """ 
     875    """
    876876
    877877    import os
    878878    from Scientific.IO.NetCDF import NetCDFFile
    879     from Numeric import Float, arrayrange, concatenate   
     879    from Numeric import Float, arrayrange, concatenate
    880880
    881881    root = basename_in
     
    885885
    886886    if verbose: print 'Reading DEM from %s' %(root + '.dem')
    887    
     887
    888888    ncols = infile.ncols[0]
    889889    nrows = infile.nrows[0]
     
    902902    datum = infile.datum
    903903    units = infile.units
    904    
     904
    905905
    906906    #Get output file
     
    909909    else:
    910910        ptsname = basename_out + '.pts'
    911        
     911
    912912    if verbose: print 'Store to NetCDF file %s' %ptsname
    913913    # NetCDF file definition
    914914    outfile = NetCDFFile(ptsname, 'w')
    915        
     915
    916916    #Create new file
    917917    outfile.institution = 'Geoscience Australia'
     
    925925    outfile.false_easting = false_easting
    926926    outfile.false_northing =false_northing
    927    
     927
    928928    outfile.projection = projection
    929929    outfile.datum = datum
     
    935935    outfile.nrows = nrows
    936936
    937    
     937
    938938    # dimension definitions
    939     outfile.createDimension('number_of_points', nrows*ncols)   
     939    outfile.createDimension('number_of_points', nrows*ncols)
    940940    outfile.createDimension('number_of_dimensions', 2) #This is 2d data
    941    
     941
    942942    # variable definitions
    943943    outfile.createVariable('points', Float, ('number_of_points',
     
    953953    for i in range(nrows):
    954954        if verbose: print 'Processing row %d of %d' %(i, nrows)
    955        
    956         y = (nrows-i)*cellsize           
     955
     956        y = (nrows-i)*cellsize
    957957        for j in range(ncols):
    958958            index = i*ncols + j
    959            
     959
    960960            x = j*cellsize
    961961            points[index, :] = [x,y]
    962             elevation[index] = dem_elevation[i, j]           
    963 
    964     infile.close()           
     962            elevation[index] = dem_elevation[i, j]
     963
     964    infile.close()
    965965    outfile.close()
    966966
    967                                      
     967
    968968def convert_dem_from_ascii2netcdf(basename_in, basename_out = None,
    969969                                  verbose=False):
     
    988988
    989989    The prj format is assumed to be as
    990    
     990
    991991    Projection    UTM
    992992    Zone          56
     
    998998    Yshift        10000000.0000000000
    999999    Parameters
    1000     """ 
     1000    """
    10011001
    10021002    import os
     
    10101010    # Read Meta data
    10111011    if verbose: print 'Reading METADATA from %s' %root + '.prj'
    1012     metadatafile = open(root + '.prj')   
     1012    metadatafile = open(root + '.prj')
    10131013    metalines = metadatafile.readlines()
    10141014    metadatafile.close()
     
    10201020    L = metalines[1].strip().split()
    10211021    assert L[0].strip().lower() == 'zone'
    1022     zone = int(L[1].strip())   
     1022    zone = int(L[1].strip())
    10231023
    10241024    L = metalines[2].strip().split()
    10251025    assert L[0].strip().lower() == 'datum'
    1026     datum = L[1].strip()                        #TEXT 
    1027 
    1028     L = metalines[3].strip().split()     
     1026    datum = L[1].strip()                        #TEXT
     1027
     1028    L = metalines[3].strip().split()
    10291029    assert L[0].strip().lower() == 'zunits'     #IGNORE
    10301030    zunits = L[1].strip()                       #TEXT
     
    10391039
    10401040    L = metalines[6].strip().split()
    1041     assert L[0].strip().lower() == 'xshift'     
     1041    assert L[0].strip().lower() == 'xshift'
    10421042    false_easting = float(L[1].strip())
    10431043
    10441044    L = metalines[7].strip().split()
    10451045    assert L[0].strip().lower() == 'yshift'
    1046     false_northing = float(L[1].strip())   
     1046    false_northing = float(L[1].strip())
    10471047
    10481048    #print false_easting, false_northing, zone, datum
     
    10511051    ###########################################
    10521052    #Read DEM data
    1053    
     1053
    10541054    datafile = open(basename_in + '.asc')
    10551055
     
    10591059
    10601060    if verbose: print 'Got', len(lines), ' lines'
    1061    
     1061
    10621062    ncols = int(lines[0].split()[1].strip())
    10631063    nrows = int(lines[1].split()[1].strip())
     
    10761076        netcdfname = root + '.dem'
    10771077    else:
    1078         netcdfname = basename_out + '.dem'       
    1079        
     1078        netcdfname = basename_out + '.dem'
     1079
    10801080    if verbose: print 'Store to NetCDF file %s' %netcdfname
    10811081    # NetCDF file definition
    10821082    fid = NetCDFFile(netcdfname, 'w')
    1083        
     1083
    10841084    #Create new file
    10851085    fid.institution = 'Geoscience Australia'
     
    10961096    fid.zone = zone
    10971097    fid.false_easting = false_easting
    1098     fid.false_northing = false_northing   
     1098    fid.false_northing = false_northing
    10991099    fid.projection = projection
    11001100    fid.datum = datum
    11011101    fid.units = units
    1102    
     1102
    11031103
    11041104    # dimension definitions
    11051105    fid.createDimension('number_of_rows', nrows)
    1106     fid.createDimension('number_of_columns', ncols)           
     1106    fid.createDimension('number_of_columns', ncols)
    11071107
    11081108    # variable definitions
     
    11221122    fid.close()
    11231123
    1124    
     1124
    11251125
    11261126def ferret2sww(basename_in, basename_out = None,
     
    11531153    ferret2sww uses grid points as vertices in a triangular grid
    11541154    counting vertices from lower left corner upwards, then right
    1155     """ 
     1155    """
    11561156
    11571157    import os
    11581158    from Scientific.IO.NetCDF import NetCDFFile
    11591159    from Numeric import Float, Int, Int32, searchsorted, zeros, array
    1160     precision = Float 
     1160    precision = Float
    11611161
    11621162
     
    11651165    file_h = NetCDFFile(basename_in + '_ha.nc', 'r') #Wave amplitude (cm)
    11661166    file_u = NetCDFFile(basename_in + '_ua.nc', 'r') #Velocity (x) (cm/s)
    1167     file_v = NetCDFFile(basename_in + '_va.nc', 'r') #Velocity (y) (cm/s)   
     1167    file_v = NetCDFFile(basename_in + '_va.nc', 'r') #Velocity (y) (cm/s)
    11681168
    11691169    if basename_out is None:
    11701170        swwname = basename_in + '.sww'
    11711171    else:
    1172         swwname = basename_out + '.sww'       
     1172        swwname = basename_out + '.sww'
    11731173
    11741174    times = file_h.variables['TIME']
     
    11781178    if mint == None:
    11791179        jmin = 0
    1180     else:   
     1180    else:
    11811181        jmin = searchsorted(times, mint)
    1182    
     1182
    11831183    if maxt == None:
    11841184        jmax=len(times)
    1185     else:   
     1185    else:
    11861186        jmax = searchsorted(times, maxt)
    1187        
     1187
    11881188    if minlat == None:
    11891189        kmin=0
     
    11981198    if minlon == None:
    11991199        lmin=0
    1200     else:   
     1200    else:
    12011201        lmin = searchsorted(longitudes, minlon)
    1202    
     1202
    12031203    if maxlon == None:
    12041204        lmax = len(longitudes)
    12051205    else:
    1206         lmax = searchsorted(longitudes, maxlon)           
    1207 
    1208     times = times[jmin:jmax]       
     1206        lmax = searchsorted(longitudes, maxlon)
     1207
     1208    times = times[jmin:jmax]
    12091209    latitudes = latitudes[kmin:kmax]
    12101210    longitudes = longitudes[lmin:lmax]
     
    12141214    amplitudes = file_h.variables['HA'][jmin:jmax, kmin:kmax, lmin:lmax]
    12151215    xspeed = file_u.variables['UA'][jmin:jmax, kmin:kmax, lmin:lmax]
    1216     yspeed = file_v.variables['VA'][jmin:jmax, kmin:kmax, lmin:lmax]   
     1216    yspeed = file_v.variables['VA'][jmin:jmax, kmin:kmax, lmin:lmax]
    12171217
    12181218    number_of_times = times.shape[0]
     
    12221222    assert amplitudes.shape[0] == number_of_times
    12231223    assert amplitudes.shape[1] == number_of_latitudes
    1224     assert amplitudes.shape[2] == number_of_longitudes         
     1224    assert amplitudes.shape[2] == number_of_longitudes
    12251225
    12261226    #print times
     
    12291229
    12301230    #print 'MIN', min(min(min(amplitudes)))
    1231     #print 'MAX', max(max(max(amplitudes)))   
     1231    #print 'MAX', max(max(max(amplitudes)))
    12321232
    12331233    #print number_of_latitudes, number_of_longitudes
    12341234    number_of_points = number_of_latitudes*number_of_longitudes
    12351235    number_of_volumes = (number_of_latitudes-1)*(number_of_longitudes-1)*2
    1236    
     1236
    12371237    #print file_h.dimensions.keys()
    1238     #print file_h.variables.keys()   
     1238    #print file_h.variables.keys()
    12391239
    12401240    file_h.close()
    12411241    file_u.close()
    1242     file_v.close()   
     1242    file_v.close()
    12431243
    12441244
     
    12461246    # NetCDF file definition
    12471247    outfile = NetCDFFile(swwname, 'w')
    1248        
     1248
    12491249    #Create new file
    12501250    outfile.institution = 'Geoscience Australia'
     
    12561256
    12571257    #For sww compatibility
    1258     outfile.smoothing = 'Yes' 
     1258    outfile.smoothing = 'Yes'
    12591259    outfile.order = 1
    1260            
     1260
    12611261    #Start time in seconds since the epoch (midnight 1/1/1970)
    12621262    outfile.starttime = times[0]
    1263    
     1263
    12641264    # dimension definitions
    12651265    outfile.createDimension('number_of_volumes', number_of_volumes)
     
    12671267    outfile.createDimension('number_of_vertices', 3)
    12681268    outfile.createDimension('number_of_points', number_of_points)
    1269                            
    1270                
     1269
     1270
    12711271    #outfile.createDimension('number_of_timesteps', len(times))
    12721272    outfile.createDimension('number_of_timesteps', len(times))
     
    12761276    outfile.createVariable('y', precision, ('number_of_points',))
    12771277    outfile.createVariable('elevation', precision, ('number_of_points',))
    1278            
     1278
    12791279    #FIXME: Backwards compatibility
    12801280    outfile.createVariable('z', precision, ('number_of_points',))
    12811281    #################################
    1282        
     1282
    12831283    outfile.createVariable('volumes', Int, ('number_of_volumes',
    12841284                                            'number_of_vertices'))
    1285    
     1285
    12861286    outfile.createVariable('time', precision,
    12871287                           ('number_of_timesteps',))
    1288        
     1288
    12891289    outfile.createVariable('stage', precision,
    12901290                           ('number_of_timesteps',
     
    12941294                           ('number_of_timesteps',
    12951295                            'number_of_points'))
    1296    
     1296
    12971297    outfile.createVariable('ymomentum', precision,
    12981298                           ('number_of_timesteps',
     
    13081308
    13091309    #Check zone boundaries
    1310     refzone, _, _ = redfearn(latitudes[0],longitudes[0])   
     1310    refzone, _, _ = redfearn(latitudes[0],longitudes[0])
    13111311
    13121312    vertices = {}
    1313     for k, lat in enumerate(latitudes):   
    1314         for l, lon in enumerate(longitudes):   
     1313    for k, lat in enumerate(latitudes):
     1314        for l, lon in enumerate(longitudes):
    13151315
    13161316            vertices[l,k] = i
    13171317
    1318             zone, easting, northing = redfearn(lat,lon)               
     1318            zone, easting, northing = redfearn(lat,lon)
    13191319
    13201320            msg = 'Zone boundary crossed at longitude =', lon
     
    13311331        for k in range(number_of_latitudes-1):
    13321332            v1 = vertices[l,k+1]
    1333             v2 = vertices[l,k]           
    1334             v3 = vertices[l+1,k+1]           
    1335             v4 = vertices[l+1,k]           
     1333            v2 = vertices[l,k]
     1334            v3 = vertices[l+1,k+1]
     1335            v4 = vertices[l+1,k]
    13361336
    13371337            volumes.append([v1,v2,v3]) #Upper element
    1338             volumes.append([v4,v3,v2]) #Lower element           
    1339 
    1340     volumes = array(volumes)       
     1338            volumes.append([v4,v3,v2]) #Lower element
     1339
     1340    volumes = array(volumes)
    13411341
    13421342    if origin == None:
    1343         zone = refzone       
     1343        zone = refzone
    13441344        xllcorner = min(x)
    13451345        yllcorner = min(y)
     
    13471347        zone = origin[0]
    13481348        xllcorner = origin[1]
    1349         yllcorner = origin[2]               
    1350 
    1351    
     1349        yllcorner = origin[2]
     1350
     1351
    13521352    outfile.xllcorner = xllcorner
    13531353    outfile.yllcorner = yllcorner
     
    13581358    outfile.variables['z'][:] = 0.0
    13591359    outfile.variables['elevation'][:] = 0.0
    1360     outfile.variables['time'][:] = times       
     1360    outfile.variables['time'][:] = times
    13611361    outfile.variables['volumes'][:] = volumes.astype(Int32) #On Opteron 64
    1362    
     1362
    13631363
    13641364
     
    13661366    stage = outfile.variables['stage']
    13671367    xmomentum = outfile.variables['xmomentum']
    1368     ymomentum = outfile.variables['ymomentum']       
     1368    ymomentum = outfile.variables['ymomentum']
    13691369
    13701370    for j in range(len(times)):
    13711371        i = 0
    13721372        for k in range(number_of_latitudes):
    1373             for l in range(number_of_longitudes):                   
     1373            for l in range(number_of_longitudes):
    13741374                h = zscale*amplitudes[j,k,l]/100 + mean_stage
    13751375                stage[j,i] = h
    13761376                xmomentum[j,i] = xspeed[j,k,l]/100*h
    1377                 ymomentum[j,i] = yspeed[j,k,l]/100*h               
     1377                ymomentum[j,i] = yspeed[j,k,l]/100*h
    13781378                i += 1
    1379        
    1380     outfile.close()               
    1381    
    1382  
     1379
     1380    outfile.close()
     1381
     1382
    13831383def extent_sww(file_name):
    13841384    """
    13851385    Read in an sww file.
    1386    
     1386
    13871387    Input;
    13881388    file_name - the sww file
    1389    
     1389
    13901390    Output;
    13911391    z - Vector of bed elevation
     
    13951395    stage - array with respect to time and vertices (x,y)
    13961396    """
    1397        
    1398    
    1399     from Scientific.IO.NetCDF import NetCDFFile         
    1400    
     1397
     1398
     1399    from Scientific.IO.NetCDF import NetCDFFile
     1400
    14011401    #Check contents
    14021402    #Get NetCDF
    1403     fid = NetCDFFile(file_name, 'r') 
    1404    
     1403    fid = NetCDFFile(file_name, 'r')
     1404
    14051405    # Get the variables
    14061406    x = fid.variables['x'][:]
     
    14131413
    14141414    fid.close()
    1415    
     1415
    14161416    return [min(x),max(x),min(y),max(y),min(stage.flat),max(stage.flat)]
    14171417
     
    14261426
    14271427    M, N = v0.shape
    1428        
     1428
    14291429    FN = create_filename(filename, 'cpt', M, t)
    14301430    #print 'Writing to %s' %FN
    1431    
     1431
    14321432    fid = open(FN, 'w')
    14331433    for i in range(M):
    1434         for j in range(N):       
    1435             fid.write('%.16e ' %v0[i,j])           
    14361434        for j in range(N):
    1437             fid.write('%.16e ' %v1[i,j])                       
     1435            fid.write('%.16e ' %v0[i,j])
    14381436        for j in range(N):
    1439             fid.write('%.16e ' %v2[i,j])                       
    1440            
     1437            fid.write('%.16e ' %v1[i,j])
     1438        for j in range(N):
     1439            fid.write('%.16e ' %v2[i,j])
     1440
    14411441        fid.write('\n')
    14421442    fid.close()
     
    14481448
    14491449    M, N = v0.shape
    1450        
     1450
    14511451    FN = create_filename(filename, 'cpt', M, t)
    14521452    #print 'Reading from %s' %FN
    1453    
     1453
    14541454    fid = open(FN)
    14551455
     
    14621462            v1[i,j] = float(values[3+j])
    14631463            v2[i,j] = float(values[6+j])
    1464    
     1464
    14651465    fid.close()
    14661466
     
    14741474
    14751475    print X0
    1476     import sys; sys.exit() 
     1476    import sys; sys.exit()
    14771477    FN = create_filename(filename, 'cpt', M)
    14781478    print 'Writing to %s' %FN
    1479    
     1479
    14801480    fid = open(FN, 'w')
    14811481    for i in range(M):
    1482         for j in range(2):       
     1482        for j in range(2):
    14831483            fid.write('%.16e ' %X0[i,j])   #x, y
    1484         for j in range(N):                   
     1484        for j in range(N):
    14851485            fid.write('%.16e ' %v0[i,j])       #z,z,z,
    1486            
    1487         for j in range(2):                   
     1486
     1487        for j in range(2):
    14881488            fid.write('%.16e ' %X1[i,j])   #x, y
    1489         for j in range(N):                               
    1490             fid.write('%.16e ' %v1[i,j]) 
    1491        
    1492         for j in range(2):                               
     1489        for j in range(N):
     1490            fid.write('%.16e ' %v1[i,j])
     1491
     1492        for j in range(2):
    14931493            fid.write('%.16e ' %X2[i,j])   #x, y
    1494         for j in range(N):                                           
    1495             fid.write('%.16e ' %v2[i,j]) 
    1496            
     1494        for j in range(N):
     1495            fid.write('%.16e ' %v2[i,j])
     1496
    14971497        fid.write('\n')
    14981498    fid.close()
     
    15081508
    15091509    M, N = v0.shape
    1510        
     1510
    15111511    FN = create_filename(filename, 'dat', M)
    15121512    #print 'Writing to %s' %FN
    1513    
     1513
    15141514    fid = open(FN, 'w')
    15151515    for i in range(M):
    1516         for j in range(2):       
     1516        for j in range(2):
    15171517            fid.write('%f ' %X0[i,j])   #x, y
    15181518        fid.write('%f ' %v0[i,0])       #z
    1519            
    1520         for j in range(2):                   
     1519
     1520        for j in range(2):
    15211521            fid.write('%f ' %X1[i,j])   #x, y
    15221522        fid.write('%f ' %v1[i,0])       #z
    1523        
    1524         for j in range(2):                               
     1523
     1524        for j in range(2):
    15251525            fid.write('%f ' %X2[i,j])   #x, y
    15261526        fid.write('%f ' %v2[i,0])       #z
    1527            
     1527
    15281528        fid.write('\n')
    15291529    fid.close()
     
    15361536
    15371537    M, N = v0.shape
    1538        
     1538
    15391539    FN = create_filename(filename, 'dat', M, t)
    15401540    #print 'Writing to %s' %FN
    1541    
     1541
    15421542    fid = open(FN, 'w')
    15431543    for i in range(M):
    15441544        fid.write('%.4f ' %v0[i,0])
    15451545        fid.write('%.4f ' %v1[i,0])
    1546         fid.write('%.4f ' %v2[i,0])       
     1546        fid.write('%.4f ' %v2[i,0])
    15471547
    15481548        fid.write('\n')
    15491549    fid.close()
    1550 
  • inundation/ga/storm_surge/pyvolution/test_advection.py

    r773 r1018  
    88from advection import *
    99
    10        
    11 class TestCase(unittest.TestCase):
     10
     11class Test_Advection(unittest.TestCase):
    1212    def setUp(self):
    1313        pass
    14        
     14
    1515    def tearDown(self):
    1616        pass
     
    2525
    2626        points = [a, b, c, d, e, f]
    27         #bac, bce, ecf, dbe, daf, dae 
     27        #bac, bce, ecf, dbe, daf, dae
    2828        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4], [3,0,5], [3,0,4]]
    29        
    30         domain = Domain(points, vertices)       
     29
     30        domain = Domain(points, vertices)
    3131        domain.check_integrity()
    32        
     32
    3333        assert domain.quantities.has_key('stage')
    3434
     
    3838    def test_flux_1_triangle0(self):
    3939        a = [0.0, 0.5]
    40         b = [0.0, 0.0]               
     40        b = [0.0, 0.0]
    4141        c = [0.5, 0.5]
    4242
    4343        points = [a, b, c]
    4444        vertices = [ [0,1,2] ]
    45         domain = Domain(points, vertices)       
     45        domain = Domain(points, vertices)
    4646        domain.check_integrity()
    4747
    4848
    4949        #Populate boundary array with dirichlet conditions.
    50         domain.neighbours = array([[-1,-2,-3]])         
     50        domain.neighbours = array([[-1,-2,-3]])
    5151        domain.quantities['stage'].boundary_values[:] = 1.0
    5252
     
    5454
    5555        domain.distribute_to_vertices_and_edges() #Use first order default
    56        
     56
    5757        domain.check_integrity()
    5858
     
    6161        R = -0.5/domain.areas[0]
    6262
    63         assert U==R, '%s %s' %(U, R) 
     63        assert U==R, '%s %s' %(U, R)
    6464
    6565
    6666    def test_flux_1_triangle1(self):
    67  
     67
    6868        a = [0.0, 0.5]
    69         b = [0.0, 0.0]               
     69        b = [0.0, 0.0]
    7070        c = [0.5, 0.5]
    7171
    7272        points = [a, b, c]
    7373        vertices = [ [0,1,2] ]
    74         domain = Domain(points, vertices)       
     74        domain = Domain(points, vertices)
    7575        domain.check_integrity()
    7676
     
    7979        domain.distribute_to_vertices_and_edges()
    8080        domain.check_integrity()
    81        
    82        
     81
     82
    8383        domain.compute_fluxes()
    8484        U = -domain.quantities['stage'].explicit_update
    8585        R = 0.5/domain.areas[0]
    8686
    87         assert U==R, '%s %s' %(U, R) 
     87        assert U==R, '%s %s' %(U, R)
    8888
    8989
    9090
    9191    def test_flux_1_triangle2(self):
    92        
     92
    9393        a = [0.0, 0.5]
    94         b = [0.0, 0.0]               
     94        b = [0.0, 0.0]
    9595        c = [0.5, 0.5]
    9696
    9797        points = [a, b, c]
    9898        vertices = [ [0,1,2] ]
    99         domain = Domain(points, vertices)       
     99        domain = Domain(points, vertices)
    100100        domain.check_integrity()
    101101
    102                
     102
    103103        #Populate boundary array with dirichlet conditions.
    104         domain.neighbours = array([[-1,-2,-3]])                 
     104        domain.neighbours = array([[-1,-2,-3]])
    105105        domain.quantities['stage'].boundary_values[0] = 1.0
    106        
     106
    107107        domain.distribute_to_vertices_and_edges() #Use first order default
    108        
     108
    109109        domain.check_integrity()
    110110
     
    113113        assert allclose(U, 0)
    114114
    115        
     115
    116116
    117117
     
    122122
    123123        a = [0.0, 0.5]
    124         b = [0.0, 0.0]               
     124        b = [0.0, 0.0]
    125125        c = [0.5, 0.5]
    126         d = [0.5, 0.0]       
     126        d = [0.5, 0.0]
    127127
    128128        points = [a, b, c, d]
    129129        vertices = [ [0,1,2], [3,2,1] ]
    130         domain = Domain(points, vertices)       
     130        domain = Domain(points, vertices)
    131131        domain.check_integrity()
    132132
     
    137137        domain.distribute_to_vertices_and_edges()
    138138
    139         domain.compute_fluxes()         
     139        domain.compute_fluxes()
    140140
    141141        X = domain.quantities['stage'].explicit_update
    142142        assert X[0] == -X[1]
    143                        
     143
    144144
    145145    def test_advection_example(self):
    146146        #Test that system can evolve
    147        
     147
    148148        from mesh_factory import rectangular
    149149
    150150        points, vertices, boundary = rectangular(6, 6)
    151151
    152         #Create advection domain with direction (1,-1)       
     152        #Create advection domain with direction (1,-1)
    153153        domain = Domain(points, vertices, boundary, velocity=[1.0, -1.0])
    154154
    155155        # Initial condition is zero by default
    156        
     156
    157157        #Boundaries
    158158        T = Transmissive_boundary(domain)
    159159        D = Dirichlet_boundary(array([3.1415]))
    160        
     160
    161161        domain.set_boundary( {'left': D, 'right': T, 'bottom': T, 'top': T} )
    162162        domain.check_integrity()
     
    166166            if allclose(domain.quantities['stage'].centroid_values, 3.1415):
    167167                break
    168            
     168
    169169        assert allclose(domain.quantities['stage'].centroid_values, 3.1415)
    170170
    171        
     171
    172172#-------------------------------------------------------------
    173173if __name__ == "__main__":
    174     suite = unittest.makeSuite(TestCase,'test')
     174    suite = unittest.makeSuite(Test_Advection,'test')
    175175    runner = unittest.TextTestRunner()
    176176    runner.run(suite)
  • inundation/ga/storm_surge/pyvolution/test_all.py

    r892 r1018  
    2323
    2424    import sys
    25    
     25
    2626    files = os.listdir(path)
    2727
     
    3838        else:
    3939            pass
    40     return test_files   
     40    return test_files
    4141
    4242
    4343
    4444def regressionTest():
    45     import sys, os, re, unittest   
     45    import sys, os, re, unittest
    4646    path = os.path.split(sys.argv[0])[0] or os.getcwd()
    4747
     
    5353    #test = re.compile('^test_[\w]*.py$', re.IGNORECASE)
    5454    #files = filter(test.search, files)
    55    
     55
    5656
    5757    try:
    5858        files.remove(__file__)  #Remove self from list (Ver 2.3. or later)
    5959    except:
    60         files.remove('test_all.py') 
     60        files.remove('test_all.py')
    6161
    6262
    63     if globals().has_key('exclude'):   
     63    if globals().has_key('exclude'):
    6464        for file in exclude:
    6565            files.remove(file)
    6666            print 'WARNING: File '+ file + ' excluded from testing'
    67        
     67
    6868
    6969    filenameToModuleName = lambda f: os.path.splitext(f)[0]
     
    7676
    7777    os.system('python compile.py') #Attempt to compile all extensions
    78    
     78
     79    #print regressionTest()
    7980    unittest.main(defaultTest='regressionTest')
    80    
  • inundation/ga/storm_surge/pyvolution/test_cg_solve.py

    r599 r1018  
    99
    1010
    11 class TestCase(unittest.TestCase):
     11class Test_CG_Solve(unittest.TestCase):
    1212
    1313    def test_sparse_solve(self):
    1414        """Small Sparse Matrix"""
    15        
     15
    1616        A = [[2.0, -1.0, 0.0, 0.0 ],
    1717             [-1.0, 2.0, -1.0, 0.0],
    1818             [0.0, -1.0, 2.0, -1.0],
    1919             [0.0,0.0, -1.0, 2.0]]
    20        
     20
    2121        A = Sparse(A)
    2222
     
    3535        n = 50
    3636        A = Sparse(n,n)
    37        
     37
    3838        for i in arange(0,n):
    3939            A[i,i] = 1.0
     
    4242            if i < n-1 :
    4343                A[i,i+1] = -0.5
    44                
     44
    4545        xe = ones( (n,), Float)
    4646
     
    5252    def test_solve_large_2d(self):
    5353        """Standard 2d laplacian"""
    54        
     54
    5555        n = 20
    5656        m = 10
     
    7070                if j < m-1 :
    7171                    A[I,I+1] = -1.0
    72                
     72
    7373        xe = ones( (n*m,), Float)
    7474
     
    8181        """Standard 2d laplacian with csr format
    8282        """
    83        
     83
    8484        n = 100
    8585        m = 100
     
    9999                if j < m-1 :
    100100                    A[I,I+1] = -1.0
    101                
     101
    102102        xe = ones( (n*m,), Float)
    103103
     
    114114    def test_solve_large_2d_with_default_guess(self):
    115115        """Standard 2d laplacian using default first guess"""
    116        
     116
    117117        n = 20
    118118        m = 10
     
    132132                if j < m-1 :
    133133                    A[I,I+1] = -1.0
    134                
     134
    135135        xe = ones( (n*m,), Float)
    136136
     
    143143    def test_vector_shape_error(self):
    144144        """Raise VectorShapeError"""
    145        
     145
    146146        A = [[2.0, -1.0, 0.0, 0.0 ],
    147147             [-1.0, 2.0, -1.0, 0.0],
    148148             [0.0, -1.0, 2.0, -1.0],
    149149             [0.0,0.0, -1.0, 2.0]]
    150        
     150
    151151        A = Sparse(A)
    152152
     
    161161            raise msg
    162162
    163        
     163
    164164#-------------------------------------------------------------
    165165if __name__ == "__main__":
    166      suite = unittest.makeSuite(TestCase,'test')
     166     suite = unittest.makeSuite(Test_CG_Solve,'test')
    167167     runner = unittest.TextTestRunner() #(verbosity=2)
    168168     runner.run(suite)
    169169
    170    
    171    
    172170
    173171
  • inundation/ga/storm_surge/pyvolution/test_data_manager.py

    r995 r1018  
    1111from config import epsilon
    1212
    13 class dataTestCase(unittest.TestCase):
     13class Test_Data_Manager(unittest.TestCase):
    1414    def setUp(self):
    1515        import time
     
    2424        domain.default_order=2
    2525
    26        
     26
    2727        #Set some field values
    28         domain.set_quantity('elevation', lambda x,y: -x)       
     28        domain.set_quantity('elevation', lambda x,y: -x)
    2929        domain.set_quantity('friction', 0.03)
    3030
    3131
    32         ###################### 
     32        ######################
    3333        # Boundary conditions
    3434        B = Transmissive_boundary(domain)
    3535        domain.set_boundary( {'left': B, 'right': B, 'top': B, 'bottom': B})
    36        
    37 
    38         ###################### 
     36
     37
     38        ######################
    3939        #Initial condition - with jumps
    4040
     
    4545        h = 0.3
    4646        for i in range(stage.shape[0]):
    47             if i % 2 == 0:           
     47            if i % 2 == 0:
    4848                stage[i,:] = bed[i,:] + h
    4949            else:
    5050                stage[i,:] = bed[i,:]
    51                
     51
    5252        domain.set_quantity('stage', stage)
    5353        self.initial_stage = copy.copy(domain.quantities['stage'].vertex_values)
    5454
    55         domain.distribute_to_vertices_and_edges()   
     55        domain.distribute_to_vertices_and_edges()
    5656
    5757
     
    6161        self.X = C[:,0:6:2].copy()
    6262        self.Y = C[:,1:6:2].copy()
    63        
     63
    6464        self.F = bed
    6565
    66        
     66
    6767    def tearDown(self):
    6868        pass
    6969
    7070
    71        
     71
    7272
    7373#     def test_xya(self):
     
    7979
    8080#         domain = self.domain
    81        
     81
    8282#         domain.filename = 'datatest' + str(time.time())
    8383#         domain.format = 'xya'
    8484#         domain.smooth = True
    85        
     85
    8686#         xya = get_dataobject(self.domain)
    8787#         xya.store_all()
     
    9999#         if domain.smooth:
    100100#             self.failUnless(lFile[0] == '9 3 # <vertex #> <x> <y> [attributes]')
    101 #         else:   
    102 #             self.failUnless(lFile[0] == '24 3 # <vertex #> <x> <y> [attributes]')           
     101#         else:
     102#             self.failUnless(lFile[0] == '24 3 # <vertex #> <x> <y> [attributes]')
    103103
    104104#         #Get smoothed field values with X and Y
     
    108108
    109109#         Q,V = domain.get_vertex_values(xy=False, value_array='conserved_quantities',
    110 #                                            indices = (0,), precision = Float)       
    111 
    112 
    113        
     110#                                            indices = (0,), precision = Float)
     111
     112
     113
    114114#         for i, line in enumerate(lFile[1:]):
    115115#             fields = line.split()
     
    121121#             assert allclose(float(fields[2]), F[i,0])
    122122#             assert allclose(float(fields[3]), Q[i,0])
    123 #             assert allclose(float(fields[4]), F[i,1])           
     123#             assert allclose(float(fields[4]), F[i,1])
    124124
    125125
     
    133133        import time, os
    134134        from Numeric import array, zeros, allclose, Float, concatenate
    135         from Scientific.IO.NetCDF import NetCDFFile       
     135        from Scientific.IO.NetCDF import NetCDFFile
    136136
    137137        self.domain.filename = 'datatest' + str(id(self))
    138138        self.domain.format = 'sww'
    139139        self.domain.smooth = False
    140      
     140
    141141        sww = get_dataobject(self.domain)
    142142        sww.store_connectivity()
     
    145145        #Get NetCDF
    146146        fid = NetCDFFile(sww.filename, 'r')  #Open existing file for append
    147      
     147
    148148        # Get the variables
    149149        x = fid.variables['x']
     
    151151        z = fid.variables['elevation']
    152152
    153         volumes = fid.variables['volumes']       
     153        volumes = fid.variables['volumes']
    154154
    155155
     
    164164            assert V[k, 0] == 3*k
    165165            assert V[k, 1] == 3*k+1
    166             assert V[k, 2] == 3*k+2           
    167      
    168      
    169         fid.close()
    170      
     166            assert V[k, 2] == 3*k+2
     167
     168
     169        fid.close()
     170
    171171        #Cleanup
    172172        os.remove(sww.filename)
     
    180180        import time, os
    181181        from Numeric import array, zeros, allclose, Float, concatenate
    182         from Scientific.IO.NetCDF import NetCDFFile       
    183 
    184         self.domain.filename = 'datatest' + str(id(self))       
     182        from Scientific.IO.NetCDF import NetCDFFile
     183
     184        self.domain.filename = 'datatest' + str(id(self))
    185185        self.domain.format = 'sww'
    186186        self.domain.smooth = True
    187      
     187
    188188        sww = get_dataobject(self.domain)
    189         sww.store_connectivity()       
     189        sww.store_connectivity()
    190190
    191191        #Check contents
    192192        #Get NetCDF
    193193        fid = NetCDFFile(sww.filename, 'r')  #Open existing file for append
    194      
     194
    195195        # Get the variables
    196196        x = fid.variables['x']
     
    198198        z = fid.variables['elevation']
    199199
    200         volumes = fid.variables['volumes']       
     200        volumes = fid.variables['volumes']
    201201
    202202        X = x[:]
    203203        Y = y[:]
    204      
     204
    205205        assert allclose([X[0], Y[0]], array([0.0, 0.0]))
    206206        assert allclose([X[1], Y[1]], array([0.0, 0.5]))
     
    209209        assert allclose([X[4], Y[4]], array([0.5, 0.5]))
    210210
    211         assert allclose([X[7], Y[7]], array([1.0, 0.5]))       
     211        assert allclose([X[7], Y[7]], array([1.0, 0.5]))
    212212
    213213        Z = z[:]
     
    221221        assert V[4,0] == 6
    222222        assert V[4,1] == 7
    223         assert V[4,2] == 3                     
    224      
    225 
    226         fid.close()
    227      
     223        assert V[4,2] == 3
     224
     225
     226        fid.close()
     227
    228228        #Cleanup
    229229        os.remove(sww.filename)
     
    237237        import time, os
    238238        from Numeric import array, zeros, allclose, Float, concatenate
    239         from Scientific.IO.NetCDF import NetCDFFile       
     239        from Scientific.IO.NetCDF import NetCDFFile
    240240
    241241        self.domain.filename = 'datatest' + str(id(self))
    242242        self.domain.format = 'sww'
    243243        self.domain.smooth = True
    244         self.domain.reduction = mean             
    245      
     244        self.domain.reduction = mean
     245
    246246        sww = get_dataobject(self.domain)
    247247        sww.store_connectivity()
     
    251251        #Get NetCDF
    252252        fid = NetCDFFile(sww.filename, 'r')  #Open existing file for append
    253      
    254 
    255         # Get the variables
    256         x = fid.variables['x']
    257         y = fid.variables['y']
    258         z = fid.variables['elevation']       
    259         time = fid.variables['time']
    260         stage = fid.variables['stage']
    261      
    262 
    263         Q = self.domain.quantities['stage']     
    264         Q0 = Q.vertex_values[:,0]
    265         Q1 = Q.vertex_values[:,1]
    266         Q2 = Q.vertex_values[:,2]
    267 
    268         A = stage[0,:]
    269         #print A[0], (Q2[0,0] + Q1[1,0])/2
    270         assert allclose(A[0], (Q2[0] + Q1[1])/2) 
    271         assert allclose(A[1], (Q0[1] + Q1[3] + Q2[2])/3)
    272         assert allclose(A[2], Q0[3])
    273         assert allclose(A[3], (Q0[0] + Q1[5] + Q2[4])/3)
    274 
    275         #Center point
    276         assert allclose(A[4], (Q1[0] + Q2[1] + Q0[2] +\
    277                                  Q0[5] + Q2[6] + Q1[7])/6)
    278                                
    279      
    280      
    281         fid.close()
    282      
    283         #Cleanup
    284         os.remove(sww.filename)
    285        
    286        
    287     def test_sww_variable2(self):
    288         """Test that sww information can be written correctly
    289         multiple timesteps. Use average as reduction operator
    290         """
    291 
    292         import time, os
    293         from Numeric import array, zeros, allclose, Float, concatenate
    294         from Scientific.IO.NetCDF import NetCDFFile
    295 
    296         self.domain.filename = 'datatest' + str(id(self))       
    297         self.domain.format = 'sww'
    298         self.domain.smooth = True
    299 
    300         self.domain.reduction = mean     
    301      
    302         sww = get_dataobject(self.domain)
    303         sww.store_connectivity()
    304         sww.store_timestep('stage')     
    305         self.domain.evolve_to_end(finaltime = 0.01)
    306         sww.store_timestep('stage')
    307 
    308 
    309         #Check contents
    310         #Get NetCDF
    311         fid = NetCDFFile(sww.filename, 'r')  #Open existing file for append
     253
    312254
    313255        # Get the variables
     
    316258        z = fid.variables['elevation']
    317259        time = fid.variables['time']
    318         stage = fid.variables['stage']       
    319 
    320         #Check values
    321         Q = self.domain.quantities['stage']     
     260        stage = fid.variables['stage']
     261
     262
     263        Q = self.domain.quantities['stage']
    322264        Q0 = Q.vertex_values[:,0]
    323265        Q1 = Q.vertex_values[:,1]
    324266        Q2 = Q.vertex_values[:,2]
    325267
    326         A = stage[1,:]
    327         assert allclose(A[0], (Q2[0] + Q1[1])/2) 
     268        A = stage[0,:]
     269        #print A[0], (Q2[0,0] + Q1[1,0])/2
     270        assert allclose(A[0], (Q2[0] + Q1[1])/2)
    328271        assert allclose(A[1], (Q0[1] + Q1[3] + Q2[2])/3)
    329272        assert allclose(A[2], Q0[3])
     
    333276        assert allclose(A[4], (Q1[0] + Q2[1] + Q0[2] +\
    334277                                 Q0[5] + Q2[6] + Q1[7])/6)
    335                                
    336      
    337      
    338          
    339      
    340         fid.close()
    341      
     278
     279
     280
     281        fid.close()
     282
    342283        #Cleanup
    343284        os.remove(sww.filename)
    344        
    345     def test_sww_variable3(self):
     285
     286
     287    def test_sww_variable2(self):
    346288        """Test that sww information can be written correctly
    347         multiple timesteps using a different reduction operator (min)
     289        multiple timesteps. Use average as reduction operator
    348290        """
    349291
     
    352294        from Scientific.IO.NetCDF import NetCDFFile
    353295
    354         self.domain.filename = 'datatest' + str(id(self))       
     296        self.domain.filename = 'datatest' + str(id(self))
    355297        self.domain.format = 'sww'
    356298        self.domain.smooth = True
    357         self.domain.reduction = min
    358      
     299
     300        self.domain.reduction = mean
     301
    359302        sww = get_dataobject(self.domain)
    360303        sww.store_connectivity()
    361304        sww.store_timestep('stage')
    362      
    363305        self.domain.evolve_to_end(finaltime = 0.01)
    364306        sww.store_timestep('stage')
    365307
    366308
    367 
    368309        #Check contents
    369310        #Get NetCDF
    370         fid = NetCDFFile(sww.filename, 'r')
    371      
     311        fid = NetCDFFile(sww.filename, 'r')  #Open existing file for append
    372312
    373313        # Get the variables
     
    376316        z = fid.variables['elevation']
    377317        time = fid.variables['time']
    378         stage = fid.variables['stage']       
     318        stage = fid.variables['stage']
    379319
    380320        #Check values
    381         #Check values
    382         Q = self.domain.quantities['stage']     
     321        Q = self.domain.quantities['stage']
    383322        Q0 = Q.vertex_values[:,0]
    384323        Q1 = Q.vertex_values[:,1]
     
    386325
    387326        A = stage[1,:]
    388         assert allclose(A[0], min(Q2[0], Q1[1])) 
     327        assert allclose(A[0], (Q2[0] + Q1[1])/2)
     328        assert allclose(A[1], (Q0[1] + Q1[3] + Q2[2])/3)
     329        assert allclose(A[2], Q0[3])
     330        assert allclose(A[3], (Q0[0] + Q1[5] + Q2[4])/3)
     331
     332        #Center point
     333        assert allclose(A[4], (Q1[0] + Q2[1] + Q0[2] +\
     334                                 Q0[5] + Q2[6] + Q1[7])/6)
     335
     336
     337
     338
     339
     340        fid.close()
     341
     342        #Cleanup
     343        os.remove(sww.filename)
     344
     345    def test_sww_variable3(self):
     346        """Test that sww information can be written correctly
     347        multiple timesteps using a different reduction operator (min)
     348        """
     349
     350        import time, os
     351        from Numeric import array, zeros, allclose, Float, concatenate
     352        from Scientific.IO.NetCDF import NetCDFFile
     353
     354        self.domain.filename = 'datatest' + str(id(self))
     355        self.domain.format = 'sww'
     356        self.domain.smooth = True
     357        self.domain.reduction = min
     358
     359        sww = get_dataobject(self.domain)
     360        sww.store_connectivity()
     361        sww.store_timestep('stage')
     362
     363        self.domain.evolve_to_end(finaltime = 0.01)
     364        sww.store_timestep('stage')
     365
     366
     367
     368        #Check contents
     369        #Get NetCDF
     370        fid = NetCDFFile(sww.filename, 'r')
     371
     372
     373        # Get the variables
     374        x = fid.variables['x']
     375        y = fid.variables['y']
     376        z = fid.variables['elevation']
     377        time = fid.variables['time']
     378        stage = fid.variables['stage']
     379
     380        #Check values
     381        #Check values
     382        Q = self.domain.quantities['stage']
     383        Q0 = Q.vertex_values[:,0]
     384        Q1 = Q.vertex_values[:,1]
     385        Q2 = Q.vertex_values[:,2]
     386
     387        A = stage[1,:]
     388        assert allclose(A[0], min(Q2[0], Q1[1]))
    389389        assert allclose(A[1], min(Q0[1], Q1[3], Q2[2]))
    390390        assert allclose(A[2], Q0[3])
     
    394394        assert allclose(A[4], min(Q1[0], Q2[1], Q0[2],\
    395395                                  Q0[5], Q2[6], Q1[7]))
    396                                
    397      
    398         fid.close()
    399      
     396
     397
     398        fid.close()
     399
    400400        #Cleanup
    401401        os.remove(sww.filename)
     
    408408        import time, os, config
    409409        from Numeric import array, zeros, allclose, Float, concatenate
    410         from Scientific.IO.NetCDF import NetCDFFile       
     410        from Scientific.IO.NetCDF import NetCDFFile
    411411
    412412        self.domain.filename = 'synctest'
     
    426426            if t == 0.0:
    427427                assert allclose(stage, self.initial_stage)
    428                 assert allclose(stage_file[:], stage.flat) 
     428                assert allclose(stage_file[:], stage.flat)
    429429            else:
    430430                assert not allclose(stage, self.initial_stage)
    431                 assert not allclose(stage_file[:], stage.flat)                 
     431                assert not allclose(stage_file[:], stage.flat)
    432432
    433433            fid.close()
     
    442442        import time, os
    443443        from Numeric import array, zeros, allclose, Float, concatenate
    444         from Scientific.IO.NetCDF import NetCDFFile       
    445 
    446         self.domain.filename = 'datatest' + str(id(self))               
     444        from Scientific.IO.NetCDF import NetCDFFile
     445
     446        self.domain.filename = 'datatest' + str(id(self))
    447447        self.domain.format = 'sww'
    448448        self.domain.smooth = True
    449         self.domain.reduction = mean             
    450      
     449        self.domain.reduction = mean
     450
    451451        sww = get_dataobject(self.domain)
    452452        sww.store_connectivity()
     
    455455        #Check contents
    456456        #Get NetCDF
    457         fid = NetCDFFile(sww.filename, 'r') 
    458      
     457        fid = NetCDFFile(sww.filename, 'r')
     458
    459459        # Get the variables
    460460        x = fid.variables['x']
     
    462462        z = fid.variables['elevation']
    463463
    464         volumes = fid.variables['volumes']   
     464        volumes = fid.variables['volumes']
    465465        time = fid.variables['time']
    466466
    467         # 2D 
    468         stage = fid.variables['stage']       
     467        # 2D
     468        stage = fid.variables['stage']
    469469
    470470        X = x[:]
     
    474474        T = time[:]
    475475        S = stage[:,:]
    476      
     476
    477477#         print "****************************"
    478478#         print "X ",X
     
    489489#         print "****************************"
    490490
    491        
    492         fid.close()
    493      
     491
     492        fid.close()
     493
    494494        #Cleanup
    495495        os.remove(sww.filename)
     
    522522        ref_elevation = []
    523523        for i in range(6):
    524             y = (6-i)*25.0           
     524            y = (6-i)*25.0
    525525            for j in range(5):
    526526                x = j*25.0
     
    530530                ref_elevation.append(z)
    531531                fid.write('%f ' %z)
    532             fid.write('\n')   
     532            fid.write('\n')
    533533
    534534        fid.close()
     
    550550""")
    551551        fid.close()
    552        
     552
    553553        #Convert to NetCDF xya
    554554        convert_dem_from_ascii2netcdf(root)
     
    558558        #Get NetCDF
    559559        fid = NetCDFFile(root+'.pts', 'r')
    560      
     560
    561561        # Get the variables
    562562        #print fid.variables.keys()
     
    572572        #print attributes[:]
    573573        #print ref_elevation
    574         assert allclose(elevation, ref_elevation)       
    575      
    576         #Cleanup
    577         fid.close()
    578        
     574        assert allclose(elevation, ref_elevation)
     575
     576        #Cleanup
     577        fid.close()
     578
    579579
    580580        os.remove(root + '.pts')
    581         os.remove(root + '.dem')               
    582         os.remove(root + '.asc')       
    583         os.remove(root + '.prj')               
     581        os.remove(root + '.dem')
     582        os.remove(root + '.asc')
     583        os.remove(root + '.prj')
    584584
    585585
     
    590590        from Scientific.IO.NetCDF import NetCDFFile
    591591
    592         #The test file has 
     592        #The test file has
    593593        # LON = 150.66667, 150.83334, 151, 151.16667
    594594        # LAT = -34.5, -34.33333, -34.16667, -34 ;
     
    597597        # First value (index=0) in small_ha.nc is 0.3400644 cm,
    598598        # Fourth value (index==3) is -6.50198 cm
    599        
     599
    600600
    601601        from coordinate_transforms.redfearn import redfearn
     
    605605        first_value = fid.variables['HA'][:][0,0,0]
    606606        fourth_value = fid.variables['HA'][:][0,0,3]
    607        
     607
    608608        #Call conversion (with zero origin)
    609609        ferret2sww('small', verbose=False,
    610610                   origin = (56, 0, 0))
    611  
     611
    612612
    613613        #Work out the UTM coordinates for first point
    614614        zone, e, n = redfearn(-34.5, 150.66667)
    615615        #print zone, e, n
    616        
     616
    617617        #Read output file 'small.sww'
    618618        fid = NetCDFFile('small.sww')
    619619
    620620        x = fid.variables['x'][:]
    621         y = fid.variables['y'][:]       
     621        y = fid.variables['y'][:]
    622622
    623623        #Check that first coordinate is correctly represented
     
    631631
    632632        #Check fourth value
    633         assert allclose(stage[0,3], fourth_value/100)  #Meters       
     633        assert allclose(stage[0,3], fourth_value/100)  #Meters
    634634
    635635        fid.close()
     
    639639        os.remove('small.sww')
    640640
    641        
     641
    642642
    643643    def test_ferret2sww_2(self):
     
    647647        from Scientific.IO.NetCDF import NetCDFFile
    648648
    649         #The test file has 
     649        #The test file has
    650650        # LON = 150.66667, 150.83334, 151, 151.16667
    651651        # LAT = -34.5, -34.33333, -34.16667, -34 ;
     
    654654        # First value (index=0) in small_ha.nc is 0.3400644 cm,
    655655        # Fourth value (index==3) is -6.50198 cm
    656        
     656
    657657
    658658        from coordinate_transforms.redfearn import redfearn
     
    665665        lat_index = 0
    666666        lon_index = 2
    667        
     667
    668668        test_value = fid.variables['HA'][:][time_index, lat_index, lon_index]
    669669        test_time = fid.variables['TIME'][:][time_index]
    670670        test_lat = fid.variables['LAT'][:][lat_index]
    671         test_lon = fid.variables['LON'][:][lon_index]       
    672        
    673         linear_point_index = lat_index*4 + lon_index 
    674         fid.close()
    675        
     671        test_lon = fid.variables['LON'][:][lon_index]
     672
     673        linear_point_index = lat_index*4 + lon_index
     674        fid.close()
     675
    676676        #Call conversion (with zero origin)
    677677        ferret2sww('small', verbose=False,
    678678                   origin = (56, 0, 0))
    679  
     679
    680680
    681681        #Work out the UTM coordinates for test point
    682682        zone, e, n = redfearn(test_lat, test_lon)
    683        
     683
    684684        #Read output file 'small.sww'
    685685        fid = NetCDFFile('small.sww')
    686686
    687687        x = fid.variables['x'][:]
    688         y = fid.variables['y'][:]       
     688        y = fid.variables['y'][:]
    689689
    690690        #Check that test coordinate is correctly represented
     
    705705
    706706
    707        
     707
    708708    def test_sww_extent(self):
    709709        """Not a test, rather a look at the sww format
     
    712712        import time, os
    713713        from Numeric import array, zeros, allclose, Float, concatenate
    714         from Scientific.IO.NetCDF import NetCDFFile       
    715 
    716         self.domain.filename = 'datatest' + str(id(self))                       
     714        from Scientific.IO.NetCDF import NetCDFFile
     715
     716        self.domain.filename = 'datatest' + str(id(self))
    717717        self.domain.format = 'sww'
    718718        self.domain.smooth = True
    719         self.domain.reduction = mean 
     719        self.domain.reduction = mean
    720720        self.domain.set_datadir('.')
    721721
    722      
     722
    723723        sww = get_dataobject(self.domain)
    724724        sww.store_connectivity()
     
    736736        [xmin, xmax, ymin, ymax, stagemin, stagemax] = \
    737737               extent_sww(file_and_extension_name )
    738        
    739         assert allclose(xmin, 0.0) 
    740         assert allclose(xmax, 1.0) 
    741         assert allclose(ymin, 0.0) 
     738
     739        assert allclose(xmin, 0.0)
     740        assert allclose(xmax, 1.0)
     741        assert allclose(ymin, 0.0)
    742742        assert allclose(ymax, 1.0)
    743         assert allclose(stagemin, -0.85) 
     743        assert allclose(stagemin, -0.85)
    744744        assert allclose(stagemax, 0.15)
    745745
     
    747747        #Cleanup
    748748        os.remove(sww.filename)
    749        
    750        
     749
     750
    751751    def test_ferret2sww_nz_origin(self):
    752752        from Scientific.IO.NetCDF import NetCDFFile
    753         from coordinate_transforms.redfearn import redfearn       
     753        from coordinate_transforms.redfearn import redfearn
    754754
    755755        #Call conversion (with nonzero origin)
     
    765765
    766766        x = fid.variables['x'][:]
    767         y = fid.variables['y'][:]       
     767        y = fid.variables['y'][:]
    768768
    769769        #Check that first coordinate is correctly represented
     
    777777        os.remove('small.sww')
    778778
    779        
     779
    780780#-------------------------------------------------------------
    781781if __name__ == "__main__":
    782     suite = unittest.makeSuite(dataTestCase,'test')
     782    suite = unittest.makeSuite(Test_Data_Manager,'test')
    783783    runner = unittest.TextTestRunner()
    784784    runner.run(suite)
  • inundation/ga/storm_surge/pyvolution/test_domain.py

    r773 r1018  
    1818        #print 'bottom - indexes',elements
    1919        domain.set_quantity('friction', 0.09, indexes = elements)
    20  
     20
    2121def set_top_friction(tag, elements, domain):
    2222    if tag == "top":
    2323        #print 'top - indexes',elements
    2424        domain.set_quantity('friction', 1., indexes = elements)
    25        
    26  
     25
     26
    2727def set_all_friction(tag, elements, domain):
    2828    if tag == "all":
    2929        new_values = domain.get_quantity('friction', indexes = elements) + 10.0
    30        
     30
    3131        domain.set_quantity('friction', new_values, indexes = elements)
    32                  
    33      
    34 class TestCase(unittest.TestCase):
     32
     33
     34class Test_Domain(unittest.TestCase):
    3535    def setUp(self):
    3636        pass
    3737
    38        
     38
    3939    def tearDown(self):
    4040        pass
    4141
    42            
     42
    4343    def test_simple(self):
    4444        a = [0.0, 0.0]
     
    5050
    5151        points = [a, b, c, d, e, f]
    52         #bac, bce, ecf, dbe, daf, dae 
     52        #bac, bce, ecf, dbe, daf, dae
    5353        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4], [3,0,5], [3,0,4]]
    5454
    5555        conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
    5656        other_quantities = ['elevation', 'friction']
    57        
     57
    5858        domain = Domain(points, vertices, None,
    59                         conserved_quantities, other_quantities)       
     59                        conserved_quantities, other_quantities)
    6060        domain.check_integrity()
    6161
     
    6464
    6565
    66         assert domain.get_conserved_quantities(0, edge=1) == 0.   
     66        assert domain.get_conserved_quantities(0, edge=1) == 0.
    6767
    6868
    6969    def test_conserved_quantities(self):
    70        
    71         a = [0.0, 0.0]
    72         b = [0.0, 2.0]
    73         c = [2.0,0.0]
    74         d = [0.0, 4.0]
    75         e = [2.0, 2.0]
    76         f = [4.0,0.0]
    77 
    78         points = [a, b, c, d, e, f]
    79         #bac, bce, ecf, dbe, daf, dae 
     70
     71        a = [0.0, 0.0]
     72        b = [0.0, 2.0]
     73        c = [2.0,0.0]
     74        d = [0.0, 4.0]
     75        e = [2.0, 2.0]
     76        f = [4.0,0.0]
     77
     78        points = [a, b, c, d, e, f]
     79        #bac, bce, ecf, dbe, daf, dae
    8080        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4], [3,0,5], [3,0,4]]
    8181
     
    8787        domain.set_quantity('stage', [[1,2,3], [5,5,5],
    8888                                      [0,0,9], [-6, 3, 3],
    89                                       [0,0,0], [0,0,0]])       
     89                                      [0,0,0], [0,0,0]])
    9090
    9191        domain.set_quantity('xmomentum', [[1,2,3], [5,5,5],
    9292                                          [0,0,9], [-6, 3, 3],
    93                                           [0,0,0], [0,0,0]])       
     93                                          [0,0,0], [0,0,0]])
    9494
    9595        domain.check_integrity()
     
    100100
    101101        q = domain.get_conserved_quantities(1)
    102         assert allclose(q, [5., 5., 0.])         
     102        assert allclose(q, [5., 5., 0.])
    103103
    104104        q = domain.get_conserved_quantities(2)
     
    106106
    107107        q = domain.get_conserved_quantities(3)
    108         assert allclose(q, [0., 0., 0.])                         
    109        
     108        assert allclose(q, [0., 0., 0.])
     109
    110110
    111111        #Edges
     
    135135        assert allclose(q, [-1.5, -1.5, 0.])
    136136        q = domain.get_conserved_quantities(3, edge=2)
    137         assert allclose(q, [-1.5, -1.5, 0.])                   
     137        assert allclose(q, [-1.5, -1.5, 0.])
    138138
    139139
     
    142142        from config import default_boundary_tag
    143143
    144        
     144
    145145        a = [0.0, 0.5]
    146         b = [0.0, 0.0]               
     146        b = [0.0, 0.0]
    147147        c = [0.5, 0.5]
    148148
     
    153153        domain.set_boundary( {default_boundary_tag: Dirichlet_boundary([5,2,1])} )
    154154
    155        
    156         domain.check_integrity()
    157 
    158         assert allclose(domain.neighbours, [[-1,-2,-3]])       
    159                
     155
     156        domain.check_integrity()
     157
     158        assert allclose(domain.neighbours, [[-1,-2,-3]])
     159
    160160
    161161
    162162    def test_boundary_conditions(self):
    163        
     163
    164164        a = [0.0, 0.0]
    165165        b = [0.0, 2.0]
     
    177177                     (2, 1): 'Second',
    178178                     (3, 1): 'Second',
    179                      (3, 2): 'Second'}                                         
    180                      
     179                     (3, 2): 'Second'}
     180
    181181
    182182        domain = Domain(points, vertices, boundary,
    183183                        conserved_quantities =\
    184                         ['stage', 'xmomentum', 'ymomentum'])       
     184                        ['stage', 'xmomentum', 'ymomentum'])
    185185        domain.check_integrity()
    186186
     
    205205               domain.get_conserved_quantities(3, edge=1)[0] #Transmissive (-1.5)
    206206        assert domain.quantities['stage'].boundary_values[5] ==\
    207                domain.get_conserved_quantities(3, edge=2)[0] #Transmissive (-1.5)         
     207               domain.get_conserved_quantities(3, edge=2)[0] #Transmissive (-1.5)
    208208
    209209        #Check enumeration
     
    217217        """Domain implements a default first order gradient limiter
    218218        """
    219        
     219
    220220        a = [0.0, 0.0]
    221221        b = [0.0, 2.0]
     
    233233                     (2, 1): 'Second',
    234234                     (3, 1): 'Second',
    235                      (3, 2): 'Third'}                                         
    236                      
     235                     (3, 2): 'Third'}
     236
    237237
    238238        domain = Domain(points, vertices, boundary,
    239239                        conserved_quantities =\
    240                         ['stage', 'xmomentum', 'ymomentum'])               
     240                        ['stage', 'xmomentum', 'ymomentum'])
    241241        domain.check_integrity()
    242242
     
    247247        assert allclose( domain.quantities['stage'].centroid_values,
    248248                         [2,5,3,0] )
    249                          
     249
    250250        domain.set_quantity('xmomentum', [[1,1,1], [2,2,2],
    251251                                          [3,3,3], [4, 4, 4]])
    252252
    253253        domain.set_quantity('ymomentum', [[10,10,10], [20,20,20],
    254                                           [30,30,30], [40, 40, 40]])       
     254                                          [30,30,30], [40, 40, 40]])
    255255
    256256
     
    283283                     (2, 1): 'Second',
    284284                     (3, 1): 'Second',
    285                      (3, 2): 'Third'}                                         
    286                      
     285                     (3, 2): 'Third'}
     286
    287287
    288288        domain = Domain(points, vertices, boundary,
    289289                        conserved_quantities =\
    290                         ['stage', 'xmomentum', 'ymomentum'])               
     290                        ['stage', 'xmomentum', 'ymomentum'])
    291291        domain.check_integrity()
    292292
     
    295295        domain.set_quantity('xmomentum', [1,2,3,4], 'centroids')
    296296        domain.set_quantity('ymomentum', [1,2,3,4], 'centroids')
    297                                          
     297
    298298
    299299        #Assign some values to update vectors
     
    303303            domain.quantities[name].explicit_update = array([4.,3.,2.,1.])
    304304            domain.quantities[name].semi_implicit_update = array([1.,1.,1.,1.])
    305            
     305
    306306
    307307        #Update with given timestep (assuming no other forcing terms)
     
    316316
    317317        for name in domain.conserved_quantities:
    318             assert allclose(domain.quantities[name].centroid_values, x)   
     318            assert allclose(domain.quantities[name].centroid_values, x)
    319319
    320320
     
    322322        """Set quantities for sub region
    323323        """
    324        
     324
    325325        a = [0.0, 0.0]
    326326        b = [0.0, 2.0]
     
    338338                     (2, 1): 'Second',
    339339                     (3, 1): 'Second',
    340                      (3, 2): 'Third'}             
     340                     (3, 2): 'Third'}
    341341
    342342        domain = Domain(points, vertices, boundary,
    343343                        conserved_quantities =\
    344                         ['stage', 'xmomentum', 'ymomentum'])               
     344                        ['stage', 'xmomentum', 'ymomentum'])
    345345        domain.check_integrity()
    346346
     
    350350        assert allclose( domain.quantities['stage'].centroid_values,
    351351                         [2,5,3,0] )
    352                          
     352
    353353        domain.set_quantity('xmomentum', [[1,1,1], [2,2,2],
    354354                                          [3,3,3], [4, 4, 4]])
    355355
    356356        domain.set_quantity('ymomentum', [[10,10,10], [20,20,20],
    357                                           [30,30,30], [40, 40, 40]])       
     357                                          [30,30,30], [40, 40, 40]])
    358358
    359359
     
    369369        domain.build_tagged_elements_dictionary({'mound':[0,1]})
    370370        domain.set_region([add_to_verts])
    371        
     371
    372372        self.failUnless(domain.test == "Mound",
    373373                        'set region failed')
    374        
     374
    375375
    376376
     
    382382        from shallow_water import Domain
    383383        from Numeric import zeros, Float
    384        
     384
    385385        #Create basic mesh
    386386        points, vertices, boundary = rectangular(1, 3)
     
    392392                                                 'all':[0,1,2,3,4,5]})
    393393
    394        
     394
    395395        #Set friction
    396396        manning = 0.07
     
    406406                         [ 1.0,  1.0,  1.0],
    407407                         [ 1.0,  1.0,  1.0]])
    408        
     408
    409409        domain.set_region([set_all_friction])
    410410        #print domain.quantities['friction'].get_values()
     
    416416                         [ 11.0,  11.0,  11.0],
    417417                         [ 11.0,  11.0,  11.0]])
     418
     419
    418420#-------------------------------------------------------------
    419421if __name__ == "__main__":
    420     suite = unittest.makeSuite(TestCase,'test')
     422    suite = unittest.makeSuite(Test_Domain,'test')
    421423    runner = unittest.TextTestRunner()
    422424    runner.run(suite)
  • inundation/ga/storm_surge/pyvolution/test_general_mesh.py

    r1011 r1018  
    99from Numeric import allclose, array, ones, Float
    1010
    11        
    12 class TestCase(unittest.TestCase):
     11
     12class Test_General_Mesh(unittest.TestCase):
    1313    def setUp(self):
    1414        pass
    15        
     15
    1616    def tearDown(self):
    1717        pass
     
    2424        from shallow_water import Domain
    2525        from Numeric import zeros, Float
    26        
     26
    2727        #Create basic mesh
    2828        points, vertices, boundary = rectangular(1, 3)
    2929        domain = Domain(points, vertices, boundary)
    30        
     30
    3131        value = [7]
    3232        indexes = [1]
    33         assert  domain.get_vertices() == domain.triangles 
     33        assert  domain.get_vertices() == domain.triangles
    3434        assert domain.get_vertices([0,4]) == [domain.triangles[0],
    3535                                              domain.triangles[4]]
     
    3838        from shallow_water import Domain
    3939        from Numeric import zeros, Float
    40        
     40
    4141        #Create basic mesh
    4242        points, vertices, boundary = rectangular(1, 3)
    4343        domain = Domain(points, vertices, boundary)
    4444
    45         assert domain.get_area() == 1.0         
     45        assert domain.get_area() == 1.0
    4646
    4747
     
    5353        from shallow_water import Domain
    5454        from Numeric import zeros, Float
    55        
     55
    5656        #Create basic mesh
    5757        points, vertices, boundary = rectangular(1, 3)
    5858        domain = Domain(points, vertices, boundary)
    59        
     59
    6060        assert  domain.get_unique_vertices() == [0,1,2,3,4,5,6,7]
    6161        unique_vertices = domain.get_unique_vertices([0,1,4])
    6262        unique_vertices.sort()
    6363        assert unique_vertices == [0,1,2,4,5,6,7]
    64        
     64
    6565        unique_vertices = domain.get_unique_vertices([0,4])
    6666        unique_vertices.sort()
    6767        assert unique_vertices == [0,2,4,5,6,7]
    68        
     68
    6969#-------------------------------------------------------------
    7070if __name__ == "__main__":
    71     suite = unittest.makeSuite(TestCase,'test')
     71    suite = unittest.makeSuite(Test_General_Mesh,'test')
    7272    runner = unittest.TextTestRunner()
    7373    runner.run(suite)
    7474
    75 
  • inundation/ga/storm_surge/pyvolution/test_generic_boundary_conditions.py

    r850 r1018  
    88from Numeric import allclose, array
    99
    10        
    11 class TestCase(unittest.TestCase):
     10
     11class Test_Generic_Boundary_Conditions(unittest.TestCase):
    1212    def setUp(self):
    1313        pass
    1414        #print "  Setting up"
    15        
     15
    1616    def tearDown(self):
    1717        pass
     
    2828        else:
    2929            raise 'Should have raised exception'
    30        
     30
    3131
    3232    def test_dirichlet_empty(self):
     
    5050        from domain import Domain
    5151        from quantity import Quantity
    52        
     52
    5353        a = [0.0, 0.0]
    5454        b = [0.0, 2.0]
     
    6262        #bac, bce, ecf, dbe
    6363        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
    64        
     64
    6565        domain = Domain(points, elements)
    6666        domain.check_integrity()
    6767
    68         domain.conserved_quantities = ['stage', 'ymomentum']       
     68        domain.conserved_quantities = ['stage', 'ymomentum']
    6969        domain.quantities['stage'] =\
    7070                                   Quantity(domain, [[1,2,3], [5,5,5],
     
    110110        from math import sin, pi
    111111        from config import time_format
    112        
     112
    113113        a = [0.0, 0.0]
    114114        b = [0.0, 2.0]
     
    122122        #bac, bce, ecf, dbe
    123123        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
    124        
     124
    125125        domain = Domain(points, elements)
    126126        domain.conserved_quantities = ['stage', 'ymomentum']
     
    134134
    135135        domain.check_integrity()
    136        
     136
    137137
    138138        #Write file
     
    145145            t_string = time.strftime(time_format, time.gmtime(t))
    146146
    147             fid.write('%s,%f %f\n' %(t_string, 1.0*i, sin(i*2*pi/10))) 
     147            fid.write('%s,%f %f\n' %(t_string, 1.0*i, sin(i*2*pi/10)))
    148148        fid.close()
    149                      
    150        
     149
     150
    151151        F = File_boundary(filename, domain)
    152152        os.remove(filename)
    153        
     153
    154154
    155155        #Check that midpoint coordinates at boundary are correctly computed
    156         assert allclose( F.midpoint_coordinates, 
    157                          [[0.0, 3.0], [1.0, 3.0], [0.0, 1.0], 
     156        assert allclose( F.midpoint_coordinates,
     157                         [[0.0, 3.0], [1.0, 3.0], [0.0, 1.0],
    158158                         [1.0, 0.0], [3.0, 0.0], [3.0, 1.0]])
    159        
     159
    160160        #assert allclose(F.midpoint_coordinates[(3,2)], [0.0, 3.0])
    161161        #assert allclose(F.midpoint_coordinates[(3,1)], [1.0, 3.0])
     
    163163        #assert allclose(F.midpoint_coordinates[(0,0)], [1.0, 0.0])
    164164        #assert allclose(F.midpoint_coordinates[(2,0)], [3.0, 0.0])
    165         #assert allclose(F.midpoint_coordinates[(2,1)], [3.0, 1.0])         
     165        #assert allclose(F.midpoint_coordinates[(2,1)], [3.0, 1.0])
    166166
    167167
     
    177177        domain.time = 2.5*5*60  #Half way between steps 2 and 3
    178178        q = F.evaluate()
    179         assert allclose(q, [2.5, (sin(2*2*pi/10) + sin(3*2*pi/10))/2])       
     179        assert allclose(q, [2.5, (sin(2*2*pi/10) + sin(3*2*pi/10))/2])
    180180
    181181
     
    191191        from math import sin, pi
    192192        from config import time_format
    193        
     193
    194194        a = [0.0, 0.0]
    195195        b = [0.0, 2.0]
     
    203203        #bac, bce, ecf, dbe
    204204        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
    205        
     205
    206206        domain = Domain(points, elements)
    207207        domain.conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
     
    228228            t_string = time.strftime(time_format, time.gmtime(t))
    229229
    230             fid.write('%s,%f %f\n' %(t_string, 1.0*i, sin(i*2*pi/10))) 
     230            fid.write('%s,%f %f\n' %(t_string, 1.0*i, sin(i*2*pi/10)))
    231231        fid.close()
    232                      
     232
    233233
    234234        try:
     
    242242
    243243
    244        
     244
    245245#-------------------------------------------------------------
    246246if __name__ == "__main__":
    247     suite = unittest.makeSuite(TestCase,'test')
     247    suite = unittest.makeSuite(Test_Generic_Boundary_Conditions,'test')
    248248    runner = unittest.TextTestRunner()
    249249    runner.run(suite)
    250250
    251251
    252        
     252
  • inundation/ga/storm_surge/pyvolution/test_interpolate_sww.py

    r907 r1018  
    1616
    1717
    18 class dataTestCase(unittest.TestCase):
     18class Test_Interpolate_sww(unittest.TestCase):
    1919    def setUp(self):
    2020        import time
     
    3030        domain.beta_h = 0
    3131
    32        
     32
    3333        #Set some field values
    34         domain.set_quantity('elevation', lambda x,y: -x)       
     34        domain.set_quantity('elevation', lambda x,y: -x)
    3535        domain.set_quantity('friction', 0.03)
    3636
    3737
    38         ###################### 
     38        ######################
    3939        # Boundary conditions
    4040        B = Transmissive_boundary(domain)
    4141        domain.set_boundary( {'left': B, 'right': B, 'top': B, 'bottom': B})
    42        
    43 
    44         ###################### 
     42
     43
     44        ######################
    4545        #Initial condition - with jumps
    4646
     
    5050        h = 0.3
    5151        for i in range(stage.shape[0]):
    52             if i % 2 == 0:           
     52            if i % 2 == 0:
    5353                stage[i,:] = bed[i,:] + h
    5454            else:
    5555                stage[i,:] = bed[i,:]
    56                
     56
    5757        domain.set_quantity('stage', stage)
    5858
    59         domain.distribute_to_vertices_and_edges()   
     59        domain.distribute_to_vertices_and_edges()
    6060
    6161
     
    6565        self.X = C[:,0:6:2].copy()
    6666        self.Y = C[:,1:6:2].copy()
    67        
     67
    6868        self.F = bed
    6969
    70        
     70
    7171    def tearDown(self):
    7272        pass
     
    7878        import time, os
    7979        from Numeric import array, zeros, allclose, Float, concatenate
    80         from Scientific.IO.NetCDF import NetCDFFile       
     80        from Scientific.IO.NetCDF import NetCDFFile
    8181
    8282        self.domain.filename = 'datatest' + str(time.time())
    8383        self.domain.format = 'sww'
    8484        self.domain.smooth = True
    85         self.domain.reduction = mean             
    86      
     85        self.domain.reduction = mean
     86
    8787        sww = get_dataobject(self.domain)
    8888        sww.store_connectivity()
    8989        sww.store_timestep('stage')
    90         self.domain.time = 2. 
     90        self.domain.time = 2.
    9191        sww.store_timestep('stage')
    9292
    9393        #Check contents
    9494        #Get NetCDF
    95         fid = NetCDFFile(sww.filename, 'r') 
    96      
     95        fid = NetCDFFile(sww.filename, 'r')
     96
    9797        # Get the variables
    9898        x = fid.variables['x']
     
    100100        z = fid.variables['elevation']
    101101
    102         volumes = fid.variables['volumes']   
     102        volumes = fid.variables['volumes']
    103103        time = fid.variables['time']
    104104
    105         # 2D 
    106         stage = fid.variables['stage']       
     105        # 2D
     106        stage = fid.variables['stage']
    107107
    108108        X = x[:]
     
    127127            print "Stage ",S
    128128            print "****************************"
    129            
    130 
    131        
    132        
     129
     130
     131
     132
    133133        fid.close()
    134      
     134
    135135        #Cleanup
    136136        os.remove(sww.filename)
    137  
     137
    138138    def test_interpolate_sww(self):
    139         """Not reaa unit test, rather a system test for 
     139        """Not reaa unit test, rather a system test for
    140140        """
    141141
     
    143143        from Numeric import array, zeros, allclose, Float, concatenate, \
    144144             transpose
    145         from Scientific.IO.NetCDF import NetCDFFile   
     145        from Scientific.IO.NetCDF import NetCDFFile
    146146        import tempfile
    147147        from load_mesh.loadASCII import  load_points_file, \
     
    151151        self.domain.format = 'sww'
    152152        self.domain.smooth = True
    153         self.domain.reduction = mean             
    154      
     153        self.domain.reduction = mean
     154
    155155        sww = get_dataobject(self.domain)
    156156        sww.store_connectivity()
    157157        sww.store_timestep('stage')
    158         self.domain.time = 2. 
     158        self.domain.time = 2.
    159159        sww.store_timestep('stage')
    160160
    161161        #print "self.domain.filename",self.domain.filename
    162162        interp = Interpolate_sww(sww.filename, 'depth')
    163        
     163
    164164        assert allclose(interp.time,[0.0,2.0])
    165165
     
    186186        point_file_out = tempfile.mktemp(".xya")
    187187        interp.write_depth_xya(point_file_out)
    188        
     188
    189189        #check the output file
    190190        xya_dict = load_points_file(point_file_out)
    191191        #print "xya_dict", xya_dict
    192         title_list,point_attributes = concatinate_attributelist(xya_dict['attributelist']) 
     192        title_list,point_attributes = concatinate_attributelist(xya_dict['attributelist'])
    193193        assert allclose(interp.point_coordinates, xya_dict['pointlist'])
    194194        assert allclose(interp.interpolated_quantity,
     
    201201        #time_list = []
    202202
    203         # Try another quantity     
     203        # Try another quantity
    204204        interp = Interpolate_sww(sww.filename, 'stage')
    205205        interp.interpolate_xya(point_file)
     
    209209        assert allclose(interp.interpolated_quantity,answer)
    210210
    211        
     211
    212212        # look at error catching
    213213        try:
     
    218218            self.failUnless(0==1,
    219219                        'bad key did not raise an error!')
    220        
     220
    221221        # look at error catching
    222222        try:
     
    227227            self.failUnless(0==1,
    228228                        'bad key did not raise an error!')
    229                
     229
    230230        #Cleanup
    231231        os.remove(sww.filename)
    232232        os.remove(point_file_out)
    233233        os.remove(point_file)
    234  
     234
    235235#-------------------------------------------------------------
    236236if __name__ == "__main__":
    237     suite = unittest.makeSuite(dataTestCase,'test')
     237    suite = unittest.makeSuite(Test_Interpolate_sww,'test')
    238238    runner = unittest.TextTestRunner()
    239239    runner.run(suite)
  • inundation/ga/storm_surge/pyvolution/test_least_squares.py

    r1003 r1018  
    1111
    1212def distance(x, y):
    13     return sqrt( sum( (array(x)-array(y))**2 ))         
     13    return sqrt( sum( (array(x)-array(y))**2 ))
    1414
    1515def linear_function(point):
    1616    point = array(point)
    1717    return point[:,0]+point[:,1]
    18    
    19        
    20 class TestCase(unittest.TestCase):
     18
     19
     20class Test_Least_Squares(unittest.TestCase):
    2121
    2222    def setUp(self):
    2323        pass
    24        
     24
    2525    def tearDown(self):
    2626        pass
     
    3333        vertices = [ [1,0,2] ]   #bac
    3434
    35         data = [ [2.0/3, 2.0/3] ] #Use centroid as one data point       
    36        
     35        data = [ [2.0/3, 2.0/3] ] #Use centroid as one data point
     36
    3737        interp = Interpolation(points, vertices, data)
    38         assert allclose(interp.get_A(), [[1./3, 1./3, 1./3]]) 
    39        
     38        assert allclose(interp.get_A(), [[1./3, 1./3, 1./3]])
     39
    4040
    4141    def test_quad_tree(self):
     
    5050        p8 = [-66.0, 20.0]
    5151        p9 = [10.0, -66.0]
    52        
     52
    5353        points = [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9]
    5454        triangles = [ [0, 1, 2],
     
    6060                      [7, 4, 5],
    6161                      [8, 0, 2],
    62                       [0, 9, 1]]   
    63 
    64         data = [ [4,4] ] 
     62                      [0, 9, 1]]
     63
     64        data = [ [4,4] ]
    6565        interp = Interpolation(points, triangles, data, alpha = 0.0,
    6666                               max_points_per_cell = 4)
     
    7575        assert allclose(interp.get_A(), answer)
    7676
    77        
     77
    7878        #point outside of quad tree root cell
    7979        interp.set_point_coordinates([[-70, -70]])
     
    8282                      0., 0. , 0., 0., 0., 0.]]
    8383        assert allclose(interp.get_A(), answer)
    84      
     84
    8585    def test_expand_search(self):
    8686        p0 = [-10.0, -10.0]
     
    9494        p8 = [-66.0, 20.0]
    9595        p9 = [10.0, -66.0]
    96        
     96
    9797        points = [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9]
    9898        triangles = [ [0, 1, 2],
     
    104104                      [7, 4, 5],
    105105                      [8, 0, 2],
    106                       [0, 9, 1]]   
     106                      [0, 9, 1]]
    107107
    108108        data = [ [4,4],
     
    134134                 [50,50],
    135135                 [30,0],
    136                  [-20,-20]] 
     136                 [-20,-20]]
    137137        point_attributes = [ -400000,
    138138                     10,
     
    163163                     10,
    164164                   10,
    165                    99] 
    166        
     165                   99]
     166
    167167        interp = Interpolation(points, triangles, data,
    168168                               alpha=0.0, expand_search=False, #verbose = True, #False,
     
    170170        calc = interp.fit_points(point_attributes, )
    171171        #print "calc",calc
    172        
     172
    173173        # the point at 4,4 is ignored.  An expanded search has to be done
    174174        # to fine which triangel it's in.
     
    194194        p4 = [10.0, 60.0]
    195195        p5 = [60.0, 60.0]
    196        
     196
    197197        points = [p0, p1, p2, p3, p4, p5]
    198198        triangles = [ [0, 1, 2],
     
    201201                      [0, 2, 4],
    202202                      [4, 2, 5],
    203                       [5, 2, 3]]   
     203                      [5, 2, 3]]
    204204
    205205        data = [ [-26.0,-26.0] ]
     
    216216        assert allclose(interp.get_A(), answer)
    217217
    218        
     218
    219219        #point outside of quad tree root cell
    220220        interp.set_point_coordinates([[-70, -70]])
     
    223223                      0., 0. ]]
    224224        assert allclose(interp.get_A(), answer)
    225            
     225
    226226
    227227    def test_datapoints_at_vertices(self):
    228228        """Test that data points coinciding with vertices yield a diagonal matrix
    229229        """
    230        
     230
    231231        a = [0.0, 0.0]
    232232        b = [0.0, 2.0]
     
    235235        vertices = [ [1,0,2] ]   #bac
    236236
    237         data = points #Use data at vertices       
    238        
     237        data = points #Use data at vertices
     238
    239239        interp = Interpolation(points, vertices, data)
    240240        assert allclose(interp.get_A(), [[1., 0., 0.],
    241241                                   [0., 1., 0.],
    242                                    [0., 0., 1.]]) 
    243        
     242                                   [0., 0., 1.]])
     243
    244244
    245245
     
    248248        each point should affect two matrix entries equally
    249249        """
    250        
     250
    251251        a = [0.0, 0.0]
    252252        b = [0.0, 2.0]
     
    256256
    257257        data = [ [0., 1.], [1., 0.], [1., 1.] ]
    258        
     258
    259259        interp = Interpolation(points, vertices, data)
    260        
    261         assert allclose(interp.get_A(), [[0.5, 0.5, 0.0],  #Affects vertex 1 and 0   
     260
     261        assert allclose(interp.get_A(), [[0.5, 0.5, 0.0],  #Affects vertex 1 and 0
    262262                                   [0.5, 0.0, 0.5],  #Affects vertex 0 and 2
    263263                                   [0.0, 0.5, 0.5]]) #Affects vertex 1 and 2
     
    268268        each point should affect two matrix entries in proportion
    269269        """
    270        
     270
    271271        a = [0.0, 0.0]
    272272        b = [0.0, 2.0]
     
    276276
    277277        data = [ [0., 1.5], [1.5, 0.], [1.5, 0.5] ]
    278        
     278
    279279        interp = Interpolation(points, vertices, data)
    280        
     280
    281281        assert allclose(interp.get_A(), [[0.25, 0.75, 0.0],  #Affects vertex 1 and 0
    282282                                   [0.25, 0.0, 0.75],  #Affects vertex 0 and 2
     
    288288
    289289        from Numeric import sum
    290        
     290
    291291        a = [0.0, 0.0]
    292292        b = [0.0, 2.0]
     
    296296
    297297        data = [ [0.2, 1.5], [0.123, 1.768], [1.43, 0.44] ]
    298        
     298
    299299        interp = Interpolation(points, vertices, data)
    300300        #print "interp.get_A()", interp.get_A()
    301301        assert allclose(sum(interp.get_A(), axis=1), 1.0)
    302        
     302
    303303    def test_arbitrary_datapoints_some_outside(self):
    304304        """Try arbitrary datapoints one outside the triangle.
     
    307307
    308308        from Numeric import sum
    309        
     309
    310310        a = [0.0, 0.0]
    311311        b = [0.0, 2.0]
     
    322322        interp = Interpolation(points, vertices, data, precrop = False)
    323323        assert allclose(sum(interp.get_A(), axis=1), [1,1,1,0])
    324        
    325        
    326 
    327     # this causes a memory error in scipy.sparse       
     324
     325
     326
     327    # this causes a memory error in scipy.sparse
    328328    def test_more_triangles(self):
    329        
     329
    330330        a = [-1.0, 0.0]
    331331        b = [3.0, 4.0]
     
    340340        #Data points
    341341        data_points = [ [-3., 2.0], [-2, 1], [0.0, 1], [0, 3], [2, 3], [-1.0/3,-4./3] ]
    342         interp = Interpolation(points, triangles, data_points) 
    343 
    344         answer = [[0.0, 0.0, 0.0, 1.0, 0.0, 0.0],    #Affects point d     
     342        interp = Interpolation(points, triangles, data_points)
     343
     344        answer = [[0.0, 0.0, 0.0, 1.0, 0.0, 0.0],    #Affects point d
    345345                  [0.5, 0.0, 0.0, 0.5, 0.0, 0.0],    #Affects points a and d
    346346                  [0.75, 0.25, 0.0, 0.0, 0.0, 0.0],  #Affects points a and b
     
    354354            for j in range(A.shape[1]):
    355355                if not allclose(A[i,j], answer[i][j]):
    356                     print i,j,':',A[i,j], answer[i][j] 
     356                    print i,j,':',A[i,j], answer[i][j]
    357357
    358358
     
    368368        points = [a, b, c]
    369369        triangles = [ [1,0,2] ]   #bac
    370          
     370
    371371        d1 = [1.0, 1.0]
    372372        d2 = [1.0, 3.0]
     
    375375        z2 = 4
    376376        z3 = 4
    377         data_coords = [d1, d2, d3] 
    378        
     377        data_coords = [d1, d2, d3]
     378
    379379        interp = Interpolation(points, triangles, data_coords, alpha=5.0e-20)
    380380        z = [z1, z2, z3]
     
    384384        #print "f\n",f
    385385        #print "answer\n",answer
    386        
     386
    387387        assert allclose(f, answer, atol=1e-7)
    388        
    389        
     388
     389
    390390    def test_smooth_att_to_meshII(self):
    391        
     391
    392392        a = [0.0, 0.0]
    393393        b = [0.0, 5.0]
     
    395395        points = [a, b, c]
    396396        triangles = [ [1,0,2] ]   #bac
    397          
     397
    398398        d1 = [1.0, 1.0]
    399399        d2 = [1.0, 2.0]
    400400        d3 = [3.0,1.0]
    401         data_coords = [d1, d2, d3]       
     401        data_coords = [d1, d2, d3]
    402402        z = linear_function(data_coords)
    403403        interp = Interpolation(points, triangles, data_coords, alpha=0.0)
    404404        f = interp.fit(z)
    405405        answer = linear_function(points)
    406        
     406
    407407        assert allclose(f, answer)
    408    
     408
    409409    def test_smooth_attributes_to_meshIII(self):
    410        
     410
    411411        a = [-1.0, 0.0]
    412412        b = [3.0, 4.0]
     
    441441        #print "answer\n",answer
    442442        assert allclose(f, answer)
    443        
     443
    444444
    445445    def test_smooth_attributes_to_meshIV(self):
    446446        """ Testing 2 attributes smoothed to the mesh
    447447        """
    448        
     448
    449449        a = [0.0, 0.0]
    450450        b = [0.0, 5.0]
     
    452452        points = [a, b, c]
    453453        triangles = [ [1,0,2] ]   #bac
    454          
     454
    455455        d1 = [1.0, 1.0]
    456456        d2 = [1.0, 3.0]
     
    459459        z2 = [4, 8]
    460460        z3 = [4, 8]
    461         data_coords = [d1, d2, d3] 
    462        
     461        data_coords = [d1, d2, d3]
     462
    463463        interp = Interpolation(points, triangles, data_coords, alpha=0.0)
    464464        z = [z1, z2, z3]
     
    466466        answer = [[0,0], [5., 10.], [5., 10.]]
    467467        assert allclose(f, answer)
    468        
     468
    469469    def test_interpolate_attributes_to_points(self):
    470470        v0 = [0.0, 0.0]
    471471        v1 = [0.0, 5.0]
    472472        v2 = [5.0, 0.0]
    473        
     473
    474474        vertices = [v0, v1, v2]
    475475        triangles = [ [1,0,2] ]   #bac
    476          
     476
    477477        d0 = [1.0, 1.0]
    478478        d1 = [1.0, 2.0]
    479479        d2 = [3.0, 1.0]
    480480        point_coords = [ d0, d1, d2]
    481        
     481
    482482        interp = Interpolation(vertices, triangles, point_coords)
    483483        f = linear_function(vertices)
    484484        z = interp.interpolate(f)
    485485        answer = linear_function(point_coords)
    486        
     486
    487487
    488488        assert allclose(z, answer)
    489489
    490        
     490
    491491    def test_interpolate_attributes_to_pointsII(self):
    492492        a = [-1.0, 0.0]
     
    500500        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
    501501
    502          
     502
    503503        point_coords = [[-2.0, 2.0],
    504504                        [-1.0, 1.0],
     
    513513                        [0.5, -1.9],
    514514                        [3.0, 1.0]]
    515        
     515
    516516        interp = Interpolation(vertices, triangles, point_coords)
    517517        f = linear_function(vertices)
     
    521521        #print "answer",answer
    522522        assert allclose(z, answer)
    523    
     523
    524524    def test_interpolate_attributes_to_pointsIII(self):
    525525        """Test linear interpolation of known values at vertices to
     
    530530        c = [5.0, 0.0]
    531531        d = [5.0, 5.0]
    532        
     532
    533533        vertices = [a, b, c, d]
    534534        triangles = [ [1,0,2], [2,3,0] ]   #bac, cdb
     
    545545        d4 = [2.5, 2.5]
    546546        d5 = [4.0, 1.0]
    547          
     547
    548548        #Point on common vertex
    549549        d6 = [0., 5.]
    550550
    551        
     551
    552552        point_coords = [d0, d1, d2, d3, d4, d5, d6]
    553        
     553
    554554        interp = Interpolation(vertices, triangles, point_coords)
    555555
    556556        #Known values at vertices
    557         #Functions are x+y, x+2y, 2x+y, x-y-5       
    558         f = [ [0., 0., 0., -5.],        # (0,0)   
     557        #Functions are x+y, x+2y, 2x+y, x-y-5
     558        f = [ [0., 0., 0., -5.],        # (0,0)
    559559              [5., 10., 5., -10.],      # (0,5)
    560560              [5., 5., 10.0, 0.],       # (5,0)
    561561              [10., 15., 15., -5.]]     # (5,5)
    562          
     562
    563563        z = interp.interpolate(f)
    564564        answer = [ [2., 3., 3., -5.],   # (1,1)
     
    576576
    577577        assert allclose(z, answer)
    578    
     578
    579579    def test_interpolate_attributes_to_pointsIV(self):
    580580        a = [-1.0, 0.0]
     
    588588        triangles = [[0,1,3], [1,0,2], [0,4,5], [0,5,2]] #abd bac aef afc
    589589
    590          
     590
    591591        point_coords = [[-2.0, 2.0],
    592592                        [-1.0, 1.0],
     
    601601                        [0.5, -1.9],
    602602                        [3.0, 1.0]]
    603        
     603
    604604        interp = Interpolation(vertices, triangles, point_coords)
    605605        f = array([linear_function(vertices),2*linear_function(vertices) ])
     
    607607        #print "f",f
    608608        z = interp.interpolate(f)
    609         answer = [linear_function(point_coords),             
     609        answer = [linear_function(point_coords),
    610610                  2*linear_function(point_coords) ]
    611611        answer = transpose(answer)
     
    613613        #print "answer",answer
    614614        assert allclose(z, answer)
    615        
     615
    616616    def test_smooth_attributes_to_mesh_function(self):
    617617        """ Testing 2 attributes smoothed to the mesh
    618618        """
    619        
     619
    620620        a = [0.0, 0.0]
    621621        b = [0.0, 5.0]
     
    623623        points = [a, b, c]
    624624        triangles = [ [1,0,2] ]   #bac
    625          
     625
    626626        d1 = [1.0, 1.0]
    627627        d2 = [1.0, 3.0]
     
    632632        data_coords = [d1, d2, d3]
    633633        z = [z1, z2, z3]
    634        
     634
    635635        f = fit_to_mesh(points, triangles, data_coords, z, alpha=0.0)
    636636        answer = [[0, 0], [5., 10.], [5., 10.]]
    637        
     637
    638638        assert allclose(f, answer)
    639639
    640640
    641        
     641
    642642    def test_pts2rectangular(self):
    643643
     
    645645        FN = 'xyatest' + str(time.time()) + '.xya'
    646646        fid = open(FN, 'w')
    647         fid.write(' %s \n' %('elevation'))       
     647        fid.write(' %s \n' %('elevation'))
    648648        fid.write('%f %f %f\n' %(1,1,2) )
    649649        fid.write('%f %f %f\n' %(1,3,4) )
    650         fid.write('%f %f %f\n' %(3,1,4) )               
     650        fid.write('%f %f %f\n' %(3,1,4) )
    651651        fid.close()
    652        
     652
    653653        points, triangles, boundary, attributes =\
    654654                pts2rectangular(FN, 4, 4, format = 'asc')
    655        
     655
    656656
    657657        data_coords = [ [1,1], [1,3], [3,1] ]
    658658        z = [2, 4, 4]
    659659
    660         ref = fit_to_mesh(points, triangles, data_coords, z)           
     660        ref = fit_to_mesh(points, triangles, data_coords, z)
    661661
    662662        #print attributes
     
    665665
    666666        os.remove(FN)
    667        
    668 
    669     #Tests of smoothing matrix   
     667
     668
     669    #Tests of smoothing matrix
    670670    def test_smoothing_matrix_one_triangle(self):
    671671        from Numeric import dot
     
    674674        c = [2.0,0.0]
    675675        points = [a, b, c]
    676        
     676
    677677        vertices = [ [1,0,2] ]   #bac
    678678
     
    689689        #           int 1 dx dy = area = 2
    690690        assert dot(dot(f, interp.get_D()), f) == 2
    691        
     691
    692692        #Define f(x,y) = y
    693693        f = array([0,2,0])  #Value at global vertex 1
     
    702702        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
    703703        #           int 2 dx dy = 2*area = 4
    704         assert dot(dot(f, interp.get_D()), f) == 4       
    705        
     704        assert dot(dot(f, interp.get_D()), f) == 4
     705
    706706
    707707
    708708    def test_smoothing_matrix_more_triangles(self):
    709709        from Numeric import dot
    710        
     710
    711711        a = [0.0, 0.0]
    712712        b = [0.0, 2.0]
     
    717717
    718718        points = [a, b, c, d, e, f]
    719         #bac, bce, ecf, dbe, daf, dae 
     719        #bac, bce, ecf, dbe, daf, dae
    720720        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4]]
    721721
     
    728728
    729729        #Define f(x,y) = x
    730         f = array([0,0,2,0,2,4]) #f evaluated at points a-f 
     730        f = array([0,0,2,0,2,4]) #f evaluated at points a-f
    731731
    732732        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
    733733        #           int 1 dx dy = total area = 8
    734734        assert dot(dot(f, interp.get_D()), f) == 8
    735        
     735
    736736        #Define f(x,y) = y
    737         f = array([0,2,0,4,2,0]) #f evaluated at points a-f 
     737        f = array([0,2,0,4,2,0]) #f evaluated at points a-f
    738738
    739739        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
     
    742742
    743743        #Define f(x,y) = x+y
    744         f = array([0,2,2,4,4,4])  #f evaluated at points a-f   
     744        f = array([0,2,2,4,4,4])  #f evaluated at points a-f
    745745
    746746        #Check that int (df/dx)**2 + (df/dy)**2 dx dy =
    747747        #           int 2 dx dy = 2*area = 16
    748         assert dot(dot(f, interp.get_D()), f) == 16       
     748        assert dot(dot(f, interp.get_D()), f) == 16
    749749
    750750
    751751    def test_fit_and_interpolation(self):
    752752        from mesh import Mesh
    753        
     753
    754754        a = [0.0, 0.0]
    755755        b = [0.0, 2.0]
     
    760760
    761761        points = [a, b, c, d, e, f]
    762         #bac, bce, ecf, dbe, daf, dae 
     762        #bac, bce, ecf, dbe, daf, dae
    763763        triangles = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
    764764
     
    773773                       [ 1.0, 1.0],
    774774                       [ 1.0, 2.0],
    775                        [ 1.0, 3.0],                                         
     775                       [ 1.0, 3.0],
    776776                       [ 2.0, 1.0],
    777777                       [ 3.0, 0.0],
    778                        [ 3.0, 1.0]]                                         
    779        
     778                       [ 3.0, 1.0]]
     779
    780780        interp = Interpolation(points, triangles, data_points, alpha=0.0)
    781781
     
    797797
    798798    def test_smoothing_and_interpolation(self):
    799        
     799
    800800        a = [0.0, 0.0]
    801801        b = [0.0, 2.0]
     
    806806
    807807        points = [a, b, c, d, e, f]
    808         #bac, bce, ecf, dbe, daf, dae 
     808        #bac, bce, ecf, dbe, daf, dae
    809809        triangles = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
    810810
     
    816816
    817817        z = linear_function(data_points)
    818         answer = linear_function(points)       
     818        answer = linear_function(points)
    819819
    820820        #Make interpolator with too few data points and no smoothing
    821821        interp = Interpolation(points, triangles, data_points, alpha=0.0)
    822         #Must raise an exception       
     822        #Must raise an exception
    823823        try:
    824824            f = interp.fit(z)
     
    828828        #Now try with smoothing parameter
    829829        interp = Interpolation(points, triangles, data_points, alpha=1.0e-13)
    830        
     830
    831831        f = interp.fit(z)
    832832        #f will be different from answerr due to smoothing
     
    855855
    856856        points = [a, b, c, d, e, f]
    857         #bac, bce, ecf, dbe, daf, dae 
     857        #bac, bce, ecf, dbe, daf, dae
    858858        triangles = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
    859859
     
    869869                        [ 15, -17],   #Outside mesh
    870870                        [ 1.0, 2.0],
    871                         [ 1.0, 3.0],                                         
     871                        [ 1.0, 3.0],
    872872                        [ 2.0, 1.0],
    873873                        [ 3.0, 0.0],
     
    889889                        [ 1.0, 0.5],
    890890                        [ 2.0, 0.4],
    891                         [ 2.8, 1.2]]                                         
    892        
     891                        [ 2.8, 1.2]]
     892
    893893
    894894
     
    907907        import Numeric
    908908        z1 = Numeric.take(z1, [0,1,2,4,5,6])
    909         answer = Numeric.take(answer, [0,1,2,4,5,6])               
     909        answer = Numeric.take(answer, [0,1,2,4,5,6])
    910910        assert allclose(z1, answer)
    911911
     
    942942
    943943        points = [a, b, c, d, e, f]
    944         #bac, bce, ecf, dbe, daf, dae 
     944        #bac, bce, ecf, dbe, daf, dae
    945945        triangles = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
    946946
     
    955955                        [ 1.0, 1.0],
    956956                        [ 1.0, 2.0],
    957                         [ 1.0, 3.0],                                         
     957                        [ 1.0, 3.0],
    958958                        [ 2.0, 1.0],
    959959                        [ 3.0, 0.0],
     
    963963        #First check that things are OK when using same origin
    964964        mesh_origin = (56, 290000, 618000) #zone, easting, northing
    965         data_origin = (56, 290000, 618000) #zone, easting, northing 
     965        data_origin = (56, 290000, 618000) #zone, easting, northing
    966966
    967967
     
    971971                               data_origin = data_origin,
    972972                               mesh_origin = mesh_origin)
    973        
     973
    974974        z = linear_function(data_points1) #Example z-values
    975975        f = interp.fit(z)                 #Fitted values at vertices
     
    982982                        [ 1.0, 0.5],
    983983                        [ 2.0, 0.4],
    984                         [ 2.8, 1.2]]                                         
    985        
     984                        [ 2.8, 1.2]]
     985
    986986
    987987        #Build new A matrix based on new points
     
    10001000        #Then check situtaion where points are relative to a different
    10011001        #origin (same zone, though, until we figure that out (FIXME))
    1002        
     1002
    10031003        mesh_origin = (56, 290000, 618000) #zone, easting, northing
    1004         data_origin = (56, 10000, 10000) #zone, easting, northing 
     1004        data_origin = (56, 10000, 10000) #zone, easting, northing
    10051005
    10061006        #Shift datapoints according to new origin
     
    10121012        for k in range(len(data_points2)):
    10131013            data_points2[k][0] += mesh_origin[1] - data_origin[1]
    1014             data_points2[k][1] += mesh_origin[2] - data_origin[2]           
    1015 
    1016 
    1017        
     1014            data_points2[k][1] += mesh_origin[2] - data_origin[2]
     1015
     1016
     1017
    10181018        #Fit surface to mesh
    10191019        interp = Interpolation(points, triangles, data_points1,
     
    10211021                               data_origin = data_origin,
    10221022                               mesh_origin = mesh_origin)
    1023        
     1023
    10241024        f1 = interp.fit(z) #Fitted values at vertices (using same z as before)
    10251025
     
    10551055    def test_fit_to_mesh_file(self):
    10561056        from load_mesh.loadASCII import mesh_file_to_mesh_dictionary, \
    1057              export_mesh_file   
     1057             export_mesh_file
    10581058        import tempfile
    10591059        import os
    1060        
     1060
    10611061        # create a .tsh file, no user outline
    10621062        mesh_dic = {}
     
    10721072        mesh_dic['segment_tags'] = ['external',
    10731073                                                  'external',
    1074                                                   'external']       
     1074                                                  'external']
    10751075        mesh_file = tempfile.mktemp(".tsh")
    10761076        export_mesh_file(mesh_file,mesh_dic)
    1077        
     1077
    10781078        # create an .xya file
    10791079        point_file = tempfile.mktemp(".xya")
     
    10811081        fd.write("elevation, stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
    10821082        fd.close()
    1083        
     1083
    10841084        mesh_output_file = "new_trianlge.tsh"
    10851085        fit_to_mesh_file(mesh_file,
    10861086                         point_file,
    10871087                         mesh_output_file,
    1088                          alpha = 0.0) 
     1088                         alpha = 0.0)
    10891089        # load in the .tsh file we just wrote
    10901090        mesh_dic = mesh_file_to_mesh_dictionary(mesh_output_file)
    1091         #print "mesh_dic",mesh_dic 
     1091        #print "mesh_dic",mesh_dic
    10921092        ans =[[0.0, 0.0],
    10931093              [5.0, 10.0],
    10941094              [5.0,10.0]]
    10951095        assert allclose(mesh_dic['vertex_attributes'],ans)
    1096        
     1096
    10971097        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
    10981098                        ['elevation','stage'],
    10991099                        'test_fit_to_mesh_file failed')
    1100        
     1100
    11011101        #clean up
    11021102        os.remove(mesh_file)
    11031103        os.remove(point_file)
    1104         os.remove(mesh_output_file)       
    1105        
     1104        os.remove(mesh_output_file)
     1105
    11061106    def test_fit_to_mesh_fileII(self):
    11071107        from load_mesh.loadASCII import mesh_file_to_mesh_dictionary, \
    1108              export_mesh_file   
     1108             export_mesh_file
    11091109        import tempfile
    11101110        import os
    1111        
     1111
    11121112        # create a .tsh file, no user outline
    11131113        mesh_dic = {}
     
    11231123        mesh_dic['segment_tags'] = ['external',
    11241124                                                  'external',
    1125                                                   'external']       
     1125                                                  'external']
    11261126        mesh_file = tempfile.mktemp(".tsh")
    11271127        export_mesh_file(mesh_file,mesh_dic)
    1128        
     1128
    11291129        # create an .xya file
    11301130        point_file = tempfile.mktemp(".xya")
     
    11321132        fd.write("elevation, stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
    11331133        fd.close()
    1134        
     1134
    11351135        mesh_output_file = "new_triangle.tsh"
    11361136        fit_to_mesh_file(mesh_file,
    11371137                         point_file,
    11381138                         mesh_output_file,
    1139                          alpha = 0.0) 
     1139                         alpha = 0.0)
    11401140        # load in the .tsh file we just wrote
    11411141        mesh_dic = mesh_file_to_mesh_dictionary(mesh_output_file)
     
    11451145                         [1.0, 2.0,5.0, 10.0],
    11461146                         [1.0, 2.0,5.0,10.0]])
    1147        
     1147
    11481148        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
    11491149                        ['density', 'temp','elevation','stage'],
    11501150                        'test_fit_to_mesh_file failed')
    1151        
     1151
    11521152        #clean up
    11531153        os.remove(mesh_file)
    1154         os.remove(mesh_output_file)       
     1154        os.remove(mesh_output_file)
    11551155        os.remove(point_file)
    1156        
     1156
    11571157    def test_fit_to_msh_netcdf_fileII(self):
    1158         from load_mesh.loadASCII import mesh_file_to_mesh_dictionary,export_mesh_file   
     1158        from load_mesh.loadASCII import mesh_file_to_mesh_dictionary,export_mesh_file
    11591159        import tempfile
    11601160        import os
    1161        
     1161
    11621162        # create a .tsh file, no user outline
    11631163        mesh_dic = {}
     
    11731173        mesh_dic['segment_tags'] = ['external',
    11741174                                                  'external',
    1175                                                   'external']       
     1175                                                  'external']
    11761176        mesh_file = tempfile.mktemp(".msh")
    11771177        export_mesh_file(mesh_file,mesh_dic)
    1178        
     1178
    11791179        # create an .xya file
    11801180        point_file = tempfile.mktemp(".xya")
     
    11821182        fd.write("elevation, stage \n 1.0, 1.0,2.,4 \n 1.0, 3.0,4,8 \n 3.0,1.0,4.,8 \n")
    11831183        fd.close()
    1184        
     1184
    11851185        mesh_output_file = "new_triangle.msh"
    11861186        fit_to_mesh_file(mesh_file,
    11871187                         point_file,
    11881188                         mesh_output_file,
    1189                          alpha = 0.0) 
     1189                         alpha = 0.0)
    11901190        # load in the .tsh file we just wrote
    11911191        mesh_dic = mesh_file_to_mesh_dictionary(mesh_output_file)
     
    11951195                         [1.0, 2.0,5.0, 10.0],
    11961196                         [1.0, 2.0,5.0,10.0]])
    1197        
     1197
    11981198        self.failUnless(mesh_dic['vertex_attribute_titles']  ==
    11991199                        ['density', 'temp','elevation','stage'],
    12001200                        'test_fit_to_mesh_file failed')
    1201        
     1201
    12021202        #clean up
    12031203        os.remove(mesh_file)
    1204         os.remove(mesh_output_file)       
     1204        os.remove(mesh_output_file)
    12051205        os.remove(point_file)
    1206        
     1206
    12071207#-------------------------------------------------------------
    12081208if __name__ == "__main__":
    1209     suite = unittest.makeSuite(TestCase,'test')
    1210 
    1211     #suite = unittest.makeSuite(TestCase,'test_fit_to_msh_netcdf_fileII')
    1212     #suite = unittest.makeSuite(TestCase,'test_fit_to_mesh_fileII')
     1209    suite = unittest.makeSuite(Test_Least_Squares,'test')
     1210
     1211    #suite = unittest.makeSuite(Test_Least_Squares,'test_fit_to_msh_netcdf_fileII')
     1212    #suite = unittest.makeSuite(Test_Least_Squares,'test_fit_to_mesh_fileII')
    12131213    runner = unittest.TextTestRunner(verbosity=1)
    12141214    runner.run(suite)
    12151215
    1216    
    1217    
    1218 
    1219 
    1220 
     1216
     1217
     1218
     1219
  • inundation/ga/storm_surge/pyvolution/test_mesh.py

    r984 r1018  
    1212
    1313def distance(x, y):
    14     return sqrt( sum( (array(x)-array(y))**2 ))         
    15        
    16 class TestCase(unittest.TestCase):
     14    return sqrt( sum( (array(x)-array(y))**2 ))
     15
     16class Test_Mesh(unittest.TestCase):
    1717    def setUp(self):
    1818        pass
    19        
     19
    2020    def tearDown(self):
    2121        pass
     
    3232            msg = 'Should have raised exception'
    3333            raise msg
    34        
    35        
     34
     35
    3636    def test_basic_triangle(self):
    3737
     
    3939        b = [4.0, 0.0]
    4040        c = [0.0, 3.0]
    41        
     41
    4242        points = [a, b, c]
    4343        vertices = [[0,1,2]]
    44         mesh = Mesh(points, vertices) 
     44        mesh = Mesh(points, vertices)
    4545
    4646        #Centroid
     
    5757        assert allclose(normals[0, 0:2], [3.0/5, 4.0/5])
    5858        assert allclose(normals[0, 2:4], [-1.0, 0.0])
    59         assert allclose(normals[0, 4:6], [0.0, -1.0])       
     59        assert allclose(normals[0, 4:6], [0.0, -1.0])
    6060
    6161        assert allclose(mesh.get_normal(0,0), [3.0/5, 4.0/5])
    6262        assert allclose(mesh.get_normal(0,1), [-1.0, 0.0])
    63         assert allclose(mesh.get_normal(0,2), [0.0, -1.0])               
    64        
     63        assert allclose(mesh.get_normal(0,2), [0.0, -1.0])
     64
    6565        #Edge lengths
    6666        assert allclose(mesh.edgelengths[0], [5.0, 3.0, 4.0])
     
    7878
    7979        V2 = mesh.get_vertex_coordinate(0, 2)
    80         assert allclose(V2, [0.0, 3.0])               
     80        assert allclose(V2, [0.0, 3.0])
    8181
    8282
     
    8686        mesh.check_integrity()
    8787
    88        
     88
    8989        #Test that the centroid is located 2/3 of the way
    9090        #from each vertex to the midpoint of the opposite side
    9191
    9292        V = mesh.get_vertex_coordinates()
    93        
     93
    9494        x0 = V[0,0]
    9595        y0 = V[0,1]
     
    9898        x2 = V[0,4]
    9999        y2 = V[0,5]
    100        
     100
    101101        m0 = [(x1 + x2)/2, (y1 + y2)/2]
    102102        m1 = [(x0 + x2)/2, (y0 + y2)/2]
     
    108108        #
    109109        d0 = distance(centroid, [x1, y1])
    110         d1 = distance(m1, [x1, y1])       
     110        d1 = distance(m1, [x1, y1])
    111111        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
    112112
    113113        d0 = distance(centroid, [x2, y2])
    114114        d1 = distance(m2, [x2, y2])
    115         assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)       
    116        
     115        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
     116
    117117        #Radius
    118118        d0 = distance(centroid, m0)
    119119        assert d0 == 5.0/6
    120        
     120
    121121        d1 = distance(centroid, m1)
    122         assert d1 == sqrt(73.0/36)       
    123 
    124         d2 = distance(centroid, m2)       
    125         assert d2 == sqrt(13.0/9)       
    126        
     122        assert d1 == sqrt(73.0/36)
     123
     124        d2 = distance(centroid, m2)
     125        assert d2 == sqrt(13.0/9)
     126
    127127        assert mesh.radii[0] == min(d0, d1, d2)
    128128        assert mesh.radii[0] == 5.0/6
     
    134134        vertices = [[0,3,2], [2,3,1], [1,3,0]]
    135135        new_mesh = Mesh(points, vertices)
    136        
     136
    137137        assert new_mesh.areas[0] == new_mesh.areas[1]
    138         assert new_mesh.areas[1] == new_mesh.areas[2]       
    139         assert new_mesh.areas[1] == new_mesh.areas[2]       
    140 
    141         assert new_mesh.areas[1] == mesh.areas[0]/3       
     138        assert new_mesh.areas[1] == new_mesh.areas[2]
     139        assert new_mesh.areas[1] == new_mesh.areas[2]
     140
     141        assert new_mesh.areas[1] == mesh.areas[0]/3
    142142
    143143
     
    151151        vertices = [[0,1,2]]
    152152
    153         mesh = Mesh(points, vertices) 
     153        mesh = Mesh(points, vertices)
    154154        centroid = mesh.centroid_coordinates[0]
    155155
    156        
     156
    157157        #Test that the centroid is located 2/3 of the way
    158158        #from each vertex to the midpoint of the opposite side
    159159
    160160        V = mesh.get_vertex_coordinates()
    161        
     161
    162162        x0 = V[0,0]
    163163        y0 = V[0,1]
     
    166166        x2 = V[0,4]
    167167        y2 = V[0,5]
    168        
     168
    169169        m0 = [(x1 + x2)/2, (y1 + y2)/2]
    170170        m1 = [(x0 + x2)/2, (y0 + y2)/2]
     
    176176        #
    177177        d0 = distance(centroid, [x1, y1])
    178         d1 = distance(m1, [x1, y1])       
     178        d1 = distance(m1, [x1, y1])
    179179        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
    180180
    181181        d0 = distance(centroid, [x2, y2])
    182182        d1 = distance(m2, [x2, y2])
    183         assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)       
    184        
     183        assert abs(d0 - 2*d1/3) < epsilon, '%e, %e' %(d0, 2*d1/3)
     184
    185185        #Radius
    186186        d0 = distance(centroid, m0)
    187187        d1 = distance(centroid, m1)
    188         d2 = distance(centroid, m2)       
     188        d2 = distance(centroid, m2)
    189189        assert mesh.radii[0] == min(d0, d1, d2)
    190190
     
    197197        vertices = [[0,3,2], [2,3,1], [1,3,0]]
    198198        new_mesh = Mesh(points, vertices)
    199        
     199
    200200        assert new_mesh.areas[0] == new_mesh.areas[1]
    201         assert new_mesh.areas[1] == new_mesh.areas[2]       
    202         assert new_mesh.areas[1] == new_mesh.areas[2]       
    203 
    204         assert new_mesh.areas[1] == mesh.areas[0]/3       
    205        
     201        assert new_mesh.areas[1] == new_mesh.areas[2]
     202        assert new_mesh.areas[1] == new_mesh.areas[2]
     203
     204        assert new_mesh.areas[1] == mesh.areas[0]/3
     205
    206206
    207207        #Test that points are arranged in a counter clock wise order
     
    217217        e = [2.0, 2.0]
    218218        points = [a, b, c, e]
    219         vertices = [ [1,0,2], [1,2,3] ]   #bac, bce 
     219        vertices = [ [1,0,2], [1,2,3] ]   #bac, bce
    220220        mesh = Mesh(points, vertices)
    221        
     221
    222222        assert mesh.areas[0] == 2.0
    223223
    224         assert allclose(mesh.centroid_coordinates[0], [2.0/3, 2.0/3])       
     224        assert allclose(mesh.centroid_coordinates[0], [2.0/3, 2.0/3])
    225225
    226226
    227227        #Test that points are arranged in a counter clock wise order
    228         mesh.check_integrity()       
    229 
    230 
    231            
     228        mesh.check_integrity()
     229
     230
     231
    232232    def test_more_triangles(self):
    233        
     233
    234234        a = [0.0, 0.0]
    235235        b = [0.0, 2.0]
     
    240240
    241241        points = [a, b, c, d, e, f]
    242         #bac, bce, ecf, dbe, daf, dae 
     242        #bac, bce, ecf, dbe, daf, dae
    243243        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4], [3,0,5], [3,0,4]]
    244         mesh = Mesh(points, vertices)       
     244        mesh = Mesh(points, vertices)
    245245
    246246        #Test that points are arranged in a counter clock wise order
    247         mesh.check_integrity()       
     247        mesh.check_integrity()
    248248
    249249        assert mesh.areas[0] == 2.0
     
    252252        assert mesh.areas[3] == 2.0
    253253        assert mesh.areas[4] == 8.0
    254         assert mesh.areas[5] == 4.0                               
    255        
     254        assert mesh.areas[5] == 4.0
     255
    256256        assert mesh.edgelengths[1,0] == 2.0
    257257        assert mesh.edgelengths[1,1] == 2.0
     
    259259
    260260        assert allclose(mesh.centroid_coordinates[0], [2.0/3, 2.0/3])
    261         assert allclose(mesh.centroid_coordinates[1], [4.0/3, 4.0/3]) 
     261        assert allclose(mesh.centroid_coordinates[1], [4.0/3, 4.0/3])
    262262        assert allclose(mesh.centroid_coordinates[2], [8.0/3, 2.0/3])
    263         assert allclose(mesh.centroid_coordinates[3], [2.0/3, 8.0/3])         
     263        assert allclose(mesh.centroid_coordinates[3], [2.0/3, 8.0/3])
    264264
    265265
     
    278278        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
    279279        mesh = Mesh(points, vertices)
    280        
     280
    281281        mesh.check_integrity()
    282282
     
    284284        T = mesh
    285285        tid = 0
    286         assert T.number_of_boundaries[tid] == 2   
     286        assert T.number_of_boundaries[tid] == 2
    287287        assert T.neighbours[tid, 0] < 0  #Opposite point b (0,2)
    288288        assert T.neighbours[tid, 1] == 1 #Opposite point a (0,0)
    289         assert T.neighbours[tid, 2] < 0  #Opposite point c (2,0)       
     289        assert T.neighbours[tid, 2] < 0  #Opposite point c (2,0)
    290290
    291291        tid = 1
    292         assert T.number_of_boundaries[tid] == 0           
     292        assert T.number_of_boundaries[tid] == 0
    293293        assert T.neighbours[tid, 0] == 2  #Opposite point b (0,2)
    294294        assert T.neighbours[tid, 1] == 3  #Opposite point c (2,0)
     
    296296
    297297        tid = 2
    298         assert T.number_of_boundaries[tid] == 2           
     298        assert T.number_of_boundaries[tid] == 2
    299299        assert T.neighbours[tid, 0] < 0   #Opposite point e (2,2)
    300300        assert T.neighbours[tid, 1] < 0   #Opposite point c (2,0)
    301         assert T.neighbours[tid, 2] == 1  #Opposite point f (4,0)       
     301        assert T.neighbours[tid, 2] == 1  #Opposite point f (4,0)
    302302
    303303        tid = 3
    304         assert T.number_of_boundaries[tid] == 2           
     304        assert T.number_of_boundaries[tid] == 2
    305305        assert T.neighbours[tid, 0] == 1  #Opposite point d (0,4)
    306306        assert T.neighbours[tid, 1] < 0   #Opposite point b (0,3)
     
    311311        assert T.neighbour_edges[tid, 0] < 0  #Opposite point b (0,2)
    312312        assert T.neighbour_edges[tid, 1] == 2 #Opposite point a (0,0)
    313         assert T.neighbour_edges[tid, 2] < 0  #Opposite point c (2,0)       
    314 
    315         tid = 1       
     313        assert T.neighbour_edges[tid, 2] < 0  #Opposite point c (2,0)
     314
     315        tid = 1
    316316        assert T.neighbour_edges[tid, 0] == 2 #Opposite point b (0,2)
    317317        assert T.neighbour_edges[tid, 1] == 0 #Opposite point c (2,0)
    318318        assert T.neighbour_edges[tid, 2] == 1 #Opposite point e (2,2)
    319319
    320         tid = 2       
     320        tid = 2
    321321        assert T.neighbour_edges[tid, 0] < 0  #Opposite point e (2,2)
    322322        assert T.neighbour_edges[tid, 1] < 0  #Opposite point c (2,0)
    323         assert T.neighbour_edges[tid, 2] == 0 #Opposite point f (4,0)       
    324 
    325         tid = 3       
     323        assert T.neighbour_edges[tid, 2] == 0 #Opposite point f (4,0)
     324
     325        tid = 3
    326326        assert T.neighbour_edges[tid, 0] == 1 #Opposite point d (0,4)
    327327        assert T.neighbour_edges[tid, 1] < 0  #Opposite point b (0,3)
    328328        assert T.neighbour_edges[tid, 2] < 0  #Opposite point e (2,2)
    329329
    330        
     330
    331331    def test_rectangular_mesh_basic(self):
    332332        M=1
     
    336336        mesh = Mesh(points, vertices, boundary)
    337337
    338         #Test that points are arranged in a counter clock wise order       
     338        #Test that points are arranged in a counter clock wise order
    339339        mesh.check_integrity()
    340340
     
    343343        points, vertices, boundary = rectangular(M, N)
    344344        mesh = Mesh(points, vertices, boundary)
    345        
    346         #Test that points are arranged in a counter clock wise order       
     345
     346        #Test that points are arranged in a counter clock wise order
    347347        mesh.check_integrity()
    348348
    349349        #assert mesh.boundary[(7,1)] == 2 # top
    350350        assert mesh.boundary[(7,1)] == 'top' # top
    351         assert mesh.boundary[(3,1)] == 'top' # top               
    352 
    353        
     351        assert mesh.boundary[(3,1)] == 'top' # top
     352
     353
    354354    def test_boundary_tags(self):
    355        
     355
    356356
    357357        points, vertices, boundary = rectangular(4, 4)
    358358        mesh = Mesh(points, vertices, boundary)
    359        
    360 
    361         #Test that points are arranged in a counter clock wise order       
     359
     360
     361        #Test that points are arranged in a counter clock wise order
    362362        mesh.check_integrity()
    363363
     
    369369
    370370        for k in [24, 26, 28, 30]:
    371             assert mesh.boundary[(k,2)] == 'right'           
    372            
     371            assert mesh.boundary[(k,2)] == 'right'
     372
    373373        for k in [7, 15, 23, 31]:
    374374            assert mesh.boundary[(k,1)] == 'top'
     
    377377
    378378
    379        
     379
    380380    def test_rectangular_mesh(self):
    381381        M=4
     
    383383        len1 = 100.0
    384384        len2 = 17.0
    385        
     385
    386386        points, vertices, boundary = rectangular(M, N, len1, len2)
    387387        mesh = Mesh(points, vertices, boundary)
    388388
    389         assert len(mesh) == 2*M*N       
     389        assert len(mesh) == 2*M*N
    390390
    391391        for i in range(len(mesh)):
     
    396396            assert mesh.edgelengths[i, 1] == len1/M #x direction
    397397            assert mesh.edgelengths[i, 2] == len2/N #y direction
    398            
    399         #Test that points are arranged in a counter clock wise order     
    400         mesh.check_integrity()   
     398
     399        #Test that points are arranged in a counter clock wise order
     400        mesh.check_integrity()
    401401
    402402
     
    404404        #Check that integers don't cause trouble
    405405        N = 16
    406        
     406
    407407        points, vertices, boundary = rectangular(2*N, N, len1=10, len2=10)
    408408        mesh = Mesh(points, vertices, boundary)
     
    422422        #bac, bce, ecf, dbe
    423423        vertices = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
    424         mesh = Mesh(points, vertices)       
     424        mesh = Mesh(points, vertices)
    425425        mesh.check_integrity()
    426426
     
    428428        T = mesh
    429429        tid = 0
    430         assert T.number_of_boundaries[tid] == 2   
    431         assert T.surrogate_neighbours[tid, 0] == tid 
    432         assert T.surrogate_neighbours[tid, 1] == 1   
    433         assert T.surrogate_neighbours[tid, 2] == tid 
     430        assert T.number_of_boundaries[tid] == 2
     431        assert T.surrogate_neighbours[tid, 0] == tid
     432        assert T.surrogate_neighbours[tid, 1] == 1
     433        assert T.surrogate_neighbours[tid, 2] == tid
    434434
    435435        tid = 1
    436         assert T.number_of_boundaries[tid] == 0           
     436        assert T.number_of_boundaries[tid] == 0
    437437        assert T.surrogate_neighbours[tid, 0] == 2
    438438        assert T.surrogate_neighbours[tid, 1] == 3
     
    440440
    441441        tid = 2
    442         assert T.number_of_boundaries[tid] == 2           
    443         assert T.surrogate_neighbours[tid, 0] == tid 
    444         assert T.surrogate_neighbours[tid, 1] == tid 
     442        assert T.number_of_boundaries[tid] == 2
     443        assert T.surrogate_neighbours[tid, 0] == tid
     444        assert T.surrogate_neighbours[tid, 1] == tid
    445445        assert T.surrogate_neighbours[tid, 2] == 1
    446446
    447447        tid = 3
    448         assert T.number_of_boundaries[tid] == 2           
    449         assert T.surrogate_neighbours[tid, 0] == 1 
     448        assert T.number_of_boundaries[tid] == 2
     449        assert T.surrogate_neighbours[tid, 0] == 1
    450450        assert T.surrogate_neighbours[tid, 1] == tid
    451451        assert T.surrogate_neighbours[tid, 2] == tid
     
    470470                     (2, 1): 'Fourth',
    471471                     (3, 1): 'Fifth',
    472                      (3, 2): 'Sixth'}                                         
    473                      
    474        
    475         mesh = Mesh(points, vertices, boundary)       
     472                     (3, 2): 'Sixth'}
     473
     474
     475        mesh = Mesh(points, vertices, boundary)
    476476        mesh.check_integrity()
    477477
    478478
    479479        #Check enumeration
    480         #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):       
     480        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
    481481        #    b = -k-1
    482482        #    assert mesh.neighbours[vol_id, edge_id] == b
     
    502502                     (2, 1): 'Fourth',
    503503                     #(3, 1): 'Fifth',  #Skip this
    504                      (3, 2): 'Sixth'}                                         
    505                      
    506        
    507         mesh = Mesh(points, vertices, boundary)       
     504                     (3, 2): 'Sixth'}
     505
     506
     507        mesh = Mesh(points, vertices, boundary)
    508508        mesh.check_integrity()
    509509
     
    513513
    514514        #Check enumeration
    515         #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):       
     515        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
    516516        #    b = -k-1
    517517        #    assert mesh.neighbours[vol_id, edge_id] == b
     
    535535                     (2, 1): 'Fourth',
    536536                     #(3, 1): 'Fifth',  #Skip this
    537                      (3, 2): 'Sixth'}                                         
    538                      
    539        
    540         mesh = Mesh(points, vertices) #, boundary)       
     537                     (3, 2): 'Sixth'}
     538
     539
     540        mesh = Mesh(points, vertices) #, boundary)
    541541        mesh.check_integrity()
    542542
     
    545545        assert mesh.boundary[ (0, 2) ] == default_boundary_tag
    546546        assert mesh.boundary[ (2, 0) ] == default_boundary_tag
    547         assert mesh.boundary[ (2, 1) ] == default_boundary_tag               
     547        assert mesh.boundary[ (2, 1) ] == default_boundary_tag
    548548        assert mesh.boundary[ (3, 1) ] == default_boundary_tag
    549         assert mesh.boundary[ (3, 2) ] == default_boundary_tag               
     549        assert mesh.boundary[ (3, 2) ] == default_boundary_tag
    550550
    551551
    552552        #Check enumeration
    553         #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):       
     553        #for k, (vol_id, edge_id) in enumerate(mesh.boundary_segments):
    554554        #    b = -k-1
    555555        #    assert mesh.neighbours[vol_id, edge_id] == b
     
    575575        #Too few points
    576576        try:
    577             mesh = Mesh([points[0]], vertices)       
     577            mesh = Mesh([points[0]], vertices)
    578578        except AssertionError:
    579579            pass
     
    583583        #Too few points - 1 element
    584584        try:
    585             mesh = Mesh([points[0]], [vertices[0]])       
    586         except AssertionError:
    587             pass
    588         else:
    589             raise 'Should have raised an exception'       
    590        
    591         #Wrong dimension of vertices
    592         try:
    593             mesh = Mesh(points, vertices[0])       
     585            mesh = Mesh([points[0]], [vertices[0]])
    594586        except AssertionError:
    595587            pass
     
    597589            raise 'Should have raised an exception'
    598590
     591        #Wrong dimension of vertices
     592        try:
     593            mesh = Mesh(points, vertices[0])
     594        except AssertionError:
     595            pass
     596        else:
     597            raise 'Should have raised an exception'
     598
    599599        #Unsubscriptable coordinates object raises exception
    600600        try:
    601             mesh = Mesh(points[0], [vertices[0]])       
     601            mesh = Mesh(points[0], [vertices[0]])
    602602        except AssertionError:
    603603            pass
     
    610610        #Not specifying all boundary tags
    611611        #try:
    612         #    mesh = Mesh(points, vertices, {(3,0): 'x'})       
     612        #    mesh = Mesh(points, vertices, {(3,0): 'x'})
    613613        #except AssertionError:
    614614        #    pass
     
    618618        #Specifying wrong non existing segment
    619619        try:
    620             mesh = Mesh(points, vertices, {(5,0): 'x'})       
     620            mesh = Mesh(points, vertices, {(5,0): 'x'})
    621621        except AssertionError:
    622622            pass
     
    634634        from shallow_water import Domain
    635635        from Numeric import zeros, Float
    636        
     636
    637637        #Create basic mesh
    638638        points, vertices, boundary = rectangular(1, 3)
     
    648648                                                 'all':[0,1,2,3,4,5]})
    649649
    650        
     650
    651651    def test_boundary_polygon(self):
    652652        from mesh_factory import rectangular
     
    654654        from Numeric import zeros, Float
    655655        from util import inside_polygon
    656        
     656
    657657        #Create basic mesh
    658658        points, vertices, boundary = rectangular(2, 2)
    659659        mesh = Mesh(points, vertices, boundary)
    660        
     660
    661661
    662662        P = mesh.get_boundary_polygon()
     
    668668        for p in points:
    669669            #print p, P
    670             assert inside_polygon(p, P) 
     670            assert inside_polygon(p, P)
    671671
    672672
     
    675675        from Numeric import zeros, Float
    676676        from util import inside_polygon
    677        
     677
    678678        #Points
    679679        a = [0.0, 0.0] #0
     
    695695
    696696        mesh = Mesh(points, vertices)
    697        
    698         mesh.check_integrity()
    699        
     697
     698        mesh.check_integrity()
     699
    700700        P = mesh.get_boundary_polygon()
    701701
     
    705705        for p in points:
    706706            #print p, P
    707             assert inside_polygon(p, P) 
     707            assert inside_polygon(p, P)
    708708
    709709
     
    711711        """Same as II but vertices ordered differently
    712712        """
    713        
     713
    714714        from mesh import Mesh
    715715        from Numeric import zeros, Float
    716716        from util import inside_polygon
    717        
     717
    718718        #Points
    719719        a = [0.0, 0.0] #0
     
    738738        mesh.check_integrity()
    739739
    740        
     740
    741741        P = mesh.get_boundary_polygon()
    742742
     
    745745
    746746        for p in points:
    747             assert inside_polygon(p, P) 
    748 
    749 
    750        
     747            assert inside_polygon(p, P)
     748
     749
     750
    751751#-------------------------------------------------------------
    752752if __name__ == "__main__":
    753     suite = unittest.makeSuite(TestCase,'test')
     753    suite = unittest.makeSuite(Test_Mesh,'test')
    754754    runner = unittest.TextTestRunner()
    755755    runner.run(suite)
    756756
    757    
    758    
    759 
    760 
    761 
     757
     758
     759
     760
  • inundation/ga/storm_surge/pyvolution/test_pmesh2domain.py

    r969 r1018  
    2323     Transmissive_boundary
    2424
    25        
    26 class TestCase(unittest.TestCase):
     25
     26class Test_pmesh2domain(unittest.TestCase):
    2727
    2828    def setUp(self):
    2929        pass
    30        
     30
    3131    def tearDown(self):
    3232        pass
    33                
     33
    3434    def test_pmesh2Domain(self):
    3535         import os
    3636         import tempfile
    37        
     37
    3838         fileName = tempfile.mktemp(".tsh")
    3939         file = open(fileName,"w")
     
    66660 # <x> <y> <attribute>...Mesh Regions... \n")
    6767         file.close()
    68        
     68
    6969         tags = {}
    7070         b1 =  Dirichlet_boundary(conserved_quantities = array([0.0]))
     
    7474         tags["2"] = b2
    7575         tags["3"] = b3
    76          
     76
    7777         domain = pmesh_to_domain_instance(fileName, Domain)
    7878         os.remove(fileName)
    7979
    80          ## check the quantities       
     80         ## check the quantities
    8181         #print domain.quantities['elevation'].vertex_values
    8282         answer = [[0., 8., 0.],
    8383                   [0., 10., 8.]]
    8484         assert allclose(domain.quantities['elevation'].vertex_values,
    85                         answer) 
    86          
     85                        answer)
     86
    8787         #print domain.quantities['stage'].vertex_values
    8888         answer = [[0., 12., 10.],
     
    9090         assert allclose(domain.quantities['stage'].vertex_values,
    9191                        answer)
    92          
     92
    9393         #print domain.quantities['friction'].vertex_values
    9494         answer = [[0.01, 0.04, 0.03],
     
    100100         assert allclose(domain.tagged_elements['dsg'][0],0)
    101101         assert allclose(domain.tagged_elements['ole nielsen'][0],1)
    102          
     102
    103103         self.failUnless( domain.boundary[(1, 0)]  == '1',
    104104                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
     
    123123         meshDict['triangle_tags'] = [6.6,6.6]
    124124         meshDict['triangle_neighbors'] = [[-1,-1,1],[-1,0,-1]]
    125          meshDict['segments'] = [[1,0],[0,2],[2,3],[3,1]] 
     125         meshDict['segments'] = [[1,0],[0,2],[2,3],[3,1]]
    126126         meshDict['segment_tags'] = [2,3,1,1]
    127        
     127
    128128         domain = Domain.pmesh_dictionary_to_domain(meshDict)
    129129
     
    143143         boundary_value = Boundary_value.instances[id]
    144144         boundary_obj = boundary_value.boundary_object
    145          
     145
    146146         self.failUnless( boundary_obj  == b1,
    147147                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
    148          
     148
    149149         inverted_id = Volume.instances[0].neighbours[1]
    150150         id = -(inverted_id+1)
    151151         boundary_value = Boundary_value.instances[id]
    152          boundary_obj = boundary_value.boundary_object   
     152         boundary_obj = boundary_value.boundary_object
    153153         self.failUnless( boundary_obj  == b3,
    154154                          "test_tags_to_boundaries  failed. Single boundary wasn't added.")
     
    156156#-------------------------------------------------------------
    157157if __name__ == "__main__":
    158     suite = unittest.makeSuite(TestCase, 'test')
     158    suite = unittest.makeSuite(Test_pmesh2domain, 'test')
    159159    runner = unittest.TextTestRunner()
    160160    runner.run(suite)
    161    
    162 
    163    
    164161
    165162
    166163
     164
     165
  • inundation/ga/storm_surge/pyvolution/test_quad.py

    r707 r1018  
    99#-------------------------------------------------------------
    1010
    11 class TestCase(unittest.TestCase):
     11class Test_Quad(unittest.TestCase):
    1212
    1313    def setUp(self):
    1414        self.cell = Cell(100, 140, 0, 40, 'cell')
    15        
     15
    1616        a = [3, 107]
    1717        b = [5, 107]
     
    2424
    2525        points = [a, b, c, d, e, f, g, h]
    26         #bac, bce, ecf, dbe, daf, dae 
    27         vertices = [[1,0,2], [1,3,4], [1,2,3], [5,4,7], [4,6,7]] 
     26        #bac, bce, ecf, dbe, daf, dae
     27        vertices = [[1,0,2], [1,3,4], [1,2,3], [5,4,7], [4,6,7]]
    2828
    2929        mesh = Mesh(points, vertices)
    3030        self.mesh = mesh
    3131        Cell.initialise(mesh)
    32        
     32
    3333    def tearDown(self):
    3434        pass
     
    3737        self.cell.insert(0)
    3838        self.cell.insert(1)
    39        
     39
    4040        result = self.cell.retrieve()
    4141        assert type(result) in [types.ListType,types.TupleType],\
    42                                 'should be a list'       
     42                                'should be a list'
    4343        self.assertEqual(len(result),2)
    44        
     44
    4545    def test_add_points_2_cellII(self):
    4646        self.cell.insert([0,1,2,3,4,5,6,7])
    47        
     47
    4848        result = self.cell.retrieve()
    4949        assert type(result) in [types.ListType,types.TupleType],\
    50                                 'should be a list'       
     50                                'should be a list'
    5151        self.assertEqual(len(result),8)
    5252
     
    5555        self.cell.insert([0,1,2,3,4,5,6,7])
    5656        self.cell.split(4)
    57        
     57
    5858        result =  self.cell.search(x = 1, y = 101)
    5959        assert type(result) in [types.ListType,types.TupleType],\
    60                                 'should be a list'       
     60                                'should be a list'
    6161        self.assertEqual(result, [0,1,2,3])
    62        
    63        
     62
     63
    6464    def test_clear_1(self):
    6565        self.cell.insert([0,1,2,3,4,5,6,7])
    66         assert self.cell.count() == 8   
     66        assert self.cell.count() == 8
    6767        self.cell.clear()
    68        
     68
    6969        #This one actually revealed a bug :-)
    70         assert self.cell.count() == 0   
    71                
     70        assert self.cell.count() == 0
     71
    7272    def test_clear_2(self):
    7373        self.cell.insert([0,1,2,3,4,5,6,7])
    74         assert self.cell.count() == 8   
     74        assert self.cell.count() == 8
    7575        self.cell.split(2)
    76         assert self.cell.count() == 8           
    77                
     76        assert self.cell.count() == 8
     77
    7878        self.cell.clear()
    79         assert self.cell.count() == 0   
    80        
    81        
    82        
     79        assert self.cell.count() == 0
     80
     81
     82
    8383    def test_split(self):
    84         self.cell.insert([0,1,2,3,4,5,6,7], split = False)   
    85        
     84        self.cell.insert([0,1,2,3,4,5,6,7], split = False)
     85
    8686        #No children yet
    87         assert self.cell.children is None 
     87        assert self.cell.children is None
    8888        assert self.cell.count() == 8
    8989
     
    9292        #self.cell.show()
    9393        #self.cell.show_all()
    94        
    95        
     94
     95
    9696        #Now there are children
    97         assert self.cell.children is not None 
    98         assert self.cell.count() == 8   
    99        
    100        
    101                
     97        assert self.cell.children is not None
     98        assert self.cell.count() == 8
     99
     100
     101
    102102    def test_collapse(self):
    103         self.cell.insert([0,1,2,3,4,5,6,7], split = False)   
    104        
     103        self.cell.insert([0,1,2,3,4,5,6,7], split = False)
     104
    105105        #Split maximally
    106106        self.cell.split(1)
    107        
     107
    108108        #Now there are children
    109         assert self.cell.children is not None 
    110         assert self.cell.count() == 8   
    111        
     109        assert self.cell.children is not None
     110        assert self.cell.count() == 8
     111
    112112        #Collapse
    113113        self.cell.collapse(8)
    114        
     114
    115115        #No children
    116         assert self.cell.children is None 
    117         assert self.cell.count() == 8   
     116        assert self.cell.children is None
     117        assert self.cell.count() == 8
    118118
    119119    def test_build_quadtree(self):
     
    123123
    124124        #Q.show()
    125        
     125
    126126        result = Q.search(3, 105)
    127127        assert type(result) in [types.ListType,types.TupleType],\
     
    130130        self.assertEqual(result, [0,1,2,3])
    131131
    132      
     132
    133133    def test_build_quadtreeII(self):
    134134
    135135        self.cell = Cell(100, 140, 0, 40, 'cell')
    136        
     136
    137137        p0 = [34.6292076111,-7999.92529297]
    138138        p1 = [8000.0, 7999.0]
     
    141141
    142142        points = [p0,p1,p2, p3]
    143         #bac, bce, ecf, dbe, daf, dae 
     143        #bac, bce, ecf, dbe, daf, dae
    144144        vertices = [[0,1,2],[0,2,3]]
    145145
     
    148148        #This was causing round off error
    149149        Q = build_quadtree(mesh)
    150        
     150
    151151#-------------------------------------------------------------
    152152if __name__ == "__main__":
    153153
    154     mysuite = unittest.makeSuite(TestCase,'test')
     154    mysuite = unittest.makeSuite(Test_Sparse,'test')
    155155    runner = unittest.TextTestRunner()
    156156    runner.run(mysuite)
    157 
  • inundation/ga/storm_surge/pyvolution/test_quantity.py

    r1011 r1018  
    99from Numeric import allclose, array, ones, Float
    1010
    11        
    12 class TestCase(unittest.TestCase):
     11
     12class Test_Quantity(unittest.TestCase):
    1313    def setUp(self):
    1414        from domain import Domain
    15        
     15
    1616        a = [0.0, 0.0]
    1717        b = [0.0, 2.0]
     
    2626        elements = [ [1,0,2], [1,2,4], [4,2,5], [3,1,4] ]
    2727
    28         self.mesh1 = Domain(points[:3], [elements[0]])       
     28        self.mesh1 = Domain(points[:3], [elements[0]])
    2929        self.mesh1.check_integrity()
    30        
    31         self.mesh4 = Domain(points, elements)       
     30
     31        self.mesh4 = Domain(points, elements)
    3232        self.mesh4.check_integrity()
    33        
     33
    3434    def tearDown(self):
    3535        pass
     
    3838
    3939    def test_creation(self):
    40        
     40
    4141        quantity = Quantity(self.mesh1, [[1,2,3]])
    4242        assert allclose(quantity.vertex_values, [[1.,2.,3.]])
     
    5555            pass
    5656        except:
    57             raise 'Should have raised "mising mesh object" error'       
    58        
     57            raise 'Should have raised "mising mesh object" error'
     58
    5959
    6060    def test_creation_zeros(self):
    61        
     61
    6262        quantity = Quantity(self.mesh1)
    6363        assert allclose(quantity.vertex_values, [[0.,0.,0.]])
     
    6666        quantity = Quantity(self.mesh4)
    6767        assert allclose(quantity.vertex_values, [[0.,0.,0.], [0.,0.,0.],
    68                                                  [0.,0.,0.], [0.,0.,0.]])       
    69 
    70        
     68                                                 [0.,0.,0.], [0.,0.,0.]])
     69
     70
    7171    def test_interpolation(self):
    7272        quantity = Quantity(self.mesh1, [[1,2,3]])
    7373        assert allclose(quantity.centroid_values, [2.0]) #Centroid
    7474
    75         assert allclose(quantity.edge_values, [[2.5, 2.0, 1.5]]) 
     75        assert allclose(quantity.edge_values, [[2.5, 2.0, 1.5]])
    7676
    7777
     
    8888                                               [7.5, 0.5, 1.],
    8989                                               [-5, -2.5, 7.5]])
    90        
    91         #print quantity.edge_values       
     90
     91        #print quantity.edge_values
    9292        assert allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
    9393                                               [5., 5., 5.],
     
    120120        quantity.set_values([[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
    121121        assert allclose(quantity.vertex_values,
    122                         [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])       
     122                        [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
    123123        assert allclose(quantity.centroid_values, [2., 5., 3., 0.]) #Centroid
    124124        assert allclose(quantity.edge_values, [[2.5, 2.0, 1.5],
     
    135135                            location = 'edges')
    136136        assert allclose(quantity.edge_values,
    137                         [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])       
     137                        [[1,2,3], [5,5,5], [0,0,9], [-6, 3, 3]])
    138138
    139139        #Test exceptions
     
    174174                                               [3, 3, 3],
    175175                                               [3, 3, 3],
    176                                                [3, 3, 3]])       
     176                                               [3, 3, 3]])
    177177
    178178
     
    186186        #print "quantity.vertex_values",quantity.vertex_values
    187187        assert allclose(quantity.vertex_values,
    188                         [[2,0,2], [2,2,4], [4,2,4], [4,2,4]])       
     188                        [[2,0,2], [2,2,4], [4,2,4], [4,2,4]])
    189189        assert allclose(quantity.centroid_values,
    190190                        [4.0/3, 8.0/3, 10.0/3, 10.0/3])
    191191        assert allclose(quantity.edge_values,
    192                         [[1,2,1], [3,3,2], [3,4,3], [3,4,3]])               
    193 
    194        
     192                        [[1,2,1], [3,3,2], [3,4,3], [3,4,3]])
     193
     194
    195195        quantity.set_values(f, location = 'centroids')
    196196        assert allclose(quantity.centroid_values,
     
    201201        quantity = Quantity(self.mesh4)
    202202
    203         #Try constants first   
     203        #Try constants first
    204204        const = 5
    205         quantity.set_values(const, location = 'vertices')       
     205        quantity.set_values(const, location = 'vertices')
    206206        #print 'Q', quantity.get_integral()
    207                
    208         assert allclose(quantity.get_integral(), 
     207
     208        assert allclose(quantity.get_integral(),
    209209                        self.mesh4.get_area() * const)
    210        
     210
    211211        #Try with a linear function
    212212        def f(x, y):
     
    214214
    215215        quantity.set_values(f, location = 'vertices')
    216        
    217        
     216
     217
    218218        ref_integral = (4.0/3 + 8.0/3 + 10.0/3 + 10.0/3) * 2
    219        
    220         assert allclose (quantity.get_integral(), ref_integral) 
     219
     220        assert allclose (quantity.get_integral(), ref_integral)
    221221
    222222
     
    256256        #Centroid
    257257        assert allclose(quantity.centroid_values, [1., 7./3, 11./3, 8./3])
    258        
     258
    259259        assert allclose(quantity.edge_values, [[1., 1.5, 0.5],
    260260                                               [3., 2.5, 1.5],
     
    268268        quantity = Conserved_quantity(self.mesh4)
    269269
    270         #Set up for a gradient of (3,0) at mid triangle 
     270        #Set up for a gradient of (3,0) at mid triangle
    271271        quantity.set_values([2.0, 4.0, 8.0, 2.0],
    272272                            location = 'centroids')
     
    294294                                                 [0., 0.,  6.]])
    295295
    296                
     296
    297297    def test_second_order_extrapolation2(self):
    298         quantity = Conserved_quantity(self.mesh4)       
     298        quantity = Conserved_quantity(self.mesh4)
    299299
    300300        #Set up for a gradient of (3,1), f(x) = 3x+y
    301301        quantity.set_values([2.0+2.0/3, 4.0+4.0/3, 8.0+2.0/3, 2.0+8.0/3],
    302302                            location = 'centroids')
    303        
     303
    304304        #Gradients
    305305        a, b = quantity.compute_gradients()
     
    314314
    315315        quantity.extrapolate_second_order()
    316        
     316
    317317        #print quantity.vertex_values
    318318        assert allclose(quantity.vertex_values[1,0], 2.0)
    319         assert allclose(quantity.vertex_values[1,1], 6.0)       
     319        assert allclose(quantity.vertex_values[1,1], 6.0)
    320320        assert allclose(quantity.vertex_values[1,2], 8.0)
    321321
     
    323323
    324324    def test_first_order_extrapolator(self):
    325         quantity = Conserved_quantity(self.mesh4)               
     325        quantity = Conserved_quantity(self.mesh4)
    326326
    327327        #Test centroids
     
    338338
    339339    def test_second_order_extrapolator(self):
    340         quantity = Conserved_quantity(self.mesh4)                       
    341 
    342         #Set up for a gradient of (3,0) at mid triangle 
     340        quantity = Conserved_quantity(self.mesh4)
     341
     342        #Set up for a gradient of (3,0) at mid triangle
    343343        quantity.set_values([2.0, 4.0, 8.0, 2.0],
    344344                            location = 'centroids')
    345        
     345
    346346
    347347
     
    353353        assert quantity.vertex_values[1,0] >= quantity.vertex_values[0,0]
    354354        assert quantity.vertex_values[1,0] >= quantity.vertex_values[3,1]
    355        
     355
    356356        assert quantity.vertex_values[1,1] <= quantity.vertex_values[2,1]
    357357        assert quantity.vertex_values[1,1] >= quantity.vertex_values[0,2]
    358        
     358
    359359        assert quantity.vertex_values[1,2] <= quantity.vertex_values[2,0]
    360360        assert quantity.vertex_values[1,2] >= quantity.vertex_values[3,1]
    361361
    362        
     362
    363363        #Assert that quantities are conserved
    364364        from Numeric import sum
     
    366366            assert allclose (quantity.centroid_values[k],
    367367                             sum(quantity.vertex_values[k,:])/3)
    368        
    369        
    370 
    371        
     368
     369
     370
     371
    372372
    373373    def test_limiter(self):
     
    384384        assert quantity.vertex_values[1,0] >= quantity.vertex_values[0,0]
    385385        assert quantity.vertex_values[1,0] <= quantity.vertex_values[3,1]
    386        
     386
    387387        assert quantity.vertex_values[1,1] <= quantity.vertex_values[2,1]
    388388        assert quantity.vertex_values[1,1] >= quantity.vertex_values[0,2]
    389        
     389
    390390        assert quantity.vertex_values[1,2] <= quantity.vertex_values[2,0]
    391391        assert quantity.vertex_values[1,2] <= quantity.vertex_values[3,1]
    392392
    393393
    394        
     394
    395395        #Assert that quantities are conserved
    396396        from Numeric import sum
     
    398398            assert allclose (quantity.centroid_values[k],
    399399                             sum(quantity.vertex_values[k,:])/3)
    400        
     400
    401401
    402402    def test_limiter2(self):
     
    418418        quantity.limit()
    419419
    420        
     420
    421421        assert allclose(quantity.vertex_values[1,:], [2.2, 4.9, 4.9])
    422        
     422
    423423
    424424        #Assert that quantities are conserved
     
    429429
    430430
    431        
     431
    432432
    433433
    434434    def test_distribute_first_order(self):
    435         quantity = Conserved_quantity(self.mesh4)       
     435        quantity = Conserved_quantity(self.mesh4)
    436436
    437437        #Test centroids
     
    444444
    445445        #Interpolate
    446         quantity.interpolate_from_vertices_to_edges()       
     446        quantity.interpolate_from_vertices_to_edges()
    447447
    448448        assert allclose(quantity.vertex_values,
     
    453453
    454454    def test_distribute_second_order(self):
    455         quantity = Conserved_quantity(self.mesh4)       
     455        quantity = Conserved_quantity(self.mesh4)
    456456
    457457        #Test centroids
     
    498498        sem = array([1.,1.,1.,1.])/array([1, 2, 3, 4])
    499499        denom = ones(4, Float)-timestep*sem
    500        
     500
    501501        x = array([1, 2, 3, 4])/denom
    502502        assert allclose( quantity.centroid_values, x)
     
    512512        #Set explicit_update
    513513        quantity.explicit_update = array( [4.,3.,2.,1.] )
    514        
     514
    515515        #Set semi implicit update
    516516        quantity.semi_implicit_update = array( [1.,1.,1.,1.] )
    517517
    518518        #Update with given timestep
    519         timestep = 0.1       
     519        timestep = 0.1
    520520        quantity.update(0.1)
    521521
     
    525525        x = array([1, 2, 3, 4]) + array( [.4,.3,.2,.1] )
    526526        x /= denom
    527         assert allclose( quantity.centroid_values, x)       
    528 
    529        
    530 
    531 
    532     #Test smoothing   
     527        assert allclose( quantity.centroid_values, x)
     528
     529
     530
     531
     532    #Test smoothing
    533533    def test_smoothing(self):
    534534
     
    546546        domain.reduction = mean
    547547
    548        
     548
    549549        #Set some field values
    550         domain.set_quantity('elevation', lambda x,y: x)       
     550        domain.set_quantity('elevation', lambda x,y: x)
    551551        domain.set_quantity('friction', 0.03)
    552552
    553553
    554         ###################### 
     554        ######################
    555555        # Boundary conditions
    556556        B = Transmissive_boundary(domain)
    557557        domain.set_boundary( {'left': B, 'right': B, 'top': B, 'bottom': B})
    558        
    559 
    560         ###################### 
     558
     559
     560        ######################
    561561        #Initial condition - with jumps
    562562
     
    566566        h = 0.03
    567567        for i in range(stage.shape[0]):
    568             if i % 2 == 0:           
     568            if i % 2 == 0:
    569569                stage[i,:] = bed[i,:] + h
    570570            else:
    571571                stage[i,:] = bed[i,:]
    572                
     572
    573573        domain.set_quantity('stage', stage)
    574574
     
    579579        Q = stage.vertex_values
    580580
    581        
    582         assert A.shape[0] == 9 
    583         assert V.shape[0] == 8 
    584         assert V.shape[1] == 3                 
    585        
    586         #First four points 
    587         assert allclose(A[0], (Q[0,2] + Q[1,1])/2) 
     581
     582        assert A.shape[0] == 9
     583        assert V.shape[0] == 8
     584        assert V.shape[1] == 3
     585
     586        #First four points
     587        assert allclose(A[0], (Q[0,2] + Q[1,1])/2)
    588588        assert allclose(A[1], (Q[1,0] + Q[3,1] + Q[2,2])/3)
    589589        assert allclose(A[2], Q[3,0])
     
    593593        assert allclose(A[4], (Q[0,1] + Q[1,2] + Q[2,0] +\
    594594                               Q[5,0] + Q[6,2] + Q[7,1])/6)
    595                                  
     595
    596596
    597597        #Check V
    598598        assert allclose(V[0,:], [3,4,0])
    599599        assert allclose(V[1,:], [1,0,4])
    600         assert allclose(V[2,:], [4,5,1])                       
     600        assert allclose(V[2,:], [4,5,1])
    601601        assert allclose(V[3,:], [2,1,5])
    602         assert allclose(V[4,:], [6,7,3])       
     602        assert allclose(V[4,:], [6,7,3])
    603603        assert allclose(V[5,:], [4,3,7])
    604604        assert allclose(V[6,:], [7,8,4])
    605         assert allclose(V[7,:], [5,4,8])                       
     605        assert allclose(V[7,:], [5,4,8])
    606606
    607607        #Get smoothed stage with XY
     
    609609
    610610        assert allclose(A, A1)
    611         assert allclose(V, V1)       
     611        assert allclose(V, V1)
    612612
    613613        #Check XY
     
    616616
    617617        assert allclose(X[7], 1.0)
    618         assert allclose(Y[7], 0.5)                 
     618        assert allclose(Y[7], 0.5)
    619619
    620620
     
    628628        from util import mean
    629629
    630        
     630
    631631        #Create basic mesh
    632632        points, vertices, boundary = rectangular(2, 2)
     
    637637        domain.reduction = mean
    638638
    639        
     639
    640640        #Set some field values
    641         domain.set_quantity('elevation', lambda x,y: x)       
     641        domain.set_quantity('elevation', lambda x,y: x)
    642642        domain.set_quantity('friction', 0.03)
    643643
    644644
    645         ###################### 
     645        ######################
    646646        #Initial condition - with jumps
    647647
     
    651651        h = 0.03
    652652        for i in range(stage.shape[0]):
    653             if i % 2 == 0:           
     653            if i % 2 == 0:
    654654                stage[i,:] = bed[i,:] + h
    655655            else:
    656656                stage[i,:] = bed[i,:]
    657                
     657
    658658        domain.set_quantity('stage', stage)
    659659
    660660        #Get stage
    661         stage = domain.quantities['stage']       
     661        stage = domain.quantities['stage']
    662662        A, V = stage.get_vertex_values(xy=False, smooth=False)
    663663        Q = stage.vertex_values.flat
     
    666666            assert allclose(A[k], Q[k])
    667667
    668            
     668
    669669        for k in range(8):
    670670            assert V[k, 0] == 3*k
    671671            assert V[k, 1] == 3*k+1
    672             assert V[k, 2] == 3*k+2           
    673            
     672            assert V[k, 2] == 3*k+2
     673
    674674
    675675
    676676        X, Y, A1, V1 = stage.get_vertex_values(xy=True, smooth=False)
    677677
    678        
     678
    679679        assert allclose(A, A1)
    680         assert allclose(V, V1)       
     680        assert allclose(V, V1)
    681681
    682682        #Check XY
     
    686686        assert allclose(Y[4], 0.0)
    687687        assert allclose(X[12], 1.0)
    688         assert allclose(Y[12], 0.0)               
    689        
    690        
    691  
     688        assert allclose(Y[12], 0.0)
     689
     690
     691
    692692    def set_array_values_by_index(self):
    693693
     
    695695        from shallow_water import Domain
    696696        from Numeric import zeros, Float
    697        
     697
    698698        #Create basic mesh
    699699        points, vertices, boundary = rectangular(1, 1)
     
    701701        #Create shallow water domain
    702702        domain = Domain(points, vertices, boundary)
    703         #print "domain.number_of_elements ",domain.number_of_elements 
     703        #print "domain.number_of_elements ",domain.number_of_elements
    704704        quantity = Quantity(domain,[[1,1,1],[2,2,2]])
    705705        value = [7]
     
    709709                                           indexes = indexes)
    710710        #print "quantity.centroid_values",quantity.centroid_values
    711        
     711
    712712        assert allclose(quantity.centroid_values, [1,7])
    713713
     
    717717        quantity.set_array_values([15,20,25], indexes = indexes)
    718718        assert allclose(quantity.centroid_values, [1,20])
    719        
     719
    720720    def test_setting_some_vertex_values(self):
    721721        """
     
    725725        from shallow_water import Domain
    726726        from Numeric import zeros, Float
    727        
     727
    728728        #Create basic mesh
    729729        points, vertices, boundary = rectangular(1, 3)
     
    731731        #Create shallow water domain
    732732        domain = Domain(points, vertices, boundary)
    733         #print "domain.number_of_elements ",domain.number_of_elements 
     733        #print "domain.number_of_elements ",domain.number_of_elements
    734734        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
    735735                                    [4,4,4],[5,5,5],[6,6,6]])
     
    741741        #print "quantity.centroid_values",quantity.centroid_values
    742742        assert allclose(quantity.centroid_values, [1,7,3,4,5,6])
    743        
     743
    744744        value = [[15,20,25]]
    745745        quantity.set_values(value, indexes = indexes)
     
    758758        assert allclose(quantity.centroid_values, [10,100,3,4,5,50])
    759759
    760        
     760
    761761        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
    762762                                    [4,4,4],[5,5,5],[6,6,6]])
     
    764764        #this will be per unique vertex, indexing the vertices
    765765        #print "quantity.vertex_values",quantity.vertex_values
    766         quantity.set_values(values, indexes = [0,1,5]) 
     766        quantity.set_values(values, indexes = [0,1,5])
    767767        #print "quantity.vertex_values",quantity.vertex_values
    768768        assert allclose(quantity.vertex_values[0], [1,50,10])
     
    780780                                    [4,4,4],[5,5,5],[6,6,6]]
    781781        quantity.set_values(values)
    782        
     782
    783783        # testing the standard set values by vertex
    784784        # indexed by vertex_id in general_mesh.coordinates
    785785        values = [0,1,2,3,4,5,6,7]
    786        
     786
    787787        quantity.set_values(values)
    788788        #print "1 quantity.vertex_values",quantity.vertex_values
     
    793793                                                [ 6.,  7.,  2.],
    794794                                                [ 3.,  2.,  7.]])
    795    
     795
    796796    def test_setting_unique_vertex_values(self):
    797797        """
     
    801801        from shallow_water import Domain
    802802        from Numeric import zeros, Float
    803        
     803
    804804        #Create basic mesh
    805805        points, vertices, boundary = rectangular(1, 3)
     
    807807        #Create shallow water domain
    808808        domain = Domain(points, vertices, boundary)
    809         #print "domain.number_of_elements ",domain.number_of_elements 
     809        #print "domain.number_of_elements ",domain.number_of_elements
    810810        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
    811811                                    [4,4,4],[5,5,5]])
     
    819819        assert allclose(quantity.vertex_values[1], [7,1,7])
    820820        assert allclose(quantity.vertex_values[2], [7,2,7])
    821        
    822    
     821
     822
    823823    def test_get_values(self):
    824824        """
     
    828828        from shallow_water import Domain
    829829        from Numeric import zeros, Float
    830        
     830
    831831        #Create basic mesh
    832832        points, vertices, boundary = rectangular(1, 3)
     
    838838        #Create shallow water domain
    839839        domain = Domain(points, vertices, boundary)
    840         #print "domain.number_of_elements ",domain.number_of_elements 
     840        #print "domain.number_of_elements ",domain.number_of_elements
    841841        quantity = Quantity(domain,[[0,0,0],[1,1,1],[2,2,2],[3,3,3],
    842842                                    [4,4,4],[5,5,5]])
    843        
     843
    844844        #print "quantity.get_values(location = 'unique vertices')", \
    845845        #      quantity.get_values(location = 'unique vertices')
     
    848848        #      quantity.get_values(indexes=[0,1,2,3,4,5,6,7], \
    849849        #                          location = 'unique vertices')
    850        
     850
    851851        answer = [0.5,2,4,5,0,1,3,4.5]
    852852        assert allclose(answer,
    853853                        quantity.get_values(location = 'unique vertices'))
    854        
     854
    855855        indexes = [0,5,3]
    856856        answer = [0.5,1,5]
     
    861861        #print "quantity.get_values(location = 'centroids') ",\
    862862        #      quantity.get_values(location = 'centroids')
    863        
     863
    864864    def test_getting_some_vertex_values(self):
    865865        """
     
    869869        from shallow_water import Domain
    870870        from Numeric import zeros, Float
    871        
     871
    872872        #Create basic mesh
    873873        points, vertices, boundary = rectangular(1, 3)
     
    879879        #Create shallow water domain
    880880        domain = Domain(points, vertices, boundary)
    881         #print "domain.number_of_elements ",domain.number_of_elements 
     881        #print "domain.number_of_elements ",domain.number_of_elements
    882882        quantity = Quantity(domain,[[1,1,1],[2,2,2],[3,3,3],
    883883                                    [4,4,4],[5,5,5],[6,6,6]])
     
    893893                        quantity.get_values(location = 'centroids'))
    894894
    895        
     895
    896896        value = [[15,20,25]]
    897897        quantity.set_values(value, indexes = indexes)
     
    902902                        quantity.get_values(location = 'edges'))
    903903
    904         # get a subset of elements 
     904        # get a subset of elements
    905905        subset = quantity.get_values(location='centroids', indexes=[0,5])
    906906        answer = [quantity.centroid_values[0],quantity.centroid_values[5]]
     
    920920        assert allclose(subset, answer)
    921921
    922        
    923        
     922
     923
    924924#-------------------------------------------------------------
    925925if __name__ == "__main__":
    926     suite = unittest.makeSuite(TestCase,'test')
     926    suite = unittest.makeSuite(Test_Quantity,'test')
    927927    #print "restricted test"
    928     #suite = unittest.makeSuite(TestCase,'test_set_vertex_values_subset')
     928    #suite = unittest.makeSuite(Test_Quantity,'test_set_vertex_values_subset')
    929929    runner = unittest.TextTestRunner()
    930930    runner.run(suite)
    931931
    932 
  • inundation/ga/storm_surge/pyvolution/test_region.py

    r773 r1018  
    1212def add_x_y(x, y):
    1313    return x+y
    14        
    15 class TestCase(unittest.TestCase):
     14
     15class Test_Region(unittest.TestCase):
    1616    def setUp(self):
    1717        pass
    1818
    19        
     19
    2020    def tearDown(self):
    2121        pass
     
    2929        from shallow_water import Domain
    3030        from Numeric import zeros, Float
    31        
     31
    3232        #Create basic mesh
    3333        points, vertices, boundary = rectangular(1, 3)
    34        
     34
    3535        #Create shallow water domain
    3636        domain = Domain(points, vertices, boundary)
     
    3939                                                 'all':[0,1,2,3,4,5]})
    4040
    41        
     41
    4242        #Set friction
    4343        manning = 0.07
     
    6666                         [ 11.0,  11.0,  11.0],
    6767                         [ 11.0,  11.0,  11.0]])
    68                          
    69         # trying a function                 
     68
     69        # trying a function
    7070        domain.set_region(Set_region('top', 'friction', add_x_y))
    7171        #print domain.quantities['friction'].get_values()
     
    7777                         [ 5./3,  2.0,  2./3],
    7878                         [ 1.0,  2./3,  2.0]])
    79                          
     79
    8080        domain.set_quantity('elevation', 10.0)
    8181        domain.set_quantity('stage', 10.0)
     
    8989                         [ 11.0,  11.0,  11.0],
    9090                         [ 11.0,  11.0,  11.0]])
    91    
     91
    9292    def test_unique_vertices(self):
    9393        """
     
    9797        from shallow_water import Domain
    9898        from Numeric import zeros, Float
    99        
     99
    100100        #Create basic mesh
    101101        points, vertices, boundary = rectangular(1, 3)
    102        
     102
    103103        #Create shallow water domain
    104104        domain = Domain(points, vertices, boundary)
     
    106106                                                 'top':[4,5],
    107107                                                 'all':[0,1,2,3,4,5]})
    108      
     108
    109109        #Set friction
    110110        manning = 0.07
     
    122122                         [ 0.07,  0.07,  0.07]])
    123123
    124        
     124
    125125    def test_unique_verticesII(self):
    126126        """
     
    130130        from shallow_water import Domain
    131131        from Numeric import zeros, Float
    132        
     132
    133133        #Create basic mesh
    134134        points, vertices, boundary = rectangular(1, 3)
    135        
     135
    136136        #Create shallow water domain
    137137        domain = Domain(points, vertices, boundary)
     
    139139                                                 'top':[4,5],
    140140                                                 'all':[0,1,2,3,4,5]})
    141      
     141
    142142        #Set friction
    143143        manning = 0.07
     
    145145
    146146        domain.set_region(Add_value_to_region('bottom', 'friction', 1.0,initial_quantity='friction', location = 'unique vertices'))
    147        
     147
    148148        #print domain.quantities['friction'].get_values()
    149149        assert allclose(domain.quantities['friction'].get_values(),\
     
    156156#-------------------------------------------------------------
    157157if __name__ == "__main__":
    158     suite = unittest.makeSuite(TestCase,'test')
     158    suite = unittest.makeSuite(Test_Region,'test')
    159159    runner = unittest.TextTestRunner()
    160160    runner.run(suite)
  • inundation/ga/storm_surge/pyvolution/test_sparse.py

    r599 r1018  
    55
    66from sparse import *
    7 from Numeric import allclose, array, transpose, Float 
    8        
    9 class TestCase(unittest.TestCase):
     7from Numeric import allclose, array, transpose, Float
     8
     9class Test_Sparse(unittest.TestCase):
    1010
    1111    def setUp(self):
    1212        pass
    13        
     13
    1414    def tearDown(self):
    1515        pass
     
    1717    def test_init1(Self):
    1818        """Test initialisation from dimensions
    19         """       
     19        """
    2020        A = Sparse(3,3)
    2121        A[1,1] = 4
     
    2626                    assert A[i,j] == 4.0
    2727                else:
    28                     assert A[i,j] == 0.0                   
    29                    
     28                    assert A[i,j] == 0.0
     29
    3030    def test_init2(Self):
    3131        """Test initialisation from dense matrix
    3232        """
    33        
     33
    3434        A = Sparse(4,3)
    3535        A[1,1] = 4
     
    3737        A[0,1] = 13
    3838        A[0,2] = -6
    39         A[2,2] = 1                       
     39        A[2,2] = 1
    4040
    4141        B = A.todense()
    4242
    4343        C = Sparse(B)
    44        
     44
    4545        assert allclose(C.todense(), B)
    4646
    47                    
     47
    4848    def test_dense(self):
    4949        A = Sparse(4,3)
    50         A[1,1] = 4       
    51                      
     50        A[1,1] = 4
     51
    5252        assert allclose(A.todense(), [[0,0,0], [0,4,0], [0,0,0], [0,0,0]])
    5353
     
    5959
    6060        A = Sparse(3,3)
    61         A[1,1] = 4       
     61        A[1,1] = 4
    6262        A[1,1] = 0
    6363
     
    6868        A[1,2] = 0
    6969        assert len(A) == 0
    70         assert allclose(A.todense(), [[0,0,0], [0,0,0], [0,0,0]])       
     70        assert allclose(A.todense(), [[0,0,0], [0,0,0], [0,0,0]])
    7171
    7272    def test_sparse_multiplication_vector(self):
    7373        A = Sparse(3,3)
    74        
     74
    7575        A[0,0] = 3
    7676        A[1,1] = 2
     
    9191
    9292        u = A*v[:,1]
    93         assert allclose(u, [12,16,4])       
     93        assert allclose(u, [12,16,4])
    9494
    9595
    9696    def test_sparse_multiplication_matrix(self):
    9797        A = Sparse(3,3)
    98        
     98
    9999        A[0,0] = 3
    100100        A[1,1] = 2
     
    106106
    107107        u = A*v
    108         assert allclose(u, [[6,12], [14,16], [4,4]]) 
    109 
    110 
    111 
    112     def test_sparse_transpose_multiplication(self):       
    113         A = Sparse(3,3)
    114        
     108        assert allclose(u, [[6,12], [14,16], [4,4]])
     109
     110
     111
     112    def test_sparse_transpose_multiplication(self):
     113        A = Sparse(3,3)
     114
    115115        A[0,0] = 3
    116116        A[1,1] = 2
     
    128128        """Test method __rmul__
    129129        """
    130        
     130
    131131        A = Sparse(3,3)
    132132
     
    140140
    141141        B = A*3
    142         assert allclose(B.todense(), 3*A.todense())       
     142        assert allclose(B.todense(), 3*A.todense())
    143143
    144144        try:
     
    152152        """ Test sparse addition with dok format
    153153        """
    154        
     154
    155155        A = Sparse(3,3)
    156156
     
    171171        """ Test conversion to csr format
    172172        """
    173        
     173
    174174        A = Sparse(4,3)
    175175
     
    181181        A[2,0] = 5
    182182
    183         #print ' ' 
     183        #print ' '
    184184        #print A.todense()
    185185
     
    197197
    198198        assert allclose(B*C2, [[15.0, 30.0],[10.0, 20.0],[8.0, 16.0],[0.0, 0.0]])
    199        
     199
    200200
    201201
    202202#-------------------------------------------------------------
    203203if __name__ == "__main__":
    204     suite = unittest.makeSuite(TestCase, 'test')
     204    suite = unittest.makeSuite(Test_Sparse, 'test')
    205205    runner = unittest.TextTestRunner()
    206206    runner.run(suite)
    207 
  • inundation/ga/storm_surge/pyvolution/test_util.py

    r999 r1018  
    1313    return x+y
    1414
    15 class TestCase(unittest.TestCase):
     15class Test_Util(unittest.TestCase):
    1616    def setUp(self):
    1717        pass
     
    2525        x1 = 1.0; y1 = 0.0; z1 = -1.0
    2626        x2 = 0.0; y2 = 1.0; z2 = 0.0
    27        
     27
    2828        zx, zy = gradient(x0, y0, x1, y1, x2, y2, z0, z1, z2)
    2929
     
    4444        q1 = 8.0+2.0/3
    4545        q2 = 2.0+8.0/3
    46        
    47         #Gradient of fitted pwl surface   
     46
     47        #Gradient of fitted pwl surface
    4848        a, b = gradient(x0, y0, x1, y1, x2, y2, q0, q1, q2)
    49        
     49
    5050        assert abs(a - 3.0) < epsilon
    5151        assert abs(b - 1.0) < epsilon
    52    
     52
    5353
    5454
     
    6767                import util_ext
    6868
    69            
     69
    7070    def test_gradient_C_extension(self):
    7171        from util_ext import gradient as gradient_c
     
    7878        q1 = 8.0+2.0/3
    7979        q2 = 2.0+8.0/3
    80        
    81         #Gradient of fitted pwl surface   
     80
     81        #Gradient of fitted pwl surface
    8282        a, b = gradient_c(x0, y0, x1, y1, x2, y2, q0, q1, q2)
    83        
     83
    8484        assert abs(a - 3.0) < epsilon
    8585        assert abs(b - 1.0) < epsilon
    8686
    87        
     87
    8888    def test_gradient_C_extension3(self):
    8989        from util_ext import gradient as gradient_c
    90        
     90
    9191        from RandomArray import uniform, seed
    9292        seed(17, 53)
     
    9696        q0 = uniform(0.0, 10.0, 4)
    9797        q1 = uniform(1.0, 3.0, 4)
    98         q2 = uniform(7.0, 20.0, 4)       
    99        
     98        q2 = uniform(7.0, 20.0, 4)
     99
    100100
    101101        for i in range(4):
    102102            #Gradient of fitted pwl surface
    103             from util import gradient_python           
     103            from util import gradient_python
    104104            a_ref, b_ref = gradient(x0, y0, x1, y1, x2, y2,
    105105                                    q0[i], q1[i], q2[i])
     
    112112            assert abs(a - a_ref) < epsilon
    113113            assert abs(b - b_ref) < epsilon
    114        
    115 
    116 
    117     #Geometric       
     114
     115
     116
     117    #Geometric
    118118    #def test_distance(self):
    119119    #    from util import distance#
     
    127127    #
    128128    #    self.failUnless( distance([9,8],[4,2]) == distance([4,2],[9,8]),
    129     #                    'distance is wrong!')       
     129    #                    'distance is wrong!')
    130130
    131131    def test_angle(self):
     
    136136
    137137    def test_anglediff(self):
    138         from util import anglediff       
     138        from util import anglediff
    139139
    140140        assert allclose(anglediff([0.0, 1.], [1.0, 1.0])/pi*180, 45.0)
     
    163163            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
    164164            t += dt
    165    
     165
    166166        fid.close()
    167167
     
    174174
    175175            #Exact linear intpolation
    176             assert allclose(q[0], 2*t) 
     176            assert allclose(q[0], 2*t)
    177177            if i%6 == 0:
    178178                assert allclose(q[1], t**2)
    179                 assert allclose(q[2], sin(t*pi/600))               
     179                assert allclose(q[2], sin(t*pi/600))
    180180
    181181        #Check non-exact
    182182
    183183        t = 90 #Halfway between 60 and 120
    184         q = F(t) 
     184        q = F(t)
    185185        assert allclose( (120**2 + 60**2)/2, q[1] )
    186186        assert allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
     
    188188
    189189        t = 100 #Two thirds of the way between between 60 and 120
    190         q = F(t) 
     190        q = F(t)
    191191        assert allclose( 2*120**2/3 + 60**2/3, q[1] )
    192192        assert allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
    193        
     193
    194194        os.remove(filename)
    195        
     195
    196196
    197197
     
    215215
    216216        #Nice test that may render some of the others redundant.
    217        
     217
    218218        import os, time
    219219        from config import time_format
     
    231231                rectangular(4, 4, 15, 30, origin = (0, -20))
    232232
    233        
     233
    234234        #print 'Number of elements', len(vertices)
    235235        domain = Domain(points, vertices, boundary)
     
    246246        domain.starttime = start
    247247
    248        
     248
    249249        #Store structure
    250250        domain.initialise_storage()
     
    262262
    263263            f3 = lambda x,y: x**2 + y**2 * sin(t*pi/600)
    264             domain.set_quantity('ymomentum', f3)                       
     264            domain.set_quantity('ymomentum', f3)
    265265
    266266            #Store and advance time
     
    275275
    276276        #Set domain.starttime to too early
    277         domain.starttime = start - 1               
     277        domain.starttime = start - 1
    278278
    279279        #Create file function
     
    286286
    287287        #Check that domain.starttime isn't updated if later
    288         domain.starttime = start + 1               
     288        domain.starttime = start + 1
    289289        F = file_function(filename + '.sww', domain,
    290290                          quantities = domain.conserved_quantities,
    291291                          interpolation_points = interpolation_points)
    292         assert allclose(domain.starttime, start+1)               
     292        assert allclose(domain.starttime, start+1)
    293293
    294294        domain.starttime = start
    295295
    296296
    297        
     297
    298298        #Check linear interpolation in time
    299299        #for id in range(len(interpolation_points)):
    300300        for id in [1]:
    301301            x = interpolation_points[id][0]
    302             y = interpolation_points[id][1]           
    303            
     302            y = interpolation_points[id][1]
     303
    304304            for i in range(20):
    305305                t = i*10
    306306                k = i%6
    307            
     307
    308308                if k == 0:
    309                     q0 = F(t, point_id=id)                               
    310                     q1 = F(t+60, point_id=id)                               
    311            
    312            
     309                    q0 = F(t, point_id=id)
     310                    q1 = F(t+60, point_id=id)
     311
     312
    313313                q = F(t, point_id=id)
    314314                assert allclose(q, (k*q1 + (6-k)*q0)/6)
    315            
    316  
     315
     316
    317317        #Another check of linear interpolation in time
    318318        for id in range(len(interpolation_points)):
    319319            q60 = F(60, point_id=id)
    320             q120 = F(120, point_id=id)       
    321        
     320            q120 = F(120, point_id=id)
     321
    322322            t = 90 #Halfway between 60 and 120
    323323            q = F(t,point_id=id)
     
    333333        #than file end time
    334334        delta = 23
    335         domain.starttime = start + delta               
     335        domain.starttime = start + delta
    336336        F = file_function(filename + '.sww', domain,
    337337                          quantities = domain.conserved_quantities,
    338338                          interpolation_points = interpolation_points)
    339         assert allclose(domain.starttime, start+delta)               
    340 
    341        
    342        
    343        
     339        assert allclose(domain.starttime, start+delta)
     340
     341
     342
     343
    344344        #Now try interpolation with delta offset
    345345        for id in [1]:
    346346            x = interpolation_points[id][0]
    347             y = interpolation_points[id][1]           
    348            
     347            y = interpolation_points[id][1]
     348
    349349            for i in range(20):
    350350                t = i*10
    351351                k = i%6
    352            
     352
    353353                if k == 0:
    354                     q0 = F(t-delta, point_id=id)     
    355                     q1 = F(t+60-delta, point_id=id)                           
    356            
     354                    q0 = F(t-delta, point_id=id)
     355                    q1 = F(t+60-delta, point_id=id)
     356
    357357                q = F(t-delta, point_id=id)
    358358                assert allclose(q, (k*q1 + (6-k)*q0)/6)
    359            
    360        
     359
     360
    361361        os.remove(filename + '.sww')
    362        
     362
    363363
    364364
     
    385385            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
    386386            t += dt
    387    
     387
    388388        fid.close()
    389389
     
    391391        b = [4.0, 0.0]
    392392        c = [0.0, 3.0]
    393        
     393
    394394        points = [a, b, c]
    395395        vertices = [[0,1,2]]
    396         domain = Domain(points, vertices) 
     396        domain = Domain(points, vertices)
    397397
    398398        #Check that domain.starttime is updated if non-existing
    399399        F = file_function(filename, domain)
    400         assert allclose(domain.starttime, start)       
     400        assert allclose(domain.starttime, start)
    401401
    402402        #Check that domain.starttime is updated if too early
    403         domain.starttime = start - 1               
     403        domain.starttime = start - 1
    404404        F = file_function(filename, domain)
    405405        assert allclose(domain.starttime, start)
    406406
    407407        #Check that domain.starttime isn't updated if later
    408         domain.starttime = start + 1               
     408        domain.starttime = start + 1
    409409        F = file_function(filename, domain)
    410         assert allclose(domain.starttime, start+1)               
     410        assert allclose(domain.starttime, start+1)
    411411
    412412        domain.starttime = start
    413        
    414        
     413
     414
    415415        #Now try interpolation
    416416        for i in range(20):
     
    419419
    420420            #Exact linear intpolation
    421             assert allclose(q[0], 2*t) 
     421            assert allclose(q[0], 2*t)
    422422            if i%6 == 0:
    423423                assert allclose(q[1], t**2)
    424                 assert allclose(q[2], sin(t*pi/600))               
     424                assert allclose(q[2], sin(t*pi/600))
    425425
    426426        #Check non-exact
    427427
    428428        t = 90 #Halfway between 60 and 120
    429         q = F(t) 
     429        q = F(t)
    430430        assert allclose( (120**2 + 60**2)/2, q[1] )
    431431        assert allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
     
    433433
    434434        t = 100 #Two thirds of the way between between 60 and 120
    435         q = F(t) 
     435        q = F(t)
    436436        assert allclose( 2*120**2/3 + 60**2/3, q[1] )
    437437        assert allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
    438        
     438
    439439        os.remove(filename)
    440        
     440
    441441
    442442    def test_file_function_time_with_domain_different_start(self):
     
    464464            fid.write('%s, %f %f %f\n' %(t_string, 2*t, t**2, sin(t*pi/600)))
    465465            t += dt
    466    
     466
    467467        fid.close()
    468468
     
    470470        b = [4.0, 0.0]
    471471        c = [0.0, 3.0]
    472        
     472
    473473        points = [a, b, c]
    474474        vertices = [[0,1,2]]
    475         domain = Domain(points, vertices) 
     475        domain = Domain(points, vertices)
    476476
    477477        #Check that domain.starttime isn't updated if later than file starttime but earlier
    478478        #than file end time
    479479        delta = 23
    480         domain.starttime = start + delta               
     480        domain.starttime = start + delta
    481481        F = file_function(filename, domain)
    482         assert allclose(domain.starttime, start+delta)               
    483 
    484        
    485        
    486        
    487         #Now try interpolation with delta offset 
     482        assert allclose(domain.starttime, start+delta)
     483
     484
     485
     486
     487        #Now try interpolation with delta offset
    488488        for i in range(20):
    489489            t = i*10
     
    491491
    492492            #Exact linear intpolation
    493             assert allclose(q[0], 2*t) 
     493            assert allclose(q[0], 2*t)
    494494            if i%6 == 0:
    495495                assert allclose(q[1], t**2)
    496                 assert allclose(q[2], sin(t*pi/600))               
     496                assert allclose(q[2], sin(t*pi/600))
    497497
    498498        #Check non-exact
    499499
    500500        t = 90 #Halfway between 60 and 120
    501         q = F(t-delta) 
     501        q = F(t-delta)
    502502        assert allclose( (120**2 + 60**2)/2, q[1] )
    503503        assert allclose( (sin(120*pi/600) + sin(60*pi/600))/2, q[2] )
     
    505505
    506506        t = 100 #Two thirds of the way between between 60 and 120
    507         q = F(t-delta) 
     507        q = F(t-delta)
    508508        assert allclose( 2*120**2/3 + 60**2/3, q[1] )
    509509        assert allclose( 2*sin(120*pi/600)/3 + sin(60*pi/600)/3, q[2] )
    510        
     510
    511511        os.remove(filename)
    512512
     
    517517        """
    518518        import time
    519        
    520         #Create sww file of simple propagation from left to right 
     519
     520        #Create sww file of simple propagation from left to right
    521521        #through rectangular domain
    522522        from shallow_water import Domain, Dirichlet_boundary
    523523        from mesh_factory import rectangular
    524         from Numeric import take, concatenate, reshape       
     524        from Numeric import take, concatenate, reshape
    525525
    526526        #Create basic mesh and shallow water domain
    527527        points, vertices, boundary = rectangular(3, 3)
    528528        domain1 = Domain(points, vertices, boundary)
    529        
     529
    530530        from util import mean
    531         domain1.reduction = mean 
     531        domain1.reduction = mean
    532532        domain1.smooth = True #NOTE: Mimic sww output where each vertex has
    533533                              # only one value.
    534534
    535535        domain1.default_order = 2
    536         domain1.store = True   
     536        domain1.store = True
    537537        domain1.set_datadir('.')
    538538        domain1.set_name('spatio_temporal_boundary_source_%d' %(id(self)))
    539539        domain1.quantities_to_be_stored = ['stage', 'xmomentum', 'ymomentum']
    540                
     540
    541541        #Bed-slope, friction and IC at vertices (and interpolated elsewhere)
    542542        domain1.set_quantity('elevation', 0)
    543543        domain1.set_quantity('friction', 0)
    544         domain1.set_quantity('stage', 0)       
     544        domain1.set_quantity('stage', 0)
    545545
    546546        # Boundary conditions
    547         B0 = Dirichlet_boundary([0,0,0])               
    548         B6 = Dirichlet_boundary([0.6,0,0])     
     547        B0 = Dirichlet_boundary([0,0,0])
     548        B6 = Dirichlet_boundary([0.6,0,0])
    549549        domain1.set_boundary({'left': B6, 'top': B6, 'right': B0, 'bottom': B0})
    550550        domain1.check_integrity()
     
    560560        from Scientific.IO.NetCDF import NetCDFFile
    561561        filename = domain1.get_name() + '.' + domain1.format
    562         fid = NetCDFFile(filename) 
     562        fid = NetCDFFile(filename)
    563563
    564564        x = fid.variables['x'][:]
    565         y = fid.variables['y'][:]       
     565        y = fid.variables['y'][:]
    566566        stage = fid.variables['stage'][:]
    567567        xmomentum = fid.variables['xmomentum'][:]
     
    581581        #this timestep are
    582582        r0 = (D[0] + D[1])/2
    583         r1 = (D[1] + D[2])/2         
    584         r2 = (D[2] + D[3])/2         
     583        r1 = (D[1] + D[2])/2
     584        r2 = (D[2] + D[3])/2
    585585
    586586        #And the midpoints are found now
    587587        Dx = take(reshape(x, (16,1)), [0,5,10,15])
    588         Dy = take(reshape(y, (16,1)), [0,5,10,15])               
     588        Dy = take(reshape(y, (16,1)), [0,5,10,15])
    589589
    590590        diag = concatenate( (Dx, Dy), axis=1)
     
    597597
    598598        q = f(timestep/10., point_id=0); assert allclose(r0, q)
    599         q = f(timestep/10., point_id=1); assert allclose(r1, q)       
     599        q = f(timestep/10., point_id=1); assert allclose(r1, q)
    600600        q = f(timestep/10., point_id=2); assert allclose(r2, q)
    601601
     
    613613        #this timestep are
    614614        r0 = (D[0] + D[1])/2
    615         r1 = (D[1] + D[2])/2         
    616         r2 = (D[2] + D[3])/2         
     615        r1 = (D[1] + D[2])/2
     616        r2 = (D[2] + D[3])/2
    617617
    618618        #Let us see if the file function can find the correct
    619         #values 
     619        #values
    620620        q = f(0, point_id=0); assert allclose(r0, q)
    621621        q = f(0, point_id=1); assert allclose(r1, q)
     
    626626        #Now do it again for a timestep in the middle
    627627
    628         timestep = 33 
     628        timestep = 33
    629629        d_stage = reshape(take(stage[timestep, :], [0,5,10,15]), (4,1))
    630630        d_uh = reshape(take(xmomentum[timestep, :], [0,5,10,15]), (4,1))
     
    635635        #this timestep are
    636636        r0 = (D[0] + D[1])/2
    637         r1 = (D[1] + D[2])/2         
    638         r2 = (D[2] + D[3])/2         
     637        r1 = (D[1] + D[2])/2
     638        r2 = (D[2] + D[3])/2
    639639
    640640        q = f(timestep/10., point_id=0); assert allclose(r0, q)
    641         q = f(timestep/10., point_id=1); assert allclose(r1, q)       
     641        q = f(timestep/10., point_id=1); assert allclose(r1, q)
    642642        q = f(timestep/10., point_id=2); assert allclose(r2, q)
    643643
     
    656656        #this timestep are
    657657        r0_0 = (D[0] + D[1])/2
    658         r1_0 = (D[1] + D[2])/2         
    659         r2_0 = (D[2] + D[3])/2         
     658        r1_0 = (D[1] + D[2])/2
     659        r2_0 = (D[2] + D[3])/2
    660660
    661661        #
     
    669669        #this timestep are
    670670        r0_1 = (D[0] + D[1])/2
    671         r1_1 = (D[1] + D[2])/2         
    672         r2_1 = (D[2] + D[3])/2         
     671        r1_1 = (D[1] + D[2])/2
     672        r2_1 = (D[2] + D[3])/2
    673673
    674674        # The reference values are
    675675        r0 = (r0_0 + r0_1)/2
    676676        r1 = (r1_0 + r1_1)/2
    677         r2 = (r2_0 + r2_1)/2       
     677        r2 = (r2_0 + r2_1)/2
    678678
    679679        q = f((timestep - 0.5)/10., point_id=0); assert allclose(r0, q)
    680         q = f((timestep - 0.5)/10., point_id=1); assert allclose(r1, q)       
     680        q = f((timestep - 0.5)/10., point_id=1); assert allclose(r1, q)
    681681        q = f((timestep - 0.5)/10., point_id=2); assert allclose(r2, q)
    682682
     
    688688        r0 = (r0_0 + 2*r0_1)/3
    689689        r1 = (r1_0 + 2*r1_1)/3
    690         r2 = (r2_0 + 2*r2_1)/3       
     690        r2 = (r2_0 + 2*r2_1)/3
    691691
    692692        #And the file function gives
    693693        q = f((timestep - 1.0/3)/10., point_id=0); assert allclose(r0, q)
    694         q = f((timestep - 1.0/3)/10., point_id=1); assert allclose(r1, q)   
     694        q = f((timestep - 1.0/3)/10., point_id=1); assert allclose(r1, q)
    695695        q = f((timestep - 1.0/3)/10., point_id=2); assert allclose(r2, q)
    696        
     696
    697697        fid.close()
    698698        import os
    699699        os.remove(filename)
    700        
     700
    701701
    702702    def test_xya_ascii(self):
     
    704704        FN = 'xyatest' + str(time.time()) + '.xya'
    705705        fid = open(FN, 'w')
    706         fid.write('      %s %s %s\n' %('a1', 'a2', 'a3') )       
     706        fid.write('      %s %s %s\n' %('a1', 'a2', 'a3') )
    707707        fid.write('%f %f %f %f %f\n' %(0,1,10,20,30) )
    708708        fid.write('%f %f %f %f %f\n' %(1,0,30,20,10) )
    709         fid.write('%f %f %f %f %f\n' %(1,1,40.2,40.3,40.4) )           
     709        fid.write('%f %f %f %f %f\n' %(1,1,40.2,40.3,40.4) )
    710710        fid.close()
    711        
     711
    712712        points, attributes = read_xya(FN, format = 'asc')
    713713
     
    715715        assert allclose(attributes['a1'], [10,30,40.2])
    716716        assert allclose(attributes['a2'], [20,20,40.3])
    717         assert allclose(attributes['a3'], [30,10,40.4])       
    718        
     717        assert allclose(attributes['a3'], [30,10,40.4])
     718
    719719        os.remove(FN)
    720        
     720
    721721    def test_xya_ascii_w_names(self):
    722722        import time, os
    723723        FN = 'xyatest' + str(time.time()) + '.xya'
    724724        fid = open(FN, 'w')
    725         fid.write('      %s %s %s\n' %('a1', 'a2', 'a3') )       
     725        fid.write('      %s %s %s\n' %('a1', 'a2', 'a3') )
    726726        fid.write('%f %f %f %f %f\n' %(0,1,10,20,30) )
    727727        fid.write('%f %f %f %f %f\n' %(1,0,30,20,10) )
    728         fid.write('%f %f %f %f %f\n' %(1,1,40.2,40.3,40.4) )           
     728        fid.write('%f %f %f %f %f\n' %(1,1,40.2,40.3,40.4) )
    729729        fid.close()
    730        
     730
    731731        points, attributes = read_xya(FN, format = 'asc')
    732732
     
    735735        assert allclose(attributes['a1'], [10,30,40.2])
    736736        assert allclose(attributes['a2'], [20,20,40.3])
    737         assert allclose(attributes['a3'], [30,10,40.4])       
    738 
    739        
     737        assert allclose(attributes['a3'], [30,10,40.4])
     738
     739
    740740        os.remove(FN)
    741741
     
    743743
    744744
    745     #Polygon stuff     
     745    #Polygon stuff
    746746    def test_polygon_function_constants(self):
    747747        p1 = [[0,0], [10,0], [10,10], [0,10]]
    748748        p2 = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
    749        
    750         f = Polygon_function( [(p1, 1.0)] )     
     749
     750        f = Polygon_function( [(p1, 1.0)] )
    751751        z = f([5, 5, 27, 35], [5, 9, 8, -5]) #Two first inside p1
    752752        assert allclose(z, [1,1,0,0])
    753                
    754        
     753
     754
    755755        f = Polygon_function( [(p2, 2.0)] )
    756756        z = f([5, 5, 27, 35], [5, 9, 8, -5]) #First and last inside p2
    757         assert allclose(z, [2,0,0,2])   
    758                
    759        
    760         #Combined       
     757        assert allclose(z, [2,0,0,2])
     758
     759
     760        #Combined
    761761        f = Polygon_function( [(p1, 1.0), (p2, 2.0)] )
    762         z = f([5, 5, 27, 35], [5, 9, 8, -5]) 
    763         assert allclose(z, [2,1,0,2])   
    764        
    765        
     762        z = f([5, 5, 27, 35], [5, 9, 8, -5])
     763        assert allclose(z, [2,1,0,2])
     764
     765
    766766    def test_polygon_function_callable(self):
    767         """Check that values passed into Polygon_function can be callable 
     767        """Check that values passed into Polygon_function can be callable
    768768        themselves.
    769769        """
    770770        p1 = [[0,0], [10,0], [10,10], [0,10]]
    771771        p2 = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
    772        
    773         f = Polygon_function( [(p1, test_function)] )   
     772
     773        f = Polygon_function( [(p1, test_function)] )
    774774        z = f([5, 5, 27, 35], [5, 9, 8, -5]) #Two first inside p1
    775775        assert allclose(z, [10,14,0,0])
    776                
    777         #Combined       
     776
     777        #Combined
    778778        f = Polygon_function( [(p1, test_function), (p2, 2.0)] )
    779         z = f([5, 5, 27, 35], [5, 9, 8, -5]) 
    780         assert allclose(z, [2,14,0,2]) 
    781        
    782        
    783         #Combined w default     
     779        z = f([5, 5, 27, 35], [5, 9, 8, -5])
     780        assert allclose(z, [2,14,0,2])
     781
     782
     783        #Combined w default
    784784        f = Polygon_function( [(p1, test_function), (p2, 2.0)], default = 3.14)
    785         z = f([5, 5, 27, 35], [5, 9, 8, -5]) 
    786         assert allclose(z, [2,14,3.14,2])               
    787        
    788        
    789         #Combined w default func       
    790         f = Polygon_function( [(p1, test_function), (p2, 2.0)], 
     785        z = f([5, 5, 27, 35], [5, 9, 8, -5])
     786        assert allclose(z, [2,14,3.14,2])
     787
     788
     789        #Combined w default func
     790        f = Polygon_function( [(p1, test_function), (p2, 2.0)],
    791791                              default = test_function)
    792         z = f([5, 5, 27, 35], [5, 9, 8, -5]) 
    793         assert allclose(z, [2,14,35,2])                 
    794        
    795        
     792        z = f([5, 5, 27, 35], [5, 9, 8, -5])
     793        assert allclose(z, [2,14,35,2])
     794
     795
    796796    def test_point_on_line(self):
    797                
    798         #Endpoints first       
    799         assert point_on_line( 0, 0, 0,0, 1,0 ) 
    800         assert point_on_line( 1, 0, 0,0, 1,0 )         
    801 
    802         #Then points on line   
    803         assert point_on_line( 0.5, 0, 0,0, 1,0 ) 
    804         assert point_on_line( 0, 0.5, 0,1, 0,0 )               
    805         assert point_on_line( 1, 0.5, 1,1, 1,0 )       
    806         assert point_on_line( 0.5, 0.5, 0,0, 1,1 )             
    807        
    808         #Then points not on line               
    809         assert not point_on_line( 0.5, 0, 0,1, 1,1 )   
    810         assert not point_on_line( 0, 0.5, 0,0, 1,1 ) 
    811        
     797
     798        #Endpoints first
     799        assert point_on_line( 0, 0, 0,0, 1,0 )
     800        assert point_on_line( 1, 0, 0,0, 1,0 )
     801
     802        #Then points on line
     803        assert point_on_line( 0.5, 0, 0,0, 1,0 )
     804        assert point_on_line( 0, 0.5, 0,1, 0,0 )
     805        assert point_on_line( 1, 0.5, 1,1, 1,0 )
     806        assert point_on_line( 0.5, 0.5, 0,0, 1,1 )
     807
     808        #Then points not on line
     809        assert not point_on_line( 0.5, 0, 0,1, 1,1 )
     810        assert not point_on_line( 0, 0.5, 0,0, 1,1 )
     811
    812812        #From real example that failed
    813813        assert not point_on_line( 40,50, 40,20, 40,40 )
    814        
    815        
     814
     815
    816816        #From real example that failed
    817         assert not point_on_line( 40,19, 40,20, 40,40 ) 
    818                        
    819        
    820        
    821        
     817        assert not point_on_line( 40,19, 40,20, 40,40 )
     818
     819
     820
     821
    822822    def test_inside_polygon_main(self):
    823823
    824        
     824
    825825        #Simplest case: Polygon is the unit square
    826826        polygon = [[0,0], [1,0], [1,1], [0,1]]
    827827
    828828        assert inside_polygon( (0.5, 0.5), polygon )
    829         assert not inside_polygon( (0.5, 1.5), polygon )   
    830         assert not inside_polygon( (0.5, -0.5), polygon )       
    831         assert not inside_polygon( (-0.5, 0.5), polygon )               
    832         assert not inside_polygon( (1.5, 0.5), polygon )       
    833        
     829        assert not inside_polygon( (0.5, 1.5), polygon )
     830        assert not inside_polygon( (0.5, -0.5), polygon )
     831        assert not inside_polygon( (-0.5, 0.5), polygon )
     832        assert not inside_polygon( (1.5, 0.5), polygon )
     833
    834834        #Try point on borders
    835         assert inside_polygon( (1., 0.5), polygon, closed=True) 
    836         assert inside_polygon( (0.5, 1), polygon, closed=True) 
    837         assert inside_polygon( (0., 0.5), polygon, closed=True) 
    838         assert inside_polygon( (0.5, 0.), polygon, closed=True) 
    839        
    840         assert not inside_polygon( (0.5, 1), polygon, closed=False)     
    841         assert not inside_polygon( (0., 0.5), polygon, closed=False)   
    842         assert not inside_polygon( (0.5, 0.), polygon, closed=False)   
    843         assert not inside_polygon( (1., 0.5), polygon, closed=False)   
    844 
    845 
    846    
     835        assert inside_polygon( (1., 0.5), polygon, closed=True)
     836        assert inside_polygon( (0.5, 1), polygon, closed=True)
     837        assert inside_polygon( (0., 0.5), polygon, closed=True)
     838        assert inside_polygon( (0.5, 0.), polygon, closed=True)
     839
     840        assert not inside_polygon( (0.5, 1), polygon, closed=False)
     841        assert not inside_polygon( (0., 0.5), polygon, closed=False)
     842        assert not inside_polygon( (0.5, 0.), polygon, closed=False)
     843        assert not inside_polygon( (1., 0.5), polygon, closed=False)
     844
     845
     846
    847847        #From real example (that failed)
    848         polygon = [[20,20], [40,20], [40,40], [20,40]]         
     848        polygon = [[20,20], [40,20], [40,40], [20,40]]
    849849        points = [ [40, 50] ]
    850850        res = inside_polygon(points, polygon)
    851851        assert len(res) == 0
    852        
    853         polygon = [[20,20], [40,20], [40,40], [20,40]]         
     852
     853        polygon = [[20,20], [40,20], [40,40], [20,40]]
    854854        points = [ [25, 25], [30, 20], [40, 50], [90, 20], [40, 90] ]
    855855        res = inside_polygon(points, polygon)
    856856        assert len(res) == 2
    857857        assert allclose(res, [0,1])
    858        
    859                
    860              
     858
     859
     860
    861861        #More convoluted and non convex polygon
    862862        polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]]
    863863        assert inside_polygon( (0.5, 0.5), polygon )
    864         assert inside_polygon( (1, -0.5), polygon ) 
     864        assert inside_polygon( (1, -0.5), polygon )
    865865        assert inside_polygon( (1.5, 0), polygon )
    866        
    867         assert not inside_polygon( (0.5, 1.5), polygon )       
    868         assert not inside_polygon( (0.5, -0.5), polygon )               
    869        
    870        
     866
     867        assert not inside_polygon( (0.5, 1.5), polygon )
     868        assert not inside_polygon( (0.5, -0.5), polygon )
     869
     870
    871871        #Very convoluted polygon
    872872        polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
    873         assert inside_polygon( (5, 5), polygon )       
    874         assert inside_polygon( (17, 7), polygon )               
    875         assert inside_polygon( (27, 2), polygon )                       
    876         assert inside_polygon( (35, -5), polygon )                     
     873        assert inside_polygon( (5, 5), polygon )
     874        assert inside_polygon( (17, 7), polygon )
     875        assert inside_polygon( (27, 2), polygon )
     876        assert inside_polygon( (35, -5), polygon )
    877877        assert not inside_polygon( (15, 7), polygon )
    878878        assert not inside_polygon( (24, 3), polygon )
    879         assert not inside_polygon( (25, -10), polygon ) 
    880        
    881        
    882        
     879        assert not inside_polygon( (25, -10), polygon )
     880
     881
     882
    883883        #Another combination (that failed)
    884884        polygon = [[0,0], [10,0], [10,10], [0,10]]
    885         assert inside_polygon( (5, 5), polygon )       
    886         assert inside_polygon( (7, 7), polygon )       
    887         assert not inside_polygon( (-17, 7), polygon )                 
    888         assert not inside_polygon( (7, 17), polygon )                   
    889         assert not inside_polygon( (17, 7), polygon )                   
    890         assert not inside_polygon( (27, 8), polygon )                   
    891         assert not inside_polygon( (35, -5), polygon )                 
    892        
    893        
    894                        
    895        
    896         #Multiple polygons     
    897        
     885        assert inside_polygon( (5, 5), polygon )
     886        assert inside_polygon( (7, 7), polygon )
     887        assert not inside_polygon( (-17, 7), polygon )
     888        assert not inside_polygon( (7, 17), polygon )
     889        assert not inside_polygon( (17, 7), polygon )
     890        assert not inside_polygon( (27, 8), polygon )
     891        assert not inside_polygon( (35, -5), polygon )
     892
     893
     894
     895
     896        #Multiple polygons
     897
    898898        polygon = [[0,0], [1,0], [1,1], [0,1], [0,0],
    899899                   [10,10], [11,10], [11,11], [10,11], [10,10]]
    900         assert inside_polygon( (0.5, 0.5), polygon )               
    901         assert inside_polygon( (10.5, 10.5), polygon )                 
    902        
     900        assert inside_polygon( (0.5, 0.5), polygon )
     901        assert inside_polygon( (10.5, 10.5), polygon )
     902
    903903        #FIXME: Fails if point is 5.5, 5.5
    904         assert not inside_polygon( (0, 5.5), polygon )                         
    905 
    906         #Polygon with a hole   
     904        assert not inside_polygon( (0, 5.5), polygon )
     905
     906        #Polygon with a hole
    907907        polygon = [[-1,-1], [2,-1], [2,2], [-1,2], [-1,-1],
    908908                   [0,0], [1,0], [1,1], [0,1], [0,0]]
    909                        
     909
    910910        assert inside_polygon( (0, -0.5), polygon )
    911         assert not inside_polygon( (0.5, 0.5), polygon )       
    912 
    913     def test_inside_polygon_vector_version(self):       
     911        assert not inside_polygon( (0.5, 0.5), polygon )
     912
     913    def test_inside_polygon_vector_version(self):
    914914        #Now try the vector formulation returning indices
    915         polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]]       
     915        polygon = [[0,0], [1,0], [0.5,-1], [2, -1], [2,1], [0,1]]
    916916        points = [ [0.5, 0.5], [1, -0.5], [1.5, 0], [0.5, 1.5], [0.5, -0.5]]
    917917        res = inside_polygon( points, polygon )
    918        
     918
    919919        assert allclose( res, [0,1,2] )
    920920
     
    938938        for point in points:
    939939            assert inside_polygon(point, polygon)
    940            
    941 
    942                      
     940
     941
     942
    943943#-------------------------------------------------------------
    944944if __name__ == "__main__":
    945945    #suite = unittest.makeSuite(TestCase,'test_inside_polygon_main')
    946     suite = unittest.makeSuite(TestCase,'test')
     946    suite = unittest.makeSuite(Test_Util,'test')
    947947    runner = unittest.TextTestRunner()
    948948    runner.run(suite)
    949    
    950    
    951 
    952 
    953 
     949
     950
     951
     952
Note: See TracChangeset for help on using the changeset viewer.