예제 #1
0
def bingrid_to_label(file_grid, file_label='label.dat', write_file=False):
    """
    * Objective
      Replace values of the grid by the label of the cells.
      The label are assigned from 0 to nb_cell, from West to East, North to South.
    * Input
      file_bin_grid: A binary grid file (whatever it is).
    * Output
      tab: a 1D array with nb_cell components.
    """
    tab, headers = arcfltgrid.read(file_grid)

    nrows=np.shape(tab)[0]
    ncols=np.shape(tab)[1]
    tab=np.reshape(tab,ncols*nrows)
    ind=np.where(tab>-99)
    tab_label=np.arange(len(tab[ind]))
    for i in tab_label:
        tab[ind[0][i]]=i
    tab=np.reshape(tab,(nrows,ncols))
    tab=tab.astype('int32')

    if write_file:
        np.savetxt(file_label, tab)

    return tab
예제 #2
0
def krige_to_grid(grid_fname, obs_x, obs_y, obs_data, vgm_par):
    """Interpolate point data onto a grid using Kriging.

    Interpolate point data onto a regular rectangular grid of square cells using
    Kriging with a predefined semi-variogram.  The observed data locations must
    be specified in the same projection and coordinate system as the grid, which
    is defined in an ArcGIS raster file.

    Parameters
    ----------
    grid_fname : string
        Filename of an ArcGIS float grid raster defining the required grid to
        Krige onto.  All cells are included regardless of their value.
    obs_x : array_like
        The x coordinates of the observation locations.
    obs_y : array_like
        The y coordinates of the observation locations.
    obs_data : array_like
        The data values at the observation locations.
    vgm : dict
        A dictionary describing the semi-variogram model.  Required keys are:
        'model' can be one of {'Lin', 'Exp', 'Sph', 'Gau'}
        'nugget' must be a scalar
        'range' must be a scalar
        'sill' must be a scalar

    Returns
    -------
    kriged_est : 2darray
        A 2D array containing the Kriged estimates at each point on the
        specified rectangular grid.

    Notes
    -----
    This function requires that R, RPy and the R gstat library are correctly
    installed.

    """
    grid, headers = arcfltgrid.read(grid_fname)
    cols = headers[0]
    rows = headers[1]
    x0 = headers[2]
    y0 = headers[3]
    cell_size = headers[4]
    # TO DO: adjust x0, y0 by 0.5*cell_size if llcorner..

    # define the grid (pixel centre's)
    xt, yt = np.meshgrid(np.linspace(x0, x0 + (cols-1)*cell_size, num=cols),
                         np.linspace(y0 + (rows-1)*cell_size, y0, num=rows))

    xt = xt.flatten()
    yt = yt.flatten()

    # Krige using gstat via RPy
    r.library('gstat')
    rpy.set_default_mode(rpy.NO_CONVERSION)

    obs_frame = r.data_frame(x=obs_x, y=obs_y, data=obs_data)
    target_grid = r.data_frame(x=xt, y=yt)

    v = r.vgm(vgm_par['sill'], vgm_par['model'],
              vgm_par['range'], vgm_par['nugget'])

    result = r.krige(r('data ~ 1'), r('~ x + y'),
                     obs_frame, target_grid, model=v)

    rpy.set_default_mode(rpy.BASIC_CONVERSION)

    result = result.as_py()

    kriged_est = np.array(result['var1.pred'])
    kriged_est = kriged_est.reshape(rows, cols)

    return kriged_est
예제 #3
0
def create_channel_slope_file(file_flowdir, file_DEM, file_slope_degree):
    """Compute the channel slopes from 8D flow direction and a DEM.

    Calculate the slope from the centre of each cell in the catchment DEM
    to it's downstream neighbour. The calculated slopes are written to
    an ArcGIS Float grid file. This file is required by the TOPKAPI model
    for the generation of a parameter file.

    Parameters
    ----------
    file_flowdir : string
        Name of an ArcGIS binary Float file containing the flow
        direction raster.
    file_DEM : string
        Name of an ArcGIS binary Float file containing the DEM raster.
    file_slope_degree : string
        Name of an ArcGIS binary Float file for the output raster.

    """
    dem, headers = arcfltgrid.read(file_DEM)
    nrows=np.shape(dem)[0]
    ncols=np.shape(dem)[1]
    Xcell = headers[4]

    flowdir, headers = arcfltgrid.read(file_flowdir)

    tab_label = bingrid_to_label(file_DEM)
    tab_slope_degree = np.array(tab_label, np.float32)

    for i in range(nrows):
        for j in range(ncols):

            label = tab_label[i,j]
            direction = flowdir[i,j]

            if label > 0:
                if direction==64:
                    dist=Xcell
                    x=i-1
                    y=j
                if direction==1:
                    dist=Xcell
                    x=i
                    y=j+1
                if direction==4:
                    dist=Xcell
                    x=i+1
                    y=j
                if direction==16:
                    dist=Xcell
                    x=i
                    y=j-1
                if direction==32:
                    dist=Xcell*(2**0.5)
                    x=i-1
                    y=j-1
                if direction==128:
                    dist=Xcell*(2**0.5)
                    x=i-1
                    y=j+1
                if direction==2:
                    dist=Xcell*(2**0.5)
                    x=i+1
                    y=j+1
                if direction==8:
                    dist=Xcell*(2**0.5)
                    x=i+1
                    y=j-1

                if tab_label[x,y] >= 0:
                    if dem[x,y] < dem[i,j]:
                        tab_slope_degree[i,j] = np.arctan((dem[i,j]-dem[x,y])
                                                          /dist) * 180./np.pi
                    if dem[x,y] == dem[i,j]:
                        tab_slope_degree[i,j] = 0.0
                    if dem[x,y] > dem[i,j]:
                        print('Negative slope cell', tab_label[i,j], \
                            direction, tab_label[x,y], dem[i,j], dem[x,y]
                        tab_slope_degree[i,j] = np.arctan((dem[i,j]-dem[x,y])
                                                          /dist) * 180./np.pi)
                else:
                    tab_slope_degree[i,j] = -9999
                    print('Downslope cell external to the catchment...')
                    print(tab_label[i,j], direction, \
                          tab_label[x,y], dem[i,j], dem[x,y])

    # write slope file
    tab_slope_degree.tofile(file_slope_degree)

    if file_DEM[-4:] == '.flt':
        copyfile(file_DEM[:-4] + '.hdr', file_slope_degree[:-4] + '.hdr')
    else:
        copyfile(file_DEM + '.hdr', file_slope_degree[:-4] + '.hdr')
예제 #4
0
def krige_to_grid(grid_fname, obs_x, obs_y, obs_data, vgm_par):
    """Interpolate point data onto a grid using Kriging.

    Interpolate point data onto a regular rectangular grid of square cells using
    Kriging with a predefined semi-variogram.  The observed data locations must
    be specified in the same projection and coordinate system as the grid, which
    is defined in an ArcGIS raster file.

    Parameters
    ----------
    grid_fname : string
        Filename of an ArcGIS float grid raster defining the required grid to
        Krige onto.  All cells are included regardless of their value.
    obs_x : array_like
        The x coordinates of the observation locations.
    obs_y : array_like
        The y coordinates of the observation locations.
    obs_data : array_like
        The data values at the observation locations.
    vgm : dict
        A dictionary describing the semi-variogram model.  Required keys are:
        'model' can be one of {'Lin', 'Exp', 'Sph', 'Gau'}
        'nugget' must be a scalar
        'range' must be a scalar
        'sill' must be a scalar

    Returns
    -------
    kriged_est : 2darray
        A 2D array containing the Kriged estimates at each point on the
        specified rectangular grid.

    Notes
    -----
    This function requires that R, RPy and the R gstat library are correctly
    installed.

    """
    grid, headers = arcfltgrid.read(grid_fname)
    cols = headers[0]
    rows = headers[1]
    x0 = headers[2]
    y0 = headers[3]
    cell_size = headers[4]
    # TO DO: adjust x0, y0 by 0.5*cell_size if llcorner..

    # define the grid (pixel centre's)
    xt, yt = np.meshgrid(
        np.linspace(x0, x0 + (cols - 1) * cell_size, num=cols),
        np.linspace(y0 + (rows - 1) * cell_size, y0, num=rows))

    xt = xt.flatten()
    yt = yt.flatten()

    # Krige using gstat via RPy
    r.library('gstat')
    rpy.set_default_mode(rpy.NO_CONVERSION)

    obs_frame = r.data_frame(x=obs_x, y=obs_y, data=obs_data)
    target_grid = r.data_frame(x=xt, y=yt)

    v = r.vgm(vgm_par['sill'], vgm_par['model'], vgm_par['range'],
              vgm_par['nugget'])

    result = r.krige(r('data ~ 1'),
                     r('~ x + y'),
                     obs_frame,
                     target_grid,
                     model=v)

    rpy.set_default_mode(rpy.BASIC_CONVERSION)

    result = result.as_py()

    kriged_est = np.array(result['var1.pred'])
    kriged_est = kriged_est.reshape(rows, cols)

    return kriged_est