Changeset 1360


Ignore:
Timestamp:
May 9, 2005, 10:03:30 PM (20 years ago)
Author:
steve
Message:
 
Location:
inundation/ga/storm_surge
Files:
7 edited

Legend:

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

    r1355 r1360  
    381381            #other modules (I think).
    382382
    383             #write a filename addon that won't break swollens reader 
     383            #write a filename addon that won't break swollens reader
    384384            #(10.sww is bad)
    385             filename_ext = '_time_%s'%self.domain.time           
     385            filename_ext = '_time_%s'%self.domain.time
    386386            filename_ext = filename_ext.replace('.', '_')
    387             #remember the old filename, then give domain a 
     387            #remember the old filename, then give domain a
    388388            #name with the extension
    389389            old_domain_filename = self.domain.filename
     
    539539
    540540        # Get X, Y and bed elevation Z
    541         Q = domain.quantities['elevation']
     541        Q = domain.quantities['elevation']
    542542        X,Y,Z,V = Q.get_vertex_values(xy=True,
    543543                                      precision = self.precision)
     
    559559        """
    560560        from Scientific.IO.NetCDF import NetCDFFile
    561         from time import sleep
     561        from time import sleep
    562562
    563563        #Get NetCDF
    564         retries = 0
    565         file_open = False
    566         while not file_open and retries < 10:
    567             try:
     564        retries = 0
     565        file_open = False
     566        while not file_open and retries < 10:
     567            try:
    568568                fid = NetCDFFile(self.filename, 'a') #Open existing file
    569             except IOError:
    570                 #This could happen if someone was reading the file.
    571                 #In that case, wait a while and try again
    572                 msg = 'Warning (store_timestep): File %s could not be opened'\
    573                 %self.filename
    574                 msg += ' - trying again'
    575                 print msg
    576                 retries += 1
    577                 sleep(1)
    578             else:
    579                file_open = True
    580 
    581         if not file_open:
    582             msg = 'File %s could not be opened for append' %self.filename
    583             raise msg
     569            except IOError:
     570                #This could happen if someone was reading the file.
     571                #In that case, wait a while and try again
     572                msg = 'Warning (store_timestep): File %s could not be opened'\
     573                          %self.filename
     574                msg += ' - trying again'
     575                print msg
     576                retries += 1
     577                sleep(1)
     578            else:
     579                file_open = True
     580
     581            if not file_open:
     582                msg = 'File %s could not be opened for append' %self.filename
     583            raise msg
    584584
    585585
     
    595595
    596596        # Get quantity
    597         Q = domain.quantities[name]
     597        Q = domain.quantities[name]
    598598        A,V = Q.get_vertex_values(xy=False,
    599599                                  precision = self.precision)
     
    10251025
    10261026def sww2asc(basename_in, basename_out = None,
    1027             quantity = None,                         
     1027            quantity = None,
    10281028            timestep = None,
    10291029            reduction = None,
     
    10611061    if quantity is given, out values from quantity otherwise default to
    10621062    elevation
    1063    
     1063
    10641064    if timestep (an index) is given, output quantity at that timestep
    10651065
    10661066    if reduction is given use that to reduce quantity over all timesteps.
    1067    
     1067
    10681068    """
    10691069    from Numeric import array, Float, concatenate, NewAxis, zeros,\
    10701070         sometrue
    1071    
     1071
    10721072
    10731073    #FIXME: Should be variable
     
    10761076    false_northing = 10000000
    10771077    NODATA_value = -9999
    1078    
     1078
    10791079    if quantity is None:
    10801080        quantity = 'elevation'
     
    10851085    if basename_out is None:
    10861086        basename_out = basename_in + '_%s' %quantity
    1087        
     1087
    10881088    swwfile = basename_in + '.sww'
    10891089    ascfile = basename_out + '.asc'
    1090     prjfile = basename_out + '.prj'   
     1090    prjfile = basename_out + '.prj'
    10911091
    10921092
     
    11031103    ymin = min(y); ymax = max(y)
    11041104    xmin = min(x); xmax = max(x)
    1105    
     1105
    11061106    number_of_timesteps = fid.dimensions['number_of_timesteps']
    11071107    number_of_points = fid.dimensions['number_of_points']
    11081108    if origin is None:
    1109        
     1109
    11101110        # get geo_reference
    11111111        #sww files don't have to have a geo_ref
     
    11141114        except AttributeError, e:
    11151115            geo_reference = Geo_reference(DEFAULT_ZONE,0,0)
    1116        
     1116
    11171117        xllcorner = geo_reference.get_xllcorner()
    11181118        yllcorner = geo_reference.get_yllcorner()
     
    11221122        xllcorner = origin[1]
    11231123        yllcorner = origin[2]
    1124        
     1124
    11251125
    11261126    #Get quantity and reduce if applicable
     
    11291129    if quantity.lower() == 'depth':
    11301130        q = fid.variables['stage'][:] - fid.variables['elevation'][:]
    1131     else: 
     1131    else:
    11321132        q = fid.variables[quantity][:]
    11331133
    1134    
     1134
    11351135    if len(q.shape) == 2:
    1136         if verbose: print 'Reducing quantity %s' %quantity           
    1137         q_reduced = zeros( number_of_points, Float ) 
     1136        if verbose: print 'Reducing quantity %s' %quantity
     1137        q_reduced = zeros( number_of_points, Float )
    11381138
    11391139        for k in range(number_of_points):
     
    11441144    #Now q has dimension: number_of_points
    11451145
    1146    
     1146
    11471147    #Write prj file
    11481148    if verbose: print 'Writing %s' %prjfile
    11491149    prjid = open(prjfile, 'w')
    11501150    prjid.write('Projection    %s\n' %'UTM')
    1151     prjid.write('Zone          %d\n' %zone)               
     1151    prjid.write('Zone          %d\n' %zone)
    11521152    prjid.write('Datum         %s\n' %datum)
    11531153    prjid.write('Zunits        NO\n')
     
    11661166    newxllcorner = xmin+xllcorner
    11671167    newyllcorner = ymin+yllcorner
    1168    
     1168
    11691169    x = x+xllcorner-newxllcorner
    11701170    y = y+yllcorner-newyllcorner
     
    11721172    vertex_points = concatenate ((x[:, NewAxis] ,y[:, NewAxis]), axis = 1)
    11731173    assert len(vertex_points.shape) == 2
    1174    
    1175 
    1176     from Numeric import zeros, Float 
     1174
     1175
     1176    from Numeric import zeros, Float
    11771177    grid_points = zeros ( (ncols*nrows, 2), Float )
    11781178
    11791179
    11801180    for i in xrange(nrows):
    1181         yg = i*cellsize       
     1181        yg = i*cellsize
    11821182        for j in xrange(ncols):
    11831183            xg = j*cellsize
     
    11871187            grid_points[k,0] = xg
    11881188            grid_points[k,1] = yg
    1189            
     1189
    11901190
    11911191    #Interpolate
    1192    
     1192
    11931193    from least_squares import Interpolation
    11941194    from util import inside_polygon
     
    11971197    #take forever. With expand_search  set to False, some grid points might
    11981198    #miss out....
    1199    
     1199
    12001200    interp = Interpolation(vertex_points, volumes, grid_points, alpha=0.0,
    12011201                           precrop = False, expand_search = False,
     
    12071207
    12081208    #Write
    1209     if verbose: print 'Writing %s' %ascfile   
     1209    if verbose: print 'Writing %s' %ascfile
    12101210    ascid = open(ascfile, 'w')
    12111211
     
    12151215    ascid.write('yllcorner     %d\n' %newyllcorner)
    12161216    ascid.write('cellsize      %f\n' %cellsize)
    1217     ascid.write('NODATA_value  %d\n' %NODATA_value)                   
     1217    ascid.write('NODATA_value  %d\n' %NODATA_value)
    12181218
    12191219
     
    12211221    P = interp.mesh.get_boundary_polygon()
    12221222    inside_indices = inside_polygon(grid_points, P)
    1223    
     1223
    12241224    for i in range(nrows):
    12251225        if verbose and i%((nrows+10)/10)==0:
    12261226            print 'Doing row %d of %d' %(i, nrows)
    1227            
     1227
    12281228        for j in range(ncols):
    12291229            index = (nrows-i-1)*ncols+j
    1230            
     1230
    12311231            if sometrue(inside_indices == index):
    1232                 ascid.write('%f ' %grid_values[index])               
     1232                ascid.write('%f ' %grid_values[index])
    12331233            else:
    12341234                ascid.write('%d ' %NODATA_value)
    1235                
     1235
    12361236        ascid.write('\n')
    1237        
     1237
    12381238    #Close
    12391239    ascid.close()
    12401240    fid.close()
    1241    
     1241
    12421242
    12431243def convert_dem_from_ascii2netcdf(basename_in, basename_out = None,
     
    14071407               fail_on_NaN = True,
    14081408               NaN_filler = 0,
    1409                elevation = None,
     1409               elevation = None,
    14101410               inverted_bathymetry = False
    14111411               ): #FIXME: Bathymetry should be obtained
    14121412                                  #from MOST somehow.
    14131413                                  #Alternatively from elsewhere
    1414                                   #or, as a last resort, 
    1415                                   #specified here. 
    1416                                   #The value of -100 will work 
     1414                                  #or, as a last resort,
     1415                                  #specified here.
     1416                                  #The value of -100 will work
    14171417                                  #for the Wollongong tsunami
    14181418                                  #scenario but is very hacky
     
    14401440    ferret2sww uses grid points as vertices in a triangular grid
    14411441    counting vertices from lower left corner upwards, then right
    1442     """ 
     1442    """
    14431443
    14441444    import os
    14451445    from Scientific.IO.NetCDF import NetCDFFile
    14461446    from Numeric import Float, Int, Int32, searchsorted, zeros, array
    1447     precision = Float 
     1447    precision = Float
    14481448
    14491449
     
    14521452    file_h = NetCDFFile(basename_in + '_ha.nc', 'r') #Wave amplitude (cm)
    14531453    file_u = NetCDFFile(basename_in + '_ua.nc', 'r') #Velocity (x) (cm/s)
    1454     file_v = NetCDFFile(basename_in + '_va.nc', 'r') #Velocity (y) (cm/s)   
    1455     file_e = NetCDFFile(basename_in + '_e.nc', 'r') #Elevation (z) (m)   
     1454    file_v = NetCDFFile(basename_in + '_va.nc', 'r') #Velocity (y) (cm/s)
     1455    file_e = NetCDFFile(basename_in + '_e.nc', 'r') #Elevation (z) (m)
    14561456
    14571457    if basename_out is None:
    14581458        swwname = basename_in + '.sww'
    14591459    else:
    1460         swwname = basename_out + '.sww'       
     1460        swwname = basename_out + '.sww'
    14611461
    14621462    times = file_h.variables['TIME']
     
    14661466    if mint == None:
    14671467        jmin = 0
    1468     else:   
     1468    else:
    14691469        jmin = searchsorted(times, mint)
    1470    
     1470
    14711471    if maxt == None:
    14721472        jmax=len(times)
    1473     else:   
     1473    else:
    14741474        jmax = searchsorted(times, maxt)
    1475        
     1475
    14761476    if minlat == None:
    14771477        kmin=0
     
    14861486    if minlon == None:
    14871487        lmin=0
    1488     else:   
     1488    else:
    14891489        lmin = searchsorted(longitudes, minlon)
    1490    
     1490
    14911491    if maxlon == None:
    14921492        lmax = len(longitudes)
    14931493    else:
    1494         lmax = searchsorted(longitudes, maxlon)           
    1495 
    1496 
    1497 
    1498     times = times[jmin:jmax]       
     1494        lmax = searchsorted(longitudes, maxlon)
     1495
     1496
     1497
     1498    times = times[jmin:jmax]
    14991499    latitudes = latitudes[kmin:kmax]
    15001500    longitudes = longitudes[lmin:lmax]
     
    15311531    else:
    15321532        nan_e = None
    1533    
     1533
    15341534    #Cleanup
    15351535    from Numeric import sometrue
    1536    
     1536
    15371537    missing = (amplitudes == nan_ha)
    15381538    if sometrue (missing):
     
    15741574    #######
    15751575
    1576                
     1576
    15771577
    15781578    number_of_times = times.shape[0]
     
    15821582    assert amplitudes.shape[0] == number_of_times
    15831583    assert amplitudes.shape[1] == number_of_latitudes
    1584     assert amplitudes.shape[2] == number_of_longitudes         
     1584    assert amplitudes.shape[2] == number_of_longitudes
    15851585
    15861586    if verbose:
     
    15961596        print '    t in [%f, %f], len(t) == %d'\
    15971597              %(min(times.flat), max(times.flat), len(times.flat))
    1598        
    1599         q = amplitudes.flat       
     1598
     1599        q = amplitudes.flat
    16001600        name = 'Amplitudes (ha) [cm]'
    16011601        print '  %s in [%f, %f]' %(name, min(q), max(q))
    1602        
     1602
    16031603        q = uspeed.flat
    1604         name = 'Speeds (ua) [cm/s]'       
     1604        name = 'Speeds (ua) [cm/s]'
    16051605        print '  %s in [%f, %f]' %(name, min(q), max(q))
    1606        
     1606
    16071607        q = vspeed.flat
    1608         name = 'Speeds (va) [cm/s]'               
    1609         print '  %s in [%f, %f]' %(name, min(q), max(q))               
     1608        name = 'Speeds (va) [cm/s]'
     1609        print '  %s in [%f, %f]' %(name, min(q), max(q))
    16101610
    16111611        q = elevations.flat
    1612         name = 'Elevations (e) [m]'               
    1613         print '  %s in [%f, %f]' %(name, min(q), max(q))               
     1612        name = 'Elevations (e) [m]'
     1613        print '  %s in [%f, %f]' %(name, min(q), max(q))
    16141614
    16151615
     
    16171617    number_of_points = number_of_latitudes*number_of_longitudes
    16181618    number_of_volumes = (number_of_latitudes-1)*(number_of_longitudes-1)*2
    1619    
     1619
    16201620
    16211621    file_h.close()
    16221622    file_u.close()
    1623     file_v.close()   
    1624     file_e.close()   
     1623    file_v.close()
     1624    file_e.close()
    16251625
    16261626
    16271627    # NetCDF file definition
    16281628    outfile = NetCDFFile(swwname, 'w')
    1629        
     1629
    16301630    #Create new file
    16311631    outfile.institution = 'Geoscience Australia'
     
    16381638
    16391639    #For sww compatibility
    1640     outfile.smoothing = 'Yes' 
     1640    outfile.smoothing = 'Yes'
    16411641    outfile.order = 1
    1642            
     1642
    16431643    #Start time in seconds since the epoch (midnight 1/1/1970)
    16441644    outfile.starttime = starttime = times[0]
    16451645    times = times - starttime  #Store relative times
    1646    
     1646
    16471647    # dimension definitions
    16481648    outfile.createDimension('number_of_volumes', number_of_volumes)
     
    16501650    outfile.createDimension('number_of_vertices', 3)
    16511651    outfile.createDimension('number_of_points', number_of_points)
    1652                            
    1653                
     1652
     1653
    16541654    #outfile.createDimension('number_of_timesteps', len(times))
    16551655    outfile.createDimension('number_of_timesteps', len(times))
     
    16591659    outfile.createVariable('y', precision, ('number_of_points',))
    16601660    outfile.createVariable('elevation', precision, ('number_of_points',))
    1661            
     1661
    16621662    #FIXME: Backwards compatibility
    16631663    outfile.createVariable('z', precision, ('number_of_points',))
    16641664    #################################
    1665        
     1665
    16661666    outfile.createVariable('volumes', Int, ('number_of_volumes',
    16671667                                            'number_of_vertices'))
    1668    
     1668
    16691669    outfile.createVariable('time', precision,
    16701670                           ('number_of_timesteps',))
    1671        
     1671
    16721672    outfile.createVariable('stage', precision,
    16731673                           ('number_of_timesteps',
     
    16771677                           ('number_of_timesteps',
    16781678                            'number_of_points'))
    1679    
     1679
    16801680    outfile.createVariable('ymomentum', precision,
    16811681                           ('number_of_timesteps',
     
    16911691    if verbose: print 'Making triangular grid'
    16921692    #Check zone boundaries
    1693     refzone, _, _ = redfearn(latitudes[0],longitudes[0])   
     1693    refzone, _, _ = redfearn(latitudes[0],longitudes[0])
    16941694
    16951695    vertices = {}
    1696     i = 0   
     1696    i = 0
    16971697    for k, lat in enumerate(latitudes):       #Y direction
    16981698        for l, lon in enumerate(longitudes):  #X direction
     
    17001700            vertices[l,k] = i
    17011701
    1702             zone, easting, northing = redfearn(lat,lon)               
     1702            zone, easting, northing = redfearn(lat,lon)
    17031703
    17041704            msg = 'Zone boundary crossed at longitude =', lon
     
    17151715        for k in range(number_of_latitudes-1): #Y direction
    17161716            v1 = vertices[l,k+1]
    1717             v2 = vertices[l,k]           
    1718             v3 = vertices[l+1,k+1]           
    1719             v4 = vertices[l+1,k]           
     1717            v2 = vertices[l,k]
     1718            v3 = vertices[l+1,k+1]
     1719            v4 = vertices[l+1,k]
    17201720
    17211721            volumes.append([v1,v2,v3]) #Upper element
    1722             volumes.append([v4,v3,v2]) #Lower element           
    1723 
    1724     volumes = array(volumes)       
     1722            volumes.append([v4,v3,v2]) #Lower element
     1723
     1724    volumes = array(volumes)
    17251725
    17261726    if origin == None:
    1727         zone = refzone       
     1727        zone = refzone
    17281728        xllcorner = min(x)
    17291729        yllcorner = min(y)
     
    17311731        zone = origin[0]
    17321732        xllcorner = origin[1]
    1733         yllcorner = origin[2]               
    1734 
    1735    
     1733        yllcorner = origin[2]
     1734
     1735
    17361736    outfile.xllcorner = xllcorner
    17371737    outfile.yllcorner = yllcorner
     
    17471747            z = elevations
    17481748        #FIXME: z should be obtained from MOST and passed in here
    1749  
     1749
    17501750    from Numeric import resize
    17511751    z = resize(z,outfile.variables['z'][:].shape)
     
    17561756    outfile.variables['time'][:] = times   #Store time relative
    17571757    outfile.variables['volumes'][:] = volumes.astype(Int32) #On Opteron 64
    1758    
     1758
    17591759
    17601760
     
    17621762    stage = outfile.variables['stage']
    17631763    xmomentum = outfile.variables['xmomentum']
    1764     ymomentum = outfile.variables['ymomentum'] 
     1764    ymomentum = outfile.variables['ymomentum']
    17651765
    17661766    if verbose: print 'Converting quantities'
     
    17811781    if verbose:
    17821782        x = outfile.variables['x'][:]
    1783         y = outfile.variables['y'][:]       
     1783        y = outfile.variables['y'][:]
    17841784        print '------------------------------------------------'
    17851785        print 'Statistics of output file:'
     
    18001800            q = outfile.variables[name][:].flferret2swwat
    18011801            print '    %s in [%f, %f]' %(name, min(q), max(q))
    1802            
    1803        
    1804 
    1805        
    1806     outfile.close()               
    1807    
     1802
     1803
     1804
     1805
     1806    outfile.close()
     1807
    18081808
    18091809
     
    18501850    Usage: domain = sww2domain('file.sww',t=time (default = last time in file))
    18511851
    1852     Boundary is not recommended if domian.smooth is not selected, as it       
    1853     uses unique coordinates, but not unique boundaries. This means that 
     1852    Boundary is not recommended if domian.smooth is not selected, as it
     1853    uses unique coordinates, but not unique boundaries. This means that
    18541854    the boundary file will not be compatable with the coordiantes, and will
    18551855    give a different final boundary, or crash.
     
    18911891    except: #AttributeError, e:
    18921892        geo_reference = None
    1893        
     1893
    18941894    if verbose: print '    getting quantities'
    18951895    for quantity in fid.variables.keys():
     
    19291929    if not boundary is None:
    19301930        domain.boundary = boundary
    1931    
     1931
    19321932    domain.geo_reference = geo_reference
    19331933
     
    19881988
    19891989def interpolated_quantity(saved_quantity,time_interp):
    1990        
     1990
    19911991    #given an index and ratio, interpolate quantity with respect to time.
    19921992    index,ratio = time_interp
    1993     Q = saved_quantity 
     1993    Q = saved_quantity
    19941994    if ratio > 0:
    19951995        q = (1-ratio)*Q[index]+ ratio*Q[index+1]
     
    20222022            ratio = 0
    20232023        else:
    2024             #t is now between index and index+1           
     2024            #t is now between index and index+1
    20252025            ratio = (tau - time[index])/(time[index+1] - time[index])
    20262026    return (index,ratio)
     
    20422042            same_point[i]=point
    20432043            #to change all point i references to point j
    2044         else: 
     2044        else:
    20452045            point_dict[point]=i
    20462046            same_point[i]=point
     
    20792079            else: new_boundary[(point0,point1)]=label
    20802080
    2081         boundary = new_boundary               
     2081        boundary = new_boundary
    20822082
    20832083    return coordinates,volumes,boundary
    2084        
    2085        
     2084
     2085
    20862086
    20872087#OBSOLETE STUFF
     
    22302230
    22312231    The momentum is not always stored.
    2232    
     2232
    22332233    """
    22342234    from Scientific.IO.NetCDF import NetCDFFile
     
    22432243    stage = fid.variables['stage']     #Water level
    22442244    #xmomentum = fid.variables['xmomentum']   #Momentum in the x-direction
    2245     #ymomentum = fid.variables['ymomentum']   #Momentum in the y-direction   
     2245    #ymomentum = fid.variables['ymomentum']   #Momentum in the y-direction
    22462246
    22472247    volumes = fid.variables['volumes'] #Connectivity
  • inundation/ga/storm_surge/pyvolution/domain.py

    r1290 r1360  
    1616    def __init__(self, coordinates, vertices, boundary = None,
    1717                 conserved_quantities = None, other_quantities = None,
    18                  tagged_elements = None, geo_reference = None):
     18                 tagged_elements = None, geo_reference = None, use_inscribed_circle=False):
    1919
    2020        Mesh.__init__(self, coordinates, vertices, boundary,
    21                       tagged_elements, geo_reference)
     21                      tagged_elements, geo_reference, use_inscribed_circle)
    2222
    2323        from Numeric import zeros, Float
  • inundation/ga/storm_surge/pyvolution/mesh.py

    r1358 r1360  
    130130                c = sqrt((x2-x0)**2+(y2-y0)**2)
    131131
    132                 self.radii[i]=self.areas[i]/(2*(a+b+c))
     132                self.radii[i]=2.0*self.areas[i]/(a+b+c)
    133133
    134134
  • inundation/ga/storm_surge/pyvolution/netherlands.py

    r1295 r1360  
    6363                z[i] = -x[i]/20+0.4
    6464
    65             if (x[i] - 0.72)**2 + (y[i] - 0.4)**2 < 0.05**2:# or\
    66                    #x[i] > 0.75 and x[i] < 0.9 and y[i] > 0.35 and y[i] < 0.45:
    67                 z[i] = -x[i]/20+0.4
    6865
    6966            #Wall
     
    8380N = 130 #size = 33800
    8481N = 600 #Size = 720000
    85 N = 40
     82N = 60
    8683
    8784#N = 15
     
    9289
    9390#Create shallow water domain
    94 domain = Domain(points, vertices, boundary)
     91domain = Domain(points, vertices, boundary, use_inscribed_circle=True)
    9592
    9693domain.check_integrity()
     
    105102
    106103#Set bed-slope and friction
    107 inflow_stage = 0.4
     104inflow_stage = 0.1
    108105manning = 0.02
    109106Z = Weir(inflow_stage)
     
    120117else:
    121118    domain.visualise = True
    122     domain.visualise_color_stage = True
     119    domain.visualise_color_stage = False
    123120    domain.visualise_timer = True
    124121    domain.checkpoint = False
    125122    domain.store = False
     123
    126124
    127125
  • inundation/ga/storm_surge/pyvolution/shallow_water.py

    r1295 r1360  
    6363
    6464    def __init__(self, coordinates, vertices, boundary = None,
    65                  tagged_elements = None, geo_reference = None):
     65                 tagged_elements = None, geo_reference = None,
     66                 use_inscribed_circle=False):
    6667
    6768        conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
     
    6970        Generic_domain.__init__(self, coordinates, vertices, boundary,
    7071                                conserved_quantities, other_quantities,
    71                                 tagged_elements, geo_reference)
     72                                tagged_elements, geo_reference, use_inscribed_circle)
    7273
    7374        from config import minimum_allowed_height, g
  • inundation/ga/storm_surge/pyvolution/test_data_manager.py

    r1201 r1360  
    263263
    264264
    265         Q = self.domain.quantities['stage']
     265        Q = self.domain.quantities['stage']
    266266        Q0 = Q.vertex_values[:,0]
    267267        Q1 = Q.vertex_values[:,1]
     
    321321
    322322        #Check values
    323         Q = self.domain.quantities['stage']
     323        Q = self.domain.quantities['stage']
    324324        Q0 = Q.vertex_values[:,0]
    325325        Q1 = Q.vertex_values[:,1]
     
    335335        assert allclose(A[4], (Q1[0] + Q2[1] + Q0[2] +\
    336336                                 Q0[5] + Q2[6] + Q1[7])/6)
    337 
    338 
    339 
    340337
    341338
     
    380377
    381378        #Check values
    382         Q = self.domain.quantities['stage']
     379        Q = self.domain.quantities['stage']
    383380        Q0 = Q.vertex_values[:,0]
    384381        Q1 = Q.vertex_values[:,1]
     
    432429
    433430            fid.close()
     431
    434432        os.remove(self.domain.writer.filename)
    435433
     
    596594        #Setup
    597595        self.domain.filename = 'datatest'
    598        
     596
    599597        prjfile = self.domain.filename + '_elevation.prj'
    600         ascfile = self.domain.filename + '_elevation.asc'       
     598        ascfile = self.domain.filename + '_elevation.asc'
    601599        swwfile = self.domain.filename + '.sww'
    602        
     600
    603601        self.domain.set_datadir('.')
    604602        self.domain.format = 'sww'
     
    607605
    608606        self.domain.geo_reference = Geo_reference(56,308500,6189000)
    609        
     607
    610608        sww = get_dataobject(self.domain)
    611609        sww.store_connectivity()
     
    630628
    631629        #Export to ascii/prj files
    632         sww2asc(self.domain.filename, 
    633                 quantity = 'elevation',                         
     630        sww2asc(self.domain.filename,
     631                quantity = 'elevation',
    634632                cellsize = cellsize,
    635633                verbose = False)
     
    655653        L = lines[3].strip().split()
    656654        assert L[0].strip().lower() == 'zunits'
    657         assert L[1].strip().lower() == 'no'                       
     655        assert L[1].strip().lower() == 'no'
    658656
    659657        L = lines[4].strip().split()
    660658        assert L[0].strip().lower() == 'units'
    661         assert L[1].strip().lower() == 'meters'               
     659        assert L[1].strip().lower() == 'meters'
    662660
    663661        L = lines[5].strip().split()
     
    671669        L = lines[7].strip().split()
    672670        assert L[0].strip().lower() == 'yshift'
    673         assert L[1].strip().lower() == '10000000'       
     671        assert L[1].strip().lower() == '10000000'
    674672
    675673        L = lines[8].strip().split()
    676674        assert L[0].strip().lower() == 'parameters'
    677        
     675
    678676
    679677        #Check asc file
    680678        ascid = open(ascfile)
    681679        lines = ascid.readlines()
    682         ascid.close()       
     680        ascid.close()
    683681
    684682        L = lines[0].strip().split()
     
    688686        L = lines[1].strip().split()
    689687        assert L[0].strip().lower() == 'nrows'
    690         assert L[1].strip().lower() == '5'       
     688        assert L[1].strip().lower() == '5'
    691689
    692690        L = lines[2].strip().split()
     
    704702        L = lines[5].strip().split()
    705703        assert L[0].strip() == 'NODATA_value'
    706         assert L[1].strip().lower() == '-9999'       
     704        assert L[1].strip().lower() == '-9999'
    707705
    708706        #Check grid values
    709707        for j in range(5):
    710             L = lines[6+j].strip().split()           
     708            L = lines[6+j].strip().split()
    711709            y = (4-j) * cellsize
    712710            for i in range(5):
    713711                assert allclose(float(L[i]), -i*cellsize - y)
    714        
     712
    715713
    716714        fid.close()
     
    718716        #Cleanup
    719717        os.remove(prjfile)
    720         os.remove(ascfile)       
     718        os.remove(ascfile)
    721719        os.remove(swwfile)
    722720
     
    735733        #Setup
    736734        self.domain.filename = 'datatest'
    737        
     735
    738736        prjfile = self.domain.filename + '_stage.prj'
    739         ascfile = self.domain.filename + '_stage.asc'               
     737        ascfile = self.domain.filename + '_stage.asc'
    740738        swwfile = self.domain.filename + '.sww'
    741        
     739
    742740        self.domain.set_datadir('.')
    743741        self.domain.format = 'sww'
     
    746744
    747745        self.domain.geo_reference = Geo_reference(56,308500,6189000)
    748        
    749        
     746
     747
    750748        sww = get_dataobject(self.domain)
    751749        sww.store_connectivity()
     
    770768
    771769        #Export to ascii/prj files
    772         sww2asc(self.domain.filename, 
    773                 quantity = 'stage',                         
     770        sww2asc(self.domain.filename,
     771                quantity = 'stage',
    774772                cellsize = cellsize,
    775773                reduction = min)
     
    779777        ascid = open(ascfile)
    780778        lines = ascid.readlines()
    781         ascid.close()       
     779        ascid.close()
    782780
    783781        L = lines[0].strip().split()
     
    787785        L = lines[1].strip().split()
    788786        assert L[0].strip().lower() == 'nrows'
    789         assert L[1].strip().lower() == '5'       
     787        assert L[1].strip().lower() == '5'
    790788
    791789        L = lines[2].strip().split()
     
    803801        L = lines[5].strip().split()
    804802        assert L[0].strip() == 'NODATA_value'
    805         assert L[1].strip().lower() == '-9999'       
    806 
    807        
     803        assert L[1].strip().lower() == '-9999'
     804
     805
    808806        #Check grid values (where applicable)
    809807        for j in range(5):
    810808            if j%2 == 0:
    811                 L = lines[6+j].strip().split()           
     809                L = lines[6+j].strip().split()
    812810                jj = 4-j
    813811                for i in range(5):
     
    825823        #Cleanup
    826824        os.remove(prjfile)
    827         os.remove(ascfile)       
     825        os.remove(ascfile)
    828826        #os.remove(swwfile)
    829827
     
    837835        This test includes the writing of missing values
    838836        """
    839        
     837
    840838        import time, os
    841839        from Numeric import array, zeros, allclose, Float, concatenate
     
    848846        points = [                        [1.0, 1.0],
    849847                              [0.5, 0.5], [1.0, 0.5],
    850                   [0.0, 0.0], [0.5, 0.0], [1.0, 0.0]]           
     848                  [0.0, 0.0], [0.5, 0.0], [1.0, 0.0]]
    851849
    852850        vertices = [ [4,1,3], [5,2,4], [1,4,2], [2,0,1]]
    853        
     851
    854852        #Create shallow water domain
    855853        domain = Domain(points, vertices)
     
    858856
    859857        #Set some field values
    860         domain.set_quantity('elevation', lambda x,y: -x-y)       
     858        domain.set_quantity('elevation', lambda x,y: -x-y)
    861859        domain.set_quantity('friction', 0.03)
    862860
     
    885883
    886884        domain.filename = 'datatest'
    887        
     885
    888886        prjfile = domain.filename + '_elevation.prj'
    889         ascfile = domain.filename + '_elevation.asc'               
     887        ascfile = domain.filename + '_elevation.asc'
    890888        swwfile = domain.filename + '.sww'
    891        
     889
    892890        domain.set_datadir('.')
    893891        domain.format = 'sww'
     
    895893
    896894        domain.geo_reference = Geo_reference(56,308500,6189000)
    897        
     895
    898896        sww = get_dataobject(domain)
    899897        sww.store_connectivity()
     
    916914        except AttributeError, e:
    917915            geo_reference = Geo_reference(DEFAULT_ZONE,0,0)
    918        
     916
    919917        #Export to ascii/prj files
    920         sww2asc(domain.filename, 
    921                 quantity = 'elevation',                         
     918        sww2asc(domain.filename,
     919                quantity = 'elevation',
    922920                cellsize = cellsize,
    923921                verbose = False)
     
    927925        ascid = open(ascfile)
    928926        lines = ascid.readlines()
    929         ascid.close()       
     927        ascid.close()
    930928
    931929        L = lines[0].strip().split()
     
    935933        L = lines[1].strip().split()
    936934        assert L[0].strip().lower() == 'nrows'
    937         assert L[1].strip().lower() == '5'       
     935        assert L[1].strip().lower() == '5'
    938936
    939937        L = lines[2].strip().split()
     
    951949        L = lines[5].strip().split()
    952950        assert L[0].strip() == 'NODATA_value'
    953         assert L[1].strip().lower() == '-9999'       
     951        assert L[1].strip().lower() == '-9999'
    954952
    955953
    956954        #Check grid values
    957955        for j in range(5):
    958             L = lines[6+j].strip().split()           
     956            L = lines[6+j].strip().split()
    959957            y = (4-j) * cellsize
    960958            for i in range(5):
     
    971969        #Cleanup
    972970        os.remove(prjfile)
    973         os.remove(ascfile)       
     971        os.remove(ascfile)
    974972        os.remove(swwfile)
    975973
     
    10191017        stage = fid.variables['stage'][:]
    10201018        xmomentum = fid.variables['xmomentum'][:]
    1021         ymomentum = fid.variables['ymomentum'][:]       
     1019        ymomentum = fid.variables['ymomentum'][:]
    10221020
    10231021        #print ymomentum
    1024                
     1022
    10251023        assert allclose(stage[0,0], first_value/100)  #Meters
    10261024
     
    11091107        # LAT = -34.5, -34.33333, -34.16667, -34 ;
    11101108        # ELEVATION = [-1 -2 -3 -4
    1111         #             -5 -6 -7 -8 
     1109        #             -5 -6 -7 -8
    11121110        #              ...
    11131111        #              ...      -16]
     
    11461144            fid.variables[lat_name].units='degrees_north'
    11471145            fid.variables[lat_name].assignValue(h2_list)
    1148        
     1146
    11491147            fid.createDimension('TIME',2)
    11501148            fid.createVariable('TIME','d',('TIME',))
     
    11531151            fid.variables['TIME'].assignValue([0.,1.])
    11541152            if fid == fid3: break
    1155        
     1153
    11561154
    11571155        for fid in [fid4]:
     
    11731171        name[fid3]='VA'
    11741172        name[fid4]='ELEVATION'
    1175        
     1173
    11761174        units = {}
    11771175        units[fid1]='cm'
     
    11851183        values[fid3]=[[[13., 12.,11.], [10.,9.,8.]],[[7.,6.,5.],[4.,3.,2.]]]
    11861184        values[fid4]=[[-3000,-3100,-3200],[-4000,-5000,-6000]]
    1187        
     1185
    11881186        for fid in [fid1,fid2,fid3]:
    11891187          fid.createVariable(name[fid],'d',('TIME',lat_name,long_name))
     
    12011199            fid.variables[name[fid]].missing_value = -99999999.
    12021200
    1203        
     1201
    12041202        fid1.sync(); fid1.close()
    12051203        fid2.sync(); fid2.close()
     
    12101208        fid2 = NetCDFFile('test_e.nc','r')
    12111209        fid3 = NetCDFFile('test_va.nc','r')
    1212        
     1210
    12131211
    12141212        first_amp = fid1.variables['HA'][:][0,0,0]
     
    12401238        stage = fid.variables['stage'][:]
    12411239        xmomentum = fid.variables['xmomentum'][:]
    1242         ymomentum = fid.variables['ymomentum'][:]       
     1240        ymomentum = fid.variables['ymomentum'][:]
    12431241
    12441242        #print ymomentum
     
    13431341        yiel=0.01
    13441342        points, vertices, boundary = rectangular(10,10)
    1345        
     1343
    13461344        #Create shallow water domain
    13471345        domain = Domain(points, vertices, boundary)
     
    14651463            #print bit
    14661464            assert allclose(eval('domain.'+bit),eval('domain2.'+bit))
    1467        
     1465
    14681466
    14691467    def test_sww2domain2(self):
     
    15071505
    15081506        domain.check_integrity()
    1509        
     1507
    15101508        for t in domain.evolve(yieldstep = 1, finaltime = 2.0):
    15111509            pass
    15121510            #domain.write_time()
    15131511
    1514        
     1512
    15151513
    15161514        ##################################
     
    15631561        coordinates2,volumes2,boundary2=weed(coordinates1,volumes1,boundary1)
    15641562
    1565         points2 = {(0.,0.):None,(1.,0.):None,(1.,1.):None,(2.,0.):None}       
     1563        points2 = {(0.,0.):None,(1.,0.):None,(1.,1.):None,(2.,0.):None}
    15661564
    15671565        assert len(points2)==len(coordinates2)
     
    15771575
    15781576
    1579      #FIXME This fails - smooth makes the comparism too hard for allclose 
     1577     #FIXME This fails - smooth makes the comparism too hard for allclose
    15801578    def ztest_sww2domain3(self):
    15811579        ################################################
     
    15901588        yiel=0.01
    15911589        points, vertices, boundary = rectangular(10,10)
    1592        
     1590
    15931591        #Create shallow water domain
    15941592        domain = Domain(points, vertices, boundary)
     
    17141712            print bit
    17151713            assert allclose(eval('domain.'+bit),eval('domain2.'+bit))
    1716        
     1714
    17171715
    17181716#-------------------------------------------------------------
    17191717if __name__ == "__main__":
    1720     suite = unittest.makeSuite(Test_Data_Manager,'test')   
     1718    suite = unittest.makeSuite(Test_Data_Manager,'test')
    17211719    #suite = unittest.makeSuite(Test_Data_Manager,'test_sww2domain')
    17221720    runner = unittest.TextTestRunner()
Note: See TracChangeset for help on using the changeset viewer.