Changeset 1137 for inundation/ga


Ignore:
Timestamp:
Mar 23, 2005, 6:06:51 PM (20 years ago)
Author:
ole
Message:

Work on sww2asc export, ensure_numeric and other minor stuff

Location:
inundation/ga/storm_surge
Files:
8 edited

Legend:

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

    r1133 r1137  
    1616
    1717.asc: ASCII foramt of regular DEMs as output from ArcView
     18.prj: Associated ArcView file giving more meta data for asc format
     19
    1820.dem: NetCDF representation of regular DEM data
    1921
    2022.tsh: ASCII format for storing meshes and associated boundary and region info
     23.msh: NetCDF format for storing meshes and associated boundary and region info
    2124
    2225.nc: Native ferret NetCDF format
     
    4043TSH -> SWW:  Conversion of TSH to sww viewable using Swollen
    4144
    42 TSH + Boundary SWW -> SWW: SImluation using pyvolution
     45TSH + Boundary SWW -> SWW: Simluation using pyvolution
    4346
    4447
     
    209212
    210213    def __init__(self, domain, mode = 'w',\
    211                  max_size = 2000000000,recursion=False):
     214                 max_size = 2000000000,
     215                 recursion=False):
    212216        from Scientific.IO.NetCDF import NetCDFFile
    213217        from Numeric import Int, Float, Float32
     
    978982    outfile.yllcorner = yllcorner #Northing of lower left corner
    979983    outfile.false_easting = false_easting
    980     outfile.false_northing =false_northing
     984    outfile.false_northing = false_northing
    981985
    982986    outfile.projection = projection
     
    10191023    outfile.close()
    10201024
     1025
     1026def sww2asc(basename_in, basename_out = None,
     1027            quantity = None,                         
     1028            timestep = None,
     1029            reduction = None,
     1030            cellsize = 10,
     1031            verbose = False,
     1032            origin = None):
     1033    """Read SWW file and convert to Digitial Elevation model format (.asc)
     1034
     1035    Example:
     1036
     1037    ncols         3121
     1038    nrows         1800
     1039    xllcorner     722000
     1040    yllcorner     5893000
     1041    cellsize      25
     1042    NODATA_value  -9999
     1043    138.3698 137.4194 136.5062 135.5558 ..........
     1044
     1045    Also write accompanying file with same basename_in but extension .prj
     1046    used to fix the UTM zone, datum, false northings and eastings.
     1047
     1048    The prj format is assumed to be as
     1049
     1050    Projection    UTM
     1051    Zone          56
     1052    Datum         WGS84
     1053    Zunits        NO
     1054    Units         METERS
     1055    Spheroid      WGS84
     1056    Xshift        0.0000000000
     1057    Yshift        10000000.0000000000
     1058    Parameters
     1059
     1060
     1061    if quantity is given, out values from quantity otherwise default to
     1062    elevation
     1063   
     1064    if timestep (an index) is given, output quantity at that timestep
     1065
     1066    if reduction is given use that to reduce quantity over all timesteps.
     1067   
     1068    """
     1069    from Numeric import array, Float
     1070
     1071    #FIXME: Should be variable
     1072    datum = 'WGS84'
     1073    false_easting = 500000
     1074    false_northing = 10000000   
     1075   
     1076    if quantity is None:
     1077        quantity = 'elevation'
     1078
     1079    if reduction is None:
     1080        reduction = max
     1081
     1082    if basename_out is None:
     1083        basename_out = basename_in
     1084       
     1085    swwfile = basename_in + '.sww'
     1086    ascfile = basename_out + '.asc'
     1087    prjfile = basename_out + '.prj'   
     1088
     1089
     1090    if verbose: print 'Reading from %s' %swwfile
     1091    #Read sww file
     1092    from Scientific.IO.NetCDF import NetCDFFile
     1093    fid = NetCDFFile(swwfile)
     1094
     1095    #Get extent and reference
     1096    x = fid.variables['x'][:]
     1097    y = fid.variables['y'][:]
     1098
     1099    ymin = min(y); ymax = max(y)
     1100    xmin = min(x); xmax = max(x)
     1101   
     1102    number_of_timesteps = fid.dimensions['number_of_timesteps']
     1103    number_of_points = fid.dimensions['number_of_points']
     1104    if origin is None:
     1105        xllcorner = fid.xllcorner[0]
     1106        yllcorner = fid.yllcorner[0]
     1107        zone = fid.zone[0]
     1108    else:
     1109        zone = origin[0]
     1110        xllcorner = origin[1]
     1111        yllcorner = origin[2]
     1112       
     1113
     1114    #Get quantity and reduce if applicable
     1115    q = fid.variables[quantity]
     1116
     1117    if len(q.shape) == 2:
     1118        q_reduced = array( number_of_points, Float )
     1119       
     1120        for k in range(number_of_points):
     1121            q_reduced[k] = reduction( q[:,k] )
     1122
     1123        q = q_reduced
     1124
     1125    #Now q has dimension: number_of_points
     1126   
     1127    #Write prj file
     1128    prjid = open(prjfile, 'w')
     1129    prjid.write('Projection    %s\n' %'UTM')
     1130    prjid.write('Zone          %d\n' %zone)               
     1131    prjid.write('Datum         %s\n' %datum)
     1132    prjid.write('Zunits        NO\n')
     1133    prjid.write('Units         METERS\n')
     1134    prjid.write('Spheroid      %s\n' %datum)
     1135    prjid.write('Xshift        %f\n' %false_easting)
     1136    prjid.write('Yshift        %f\n' %false_northing)
     1137    prjid.write('Parameters\n')
     1138    prjid.close()
     1139
     1140    #Create grid
     1141    ncols = int((xmax-xmin)/cellsize)+1
     1142    nrows = int((ymax-ymin)/cellsize)+1
     1143
     1144    from Numeric import zeros, Float
     1145    points = zeros ( (ncols*nrows, 2), Float )
     1146
     1147
     1148    for i in xrange(ncols):
     1149        xg = i*cellsize
     1150        for j in xrange(nrows):
     1151            yg = j*cellsize
     1152            k = i*nrows + j
     1153
     1154            #print k, xg, yg
     1155            points[k,0] = xg
     1156            points[k,1] = yg
     1157
     1158    #Interpolate
     1159    from least_squares import Interpolation
     1160   
     1161
     1162
     1163   
     1164    #Close
     1165    fid.close()
     1166   
    10211167
    10221168def convert_dem_from_ascii2netcdf(basename_in, basename_out = None,
  • inundation/ga/storm_surge/pyvolution/interpolate_sww.py

    r934 r1137  
    2626
    2727class Interpolate_sww:
    28     def __init__(self,file_name, quantity_name):
     28    def __init__(self, file_name, quantity_name):
    2929
    3030        #It's bad to have the quantity_name passed in here.
     
    6262        self.quantity = quantity
    6363       
    64     def interpolate_xya(self,file_name):
     64    def interpolate_xya(self, file_name):
    6565        """
    6666        Given a point file, interpolate the height w.r.t. time at the points
  • inundation/ga/storm_surge/pyvolution/least_squares.py

    r1104 r1137  
    9999        old_title_list = mesh_dict['vertex_attribute_titles']
    100100       
    101     if verbose:print "tsh file loaded"
     101    if verbose: print 'tsh file %s loaded' %mesh_file
    102102   
    103103    # load in the .pts file
     
    302302         
    303303        """
    304 
     304        from util import ensure_numeric
     305       
    305306        #Convert input to Numeric arrays
    306         triangles = array(triangles).astype(Int)
    307         vertex_coordinates = array(vertex_coordinates).astype(Float)
     307        triangles = ensure_numeric(triangles, Int)
     308        vertex_coordinates = ensure_numeric(vertex_coordinates, Float)
    308309
    309310        #Build underlying mesh
    310311        if verbose: print 'Building mesh'
    311312        #self.mesh = General_mesh(vertex_coordinates, triangles,
    312         #FIXME: Trying the normal mesh while testing precrop
     313        #FIXME: Trying the normal mesh while testing precrop,
     314        #       The functionality of boundary_polygon is needed for that
    313315        self.mesh = Mesh(vertex_coordinates, triangles,
    314316                         origin = mesh_origin)
     
    387389
    388390        from quad import build_quadtree
     391        from util import ensure_numeric
    389392
    390393        if data_origin is None:
     
    393396       
    394397        #Convert input to Numeric arrays just in case.
    395         point_coordinates = array(point_coordinates).astype(Float)
     398        point_coordinates = ensure_numeric(point_coordinates, Float)       
    396399
    397400
     
    595598        """
    596599
    597 
     600        from util import ensure_numeric
    598601       
    599602        #Convert input to Numeric arrays
    600         point_coordinates = array(point_coordinates).astype(Float)
     603        point_coordinates = ensure_numeric(point_coordinates, Float)         
    601604       
    602605        #Build n x m interpolation matrix       
     
    764767          z: Single 1d vector or array of data at the point_coordinates.
    765768        """
    766 
     769       
    767770        #Convert input to Numeric arrays
    768         z = array(z).astype(Float)
    769 
     771        from util import ensure_numeric
     772        z = ensure_numeric(z, Float)
     773       
    770774        if len(z.shape) > 1 :
    771775            raise VectorShapeError, 'Can only deal with 1d data vector'
     
    808812
    809813            #Convert input to Numeric arrays
    810             z = array(z).astype(Float)
     814            from util import ensure_numeric
     815            z = ensure_numeric(z, Float)           
    811816           
    812817            #Build n x m interpolation matrix       
  • inundation/ga/storm_surge/pyvolution/test_data_manager.py

    r1134 r1137  
    365365
    366366
    367 
    368367        #Check contents
    369368        #Get NetCDF
     
    378377        stage = fid.variables['stage']
    379378
    380         #Check values
    381379        #Check values
    382380        Q = self.domain.quantities['stage']
     
    551549        fid.close()
    552550
    553         #Convert to NetCDF xya
     551        #Convert to NetCDF pts
    554552        convert_dem_from_ascii2netcdf(root)
    555553        dem2pts(root)
     
    582580        os.remove(root + '.asc')
    583581        os.remove(root + '.prj')
     582
     583
     584
     585    def test_sww2asc(self):
     586        """Test that sww information can be converted correctly to asc/prj
     587        format readable by e.g. ArcView
     588        """
     589
     590        import time, os
     591        from Numeric import array, zeros, allclose, Float, concatenate
     592        from Scientific.IO.NetCDF import NetCDFFile
     593
     594        #Setup
     595        self.domain.filename = 'datatest' + str(id(self))
     596        self.domain.set_datadir('.')
     597        self.domain.format = 'sww'
     598        self.domain.smooth = True
     599        self.domain.set_quantity('elevation', lambda x,y: -x-y)
     600       
     601        sww = get_dataobject(self.domain)
     602        sww.store_connectivity()
     603        sww.store_timestep('stage')
     604
     605        self.domain.evolve_to_end(finaltime = 0.01)
     606        sww.store_timestep('stage')
     607
     608
     609        #Check contents
     610        #Get NetCDF
     611
     612        fid = NetCDFFile(sww.filename, 'r')
     613
     614
     615        # Get the variables
     616        x = fid.variables['x']
     617        y = fid.variables['y']
     618        z = fid.variables['elevation']
     619        time = fid.variables['time']
     620        stage = fid.variables['stage']
     621        #print x[:]
     622        #print y[:]
     623        #print z[:]
     624        #print stage[:]       
     625
     626        #Export to ascii/prj files
     627        sww2asc(self.domain.filename,
     628                quantity = 'elevation',                         
     629                cellsize = 0.25,
     630                origin = (56,0,0))
     631
     632
     633        raise 'Under construction (Ole)'
     634
     635        #Check values
     636        #Q = self.domain.quantities['stage']
     637        #Q0 = Q.vertex_values[:,0]
     638        #Q1 = Q.vertex_values[:,1]
     639        #Q2 = Q.vertex_values[:,2]
     640        #
     641        #A = stage[1,:]
     642        #assert allclose(A[0], min(Q2[0], Q1[1]))
     643        #assert allclose(A[1], min(Q0[1], Q1[3], Q2[2]))
     644        #assert allclose(A[2], Q0[3])
     645        #assert allclose(A[3], min(Q0[0], Q1[5], Q2[4]))
     646        #
     647        ##Center point
     648        #assert allclose(A[4], min(Q1[0], Q2[1], Q0[2],\
     649        #                          Q0[5], Q2[6], Q1[7]))
     650
     651
     652        fid.close()
     653
     654        #Cleanup
     655        os.remove(sww.filename)
    584656
    585657
  • inundation/ga/storm_surge/pyvolution/test_util.py

    r1093 r1137  
    195195
    196196
    197 
     197    def test_ensure_numeric(self):
     198        from util import ensure_numeric
     199        from Numeric import ArrayType, Float, array
     200
     201        A = [1,2,3,4]
     202        B = ensure_numeric(A)
     203        assert type(B) == ArrayType
     204        assert B.typecode() == 'l'
     205        assert B[0] == 1 and B[1] == 2 and B[2] == 3 and B[3] == 4
     206
     207
     208        A = [1,2,3.14,4]
     209        B = ensure_numeric(A)
     210        assert type(B) == ArrayType
     211        assert B.typecode() == 'd'
     212        assert B[0] == 1 and B[1] == 2 and B[2] == 3.14 and B[3] == 4
     213
     214
     215        A = [1,2,3,4]
     216        B = ensure_numeric(A, Float)
     217        assert type(B) == ArrayType
     218        assert B.typecode() == 'd'
     219        assert B[0] == 1.0 and B[1] == 2.0 and B[2] == 3.0 and B[3] == 4.0
     220
     221
     222        A = [1,2,3,4]
     223        B = ensure_numeric(A, Float)
     224        assert type(B) == ArrayType
     225        assert B.typecode() == 'd'
     226        assert B[0] == 1.0 and B[1] == 2.0 and B[2] == 3.0 and B[3] == 4.0
     227
     228
     229        A = array([1,2,3,4])
     230        B = ensure_numeric(A)
     231        assert type(B) == ArrayType
     232        assert B.typecode() == 'l'       
     233        assert A == B   
     234        assert A is B   #Same object
     235
     236
     237        A = array([1,2,3,4])
     238        B = ensure_numeric(A, Float)
     239        assert type(B) == ArrayType
     240        assert B.typecode() == 'd'       
     241        assert A == B   
     242        assert A is not B   #Not the same object       
     243
     244
     245       
     246       
    198247
    199248    def test_spatio_temporal_file_function_time(self):
  • inundation/ga/storm_surge/pyvolution/util.py

    r1104 r1137  
    9494      return False 
    9595   
     96def ensure_numeric(A, typecode = None):
     97    """Ensure that sequence is a Numeric array.
     98    Inputs:
     99        A: Sequance. If A is already a Numeric array it will be returned
     100                     unaltered
     101                     If not, an attempt is made to convert it to a Numeric
     102                     array
     103        typecode: Numeric type. If specified, use this in the conversion.
     104                                If not, let Numeric decide
     105
     106    This function is necessary as array(A) can cause memory overflow.
     107    """
     108
     109    from Numeric import ArrayType, array
     110
     111    if typecode is None:
     112        if type(A) == ArrayType:
     113            return A
     114        else:
     115            return array(A)
     116    else:
     117        if type(A) == ArrayType:
     118            if A.typecode == typecode:
     119                return array(A)           
     120            else:
     121                return A.astype(typecode)
     122        else:
     123            return array(A).astype(typecode)
     124       
     125   
    96126
    97127def file_function(filename, domain=None, quantities = None, interpolation_points = None, verbose = False):
     
    253283       
    254284            try:
    255                 P = array(interpolation_points)
     285                P = ensure_numeric(interpolation_points)
    256286            except:
    257287                msg = 'Interpolation points must be an N x 2 Numeric array or a list of points\n'
     
    498528            values.append(float(value))
    499529
    500         q = array(values)
     530        q = ensure_numeric(values)
    501531       
    502532        msg = 'ERROR: File must contain at least one independent value'
     
    724754            values.append(float(value))
    725755
    726         q = array(values)
     756        q = ensure_numeric(values)
    727757       
    728758        msg = 'ERROR: File must contain at least one independent value'
     
    932962    if verbose: print 'Checking input to inside_polygon'   
    933963    try:
    934         points = array(points).astype(Float)       
     964        points = ensure_numeric(points, Float)             
    935965    except:
    936966        msg = 'Points could not be converted to Numeric array'
     
    938968       
    939969    try:
    940         polygon = array(polygon).astype(Float)             
     970        polygon = ensure_numeric(polygon, Float)           
    941971    except:
    942972        msg = 'Polygon could not be converted to Numeric array'
     
    967997    if verbose: print 'Checking input to outside_polygon'   
    968998    try:
    969         points = array(points).astype(Float)       
     999        points = ensure_numeric(points, Float)             
    9701000    except:
    9711001        msg = 'Points could not be converted to Numeric array'
     
    9731003       
    9741004    try:
    975         polygon = array(polygon).astype(Float)             
     1005        polygon = ensure_numeric(polygon, Float)           
    9761006    except:
    9771007        msg = 'Polygon could not be converted to Numeric array'
     
    10411071    #Input checks
    10421072    try:
    1043         points = array(points).astype(Float)       
     1073        points = ensure_numeric(points, Float)             
    10441074    except:
    10451075        msg = 'Points could not be converted to Numeric array'
     
    10471077       
    10481078    try:
    1049         polygon = array(polygon).astype(Float)             
     1079        polygon = ensure_numeric(polygon, Float)           
    10501080    except:
    10511081        msg = 'Polygon could not be converted to Numeric array'
     
    11341164    #Input checks
    11351165    try:
    1136         #FIXME: This is where it can die due to lack of memeory
    1137         #Maybe comment out and test for Numeric type
    1138         points = array(points).astype(Float)
     1166        points = ensure_numeric(points, Float)
    11391167    except:
    11401168        msg = 'Points could not be converted to Numeric array'
     
    11431171    #if verbose: print 'Checking input to separate_points_by_polygon 2'
    11441172    try:
    1145         #FIXME: SAme thing
    1146         polygon = array(polygon).astype(Float)
     1173        polygon = ensure_numeric(polygon, Float)
    11471174    except:
    11481175        msg = 'Polygon could not be converted to Numeric array'
  • inundation/ga/storm_surge/pyvolution/util_ext.h

    r907 r1137  
    125125 
    126126  //Convert to consecutive array
    127   A = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*) B, B -> descr -> type, 0, 0);
     127  A = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*) B,
     128                                                    B -> descr -> type, 0, 0);
    128129 
    129130  Py_DECREF(B); //FIXME: Is this really needed??
  • inundation/ga/storm_surge/wiki/issues.txt

    r652 r1137  
    22OPEN ISSUES:
    33------------
     4
     5
     6Issue: Pmesh do not write in msh format
     7Importance: Mid-High
     8Action: See under pmesh/documentation
     9
     10Issue: geo_reference is not passed into domain and further on to sww file. Hence we can't export results properly to e.g GIS
     11Importance: High
     12Action: Make it happen!
     13
    414
    515 
Note: See TracChangeset for help on using the changeset viewer.