Changeset 9042


Ignore:
Timestamp:
Dec 12, 2013, 5:09:10 PM (11 years ago)
Author:
davies
Message:

Adding code to make georeferenced rasters from sww to plot_utils

Location:
trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/anuga_core/source/anuga/utilities/plot_utils.py

    r9036 r9042  
    2929                         time step in an sww file (needs both
    3030                         vertex and centroid value input).
     31
     32    util.Make_Geotiff -- convert sww centroids to a georeferenced tiff
    3133 
    3234    Here is an example ipython session which uses some of these functions:
     
    519521
    520522
    521 
     523def make_grid(data, lats, lons, fileName, EPSG_CODE=None, proj4string=None):
     524    """
     525        Convert data,lats,lons to a georeferenced raster tif
     526        INPUT: data -- array with desired raster cell values
     527               lats -- 1d array with 'latitude' or 'y' range
     528               lons -- 1D array with 'longitude' or 'x' range
     529               fileName -- name of file to write to
     530               EPSG_CODE -- Integer code with projection information in EPSG format
     531               proj4string -- proj4string with projection information
     532
     533        NOTE: proj4string is used in preference to EPSG_CODE if available
     534    """
     535    try:
     536        import gdal
     537        import osr
     538    except:
     539        raise Exception, 'Cannot find gdal and/or osr python modules'
     540
     541    xres = lons[1] - lons[0]
     542    yres = lats[1] - lats[0]
     543
     544    ysize = len(lats)
     545    xsize = len(lons)
     546
     547    # Assume data/lats/longs refer to cell centres, and compute lower left coordinate
     548    llx = lons[0] - (xres / 2.)
     549    lly = lats[0] - (yres / 2.)
     550
     551    # GDAL magic to make the tif
     552    driver = gdal.GetDriverByName('GTiff')
     553    ds = driver.Create(fileName, xsize, ysize, 1, gdal.GDT_Float32)
     554
     555    srs = osr.SpatialReference()
     556    if(proj4string is not None):
     557        srs.ImportFromProj4(proj4string)
     558    elif(EPSG_CODE is not None):
     559        srs.ImportFromEPSG(EPSG_CODE)
     560    else:
     561        raise Exception, 'No spatial reference information given'
     562
     563    ds.SetProjection(srs.ExportToWkt())
     564
     565    gt = [llx, xres, 0, lly, 0, yres ]
     566    ds.SetGeoTransform(gt)
     567
     568    outband = ds.GetRasterBand(1)
     569    outband.WriteArray(data)
     570
     571    ds = None
     572    return
     573
     574##################################################################################
     575
     576def Make_Geotif(swwFile, output_quantity='depth',
     577             myTimeStep=1, CellSize=5.0,
     578             lower_left=None, upper_right=None,
     579             EPSG_CODE=None,
     580             proj4string=None,
     581             velocity_extrapolation=True,
     582             min_allowed_height=1.0e-05,
     583             output_dir='TIFS',
     584             verbose=False):
     585    """
     586        Make a georeferenced tif by nearest-neighbour interpolation of sww file outputs.
     587
     588        You must supply projection information as either a proj4string or an integer EPSG_CODE (but not both!)
     589
     590        INPUTS: swwFile -- name of sww file
     591                output_quantity -- quantity to plot ('depth' or 'velocity' or 'stage' or 'elevation' or 'depthIntegratedVelocity')
     592                myTimeStep -- time-index of swwFile to plot, or 'last', or 'max'
     593                CellSize -- approximate pixel size for output raster [adapted to fit lower_left / upper_right]
     594                lower_left -- [x0,y0] of lower left corner. If None, use extent of swwFile.
     595                upper_right -- [x1,y1] of upper right corner. If None, use extent of swwFile.
     596                EPSG_CODE -- Projection information as an integer EPSG code (e.g. 3123 for PRS92 Zone 3, 32756 for UTM Zone 56 S, etc).
     597                             Google for info on EPSG Codes
     598                proj4string -- Projection information as a proj4string (e.g. '+init=epsg:3123')
     599                             Google for info on proj4strings.
     600                velocity_extrapolation -- Compute velocity assuming the code extrapolates with velocity (instead of momentum)?
     601                min_allowed_height -- Minimum allowed height from ANUGA
     602                output_dir -- Write outputs to this directory
     603               
     604    """
     605    try:
     606        import gdal
     607        import osr
     608        import scipy.io
     609        import scipy.interpolate
     610        import anuga
     611        from anuga.utilities import plot_utils as util
     612        import os
     613    except:
     614        raise Exception, 'Required modules not installed for mkgeotif'
     615
     616
     617    if(((EPSG_CODE is None) & (proj4string is None) )|
     618       ((EPSG_CODE is not None) & (proj4string is not None))):
     619        raise Exception, 'Must specify EITHER an integer EPSG_CODE describing the file projection, OR a proj4string'
     620
     621    # Make output_dir
     622    try:
     623        os.mkdir(output_dir)
     624    except:
     625        pass
     626
     627    # Read in ANUGA outputs
     628    # FIXME: It would be good to support reading of data subsets
     629    if(verbose):
     630        print 'Reading sww File ...'
     631    p=util.get_output(swwFile,min_allowed_height)
     632    p2=util.get_centroids(p,velocity_extrapolation)
     633    swwIn=scipy.io.netcdf_file(swwFile)
     634    xllcorner=swwIn.xllcorner
     635    yllcorner=swwIn.yllcorner
     636
     637    if(myTimeStep=='last'):
     638        myTimeStep=len(p.time)-1
     639   
     640
     641    if(verbose):
     642        print 'Extracting required data ...'
     643    # Get ANUGA points
     644    swwX=p2.x+xllcorner
     645    swwY=p2.y+yllcorner
     646
     647    if(myTimeStep!='max'):
     648        swwStage=p2.stage[myTimeStep,:]
     649        swwHeight=p2.height[myTimeStep,:]
     650        swwVel=p2.vel[myTimeStep,:]
     651        # Use if-statement here to reduce computation
     652        if(output_quantity=='depthIntegratedVelocity'):
     653            swwDIVel=(p2.xmom[myTimeStep,:]**2+p2.ymom[myTimeStep,:]**2)**0.5
     654        timestepString=str(round(p2.time[myTimeStep]))
     655    else:
     656        swwStage=p2.stage.max(axis=0)
     657        swwHeight=p2.height.max(axis=0)
     658        swwVel=p2.vel.max(axis=0)
     659        # Use if-statement here to reduce computation
     660        if(output_quantity=='depthIntegratedVelocity'):
     661            swwDIVel=((p2.xmom**2+p2.ymom**2).max(axis=0))**0.5
     662        timestepString='max'
     663       
     664    # Make name for output file
     665    output_name=output_dir+'/'+os.path.splitext(os.path.basename(swwFile))[0] + '_'+\
     666                output_quantity+'_'+timestepString+\
     667                '_'+str(myTimeStep)+'.tif'
     668
     669    if(verbose):
     670        print 'Computing grid of output locations...'
     671    # Get points where we want raster cells
     672    if(lower_left is None):
     673        lower_left=[swwX.min(),swwY.min()]
     674    if(upper_right is None):
     675        upper_right=[swwX.max(),swwY.max()]
     676
     677    nx=round((upper_right[0]-lower_left[0])*1.0/(1.0*CellSize)) + 1
     678    xres=(upper_right[0]-lower_left[0])*1.0/(1.0*(nx-1))
     679    desiredX=scipy.arange(lower_left[0], upper_right[0],xres )
     680    ny=round((upper_right[1]-lower_left[1])*1.0/(1.0*CellSize)) + 1
     681    yres=(upper_right[1]-lower_left[1])*1.0/(1.0*(ny-1))
     682    desiredY=scipy.arange(lower_left[1], upper_right[1], yres)
     683
     684    gridX, gridY=scipy.meshgrid(desiredX,desiredY)
     685
     686    # Make functions to interpolate quantities at points
     687    if(verbose):
     688        print 'Making interpolation functions...'
     689    swwXY=scipy.array([swwX[:],swwY[:]]).transpose()
     690    if(output_quantity=='stage'):
     691        qFun=scipy.interpolate.NearestNDInterpolator(swwXY,swwStage.transpose())
     692    elif(output_quantity=='velocity'):
     693        qFun=scipy.interpolate.NearestNDInterpolator(swwXY,swwVel.transpose())
     694    elif(output_quantity=='elevation'):
     695        qFun=scipy.interpolate.NearestNDInterpolator(swwXY,p2.elev.transpose())
     696    elif(output_quantity=='depth'):
     697        qFun=scipy.interpolate.NearestNDInterpolator(swwXY,swwHeight.transpose())
     698    elif(output_quantity=='depthIntegratedVelocity'):
     699        qFun=scipy.interpolate.NearestNDInterpolator(swwXY,swwDIVel.transpose())
     700    else:
     701        raise Exception, 'output_quantity not available -- check if it is spelled correctly'
     702
     703    if(verbose):
     704        print 'Interpolating'
     705    gridq=qFun(scipy.array([scipy.concatenate(gridX),scipy.concatenate(gridY)]).transpose()).transpose()
     706    gridq.shape=(len(desiredY),len(desiredX))
     707
     708    if(verbose):
     709        print 'Making raster ...'
     710    make_grid(gridq,desiredY,desiredX, output_name,EPSG_CODE=EPSG_CODE, proj4string=proj4string)
     711
     712    return
  • trunk/anuga_work/development/gareth/experimental/bal_and/plot_utils.py

    r9040 r9042  
    576576        import scipy.interpolate
    577577        import anuga
    578         from anuga.utilities import plot_utils as util
    579578        import os
    580579    except:
  • trunk/anuga_work/development/gareth/tests/runup_sinusoid/runup_sinusoid.py

    r9033 r9042  
    1515#from balanced_basic import *
    1616#from balanced_dev import *
    17 #from anuga import Domain as Domain
    18 from bal_and import *
     17from anuga import Domain as Domain
     18#from bal_and import *
    1919#from anuga_tsunami import *
    2020
     
    2626domain=Domain(points,vertices,boundary)    # Create Domain
    2727domain.set_name('runup_sinusoid_v2')                         # Output to file runup.sww
    28 domain.set_store_centroids(True)
     28#domain.set_store_centroids(True)
    2929#domain.set_timestepping_method('euler')
    30 #domain.set_flow_algorithm('DE1')
     30domain.set_flow_algorithm('DE1')
     31domain.minimum_storable_height=1.0e-03
     32domain.set_store_vertices_uniquely()
    3133#------------------
    3234# Define topography
  • trunk/anuga_work/development/gareth/tests/taguig_parallel/runtaguig.py

    r9040 r9042  
    7777barrier()
    7878
     79## Force first order
     80#domain.beta_w=0.0
     81#domain.beta_w_dry=0.0
     82#domain.beta_uh=0.0
     83#domain.beta_uh_dry=0.0
     84#domain.beta_vh=0.0
     85#domain.beta_vh_dry=0.0
     86###
     87
    7988domain.set_quantity('stage', 1.0)
    8089domain.set_quantity('friction', 0.03)
    8190
    8291# Rain
    83 rain_mps=90.0/(1000*3600) # 90mm/hr is meters-per-second
    84 def myrain(t):
    85     return(rain_mps)
    86 rainin_term=anuga.operators.rate_operators.Rate_operator(domain,rate=myrain)
     92#rain_mps=90.0/(1000*3600) # 90mm/hr is meters-per-second
     93#def myrain(t):
     94#    return(rain_mps)
     95#rainin_term=anuga.operators.rate_operators.Rate_operator(domain,rate=myrain)
    8796
    8897## Boundary conditions
Note: See TracChangeset for help on using the changeset viewer.