Raster

To do:
  1. Read, write, analyze, and visualise gridded raster data

  2. Convert shape data to raster data

  3. Convert raster data to shapefile


class hydro_raster.Raster.Raster(source_file=None, array=None, header=None, xllcorner=0, yllcorner=0, cellsize=100, NODATA_value=-9999, crs=None, num_header_rows=6, read_extent=None)

To deal with raster data with a ESRI ASCII or GTiff format

source_file

file name to read grid data

output_file

file name to write a raster object

array

a numpy array storing grid cell values

header

a dict storing reference information of the grid, with keys: nrows, ncols, xllcorner, yllcorner, cellsize, NODATA_value

extent

a tuple storing outline limits of the raster (left, right, bottom, top)

shape

shape of the Raster value array

cellsize

the length of each square cell

extent_dict

a dictionary storing outline limits of the raster

wkt

(string) the Well-Known_Text (wkt) projection information

__init__(source_file=None, array=None, header=None, xllcorner=0, yllcorner=0, cellsize=100, NODATA_value=-9999, crs=None, num_header_rows=6, read_extent=None)

Initialise the object

Parameters:
  • source_file – name of a asc/tif file if a file read is needed

  • array – values in each raster cell [a numpy array]

  • header – georeference of the raster [a dictionary containing 6 keys] nrows, nclos [int] cellsize, xllcorner, yllcorner NODATA_value

  • crs – coordinate reference system, either epsg(epsg code, int) or wkt(string), or a rasterio.crs object

  • read_extent (dict, optional) – extent window (left, right, bottom, top in map coordinates) to read part of the tif. Defaults to None.

Example: define a raster object with a random array

array = np.random.rand(10, 10) header = {‘ncols’:array.shape[1], ‘nrows’:array.shape[0],

‘xllcorner’:0, ‘yllcorner’:1, ‘cellsize’:100, ‘NODATA_value’:-9999}

obj_ras = Raster(array=array, header=header) obj_ras.mapshow() %plot map

assign_to(new_header)

Assign_to the object to a new grid defined by new_header. If their cellsizes are not equal, the original Raster will be resampled to the target grid.

Parameters:

new_header (dict) – Raster header dict

Returns:

A newly defined grid

Return type:

Raster object

clip(clip_mask=None)

clip raster according to a mask

Parameters:

mask – 1. string name of a shapefile or 2. 2-col numpy array giving X and Y coords in each column to shape the mask polygon

Returns:

a new raster object

Return type:

Raster

duplicate()

duplicate the Raster object and return a new one so that change the new object will not affect the original one

get_summary()

Get information summary of the object

Returns:

summary – information summary of the object.

Return type:

dict

grid_interpolate(value_grid, method='nearest')

Interpolate values of a grid to all cells on the Raster object

2D interpolate

Parameters:
  • value_grid – a grid file string or Raster object

  • method – {‘linear’, ‘nearest’, ‘cubic’}, optional Method of interpolation.

Returns:

the interpolated grid with the same size of the self

object

Return type:

numpy array

grid_resample_nearest(newsize)

resample a grid to a new grid resolution via nearest interpolation

Alias: GridResample

hillshade(**kwargs)

Draw a hillshade map

mapshow(**kwargs)

Display raster data without projection

Parameters:
  • figname – str, the file name to export map

  • figsize – tuple, the size of map

  • dpi – scalar, The resolution in dots per inch

  • cax_str – str, the title of the colorbar

  • relocate – True|False, relocate the origin of the grid to (0, 0)

  • scale_ratio – 1|1000, axis unit 1 m or 1000 meter

  • vmin – define the data range that the colormap covers

  • vmax – define the data range that the colormap covers

  • ytick_labelrotation – degree to rotate tick labels on y axis

Example

mapshow(ax=ax, figname=’my_fig’, figsize=(6, 8), dpi=300,

title=’My map’, cax=True, cax_str=’Meter’, relocate=False, scale_ratio=1000, ytick_labelrotation=90)

paste_on(obj_large, ignore_nan=True)

Paste the object to a larger grid defined by obj_large and replace corresponding grid values with the object array, their cellsizes MUST be equal

Parameters:
  • obj_large (Raster object) – target object

  • ignore_nan (bool, optional) – indicate whether paste nan values. Defaults to True.

Returns:

target object with new array values pasted

Return type:

Raster object

point_interpolate(points, values, method='nearest')

Interpolate values of 2D points to all cells on the Raster object

2D interpolate

Parameters:
  • points – ndarray of floats, shape (n, 2) Data point coordinates. Can either be an array of shape (n, 2), or a tuple of ndim arrays.

  • values – ndarray of float or complex, shape (n, ) Data values.

  • method – {‘linear’, ‘nearest’, ‘cubic’}, optional Method of interpolation.

rankshow(**kwargs)

Display array values in ranks

Parameters:
  • breaks – list of values to define rank. Array values lower than the first break value are set as nodata.

  • color – color series of the ranks

  • ylabelrotation – scalar giving degree to rotate yticklabel

  • legend_kw – dict, keyword arguments to set legend. A colobar rather than a legend be displayed if legend_kw is None.

  • **kwargs – keywords argument of function imshow

Example

rankshow(figname=None, figsize=None,

dpi=200, ax=None, color=’Blues’, breaks=[0.2, 0.3, 0.5, 1, 2], legend_kw={‘loc’:’upper left’, ‘facecolor’:None,

‘fontsize’:’small’, ‘title’:’depth(m)’, ‘labelspacing’:0.1},

ytick_labelrotation=None, relocate=False, scale_ratio=1, alpha=1)

rasterize(shp_filename=None, shape_data=None, attribute=None, include_nan=False)
rasterize a shapefile to the raster object and return a bool array

with Ture value in and on the polygon/polyline or return an array with values burned from one shapefile attritute whose name is given by attr_name

Parameters:
  • shp_filename (str|shapefile name. Must has the same) – crs with the raster file

  • shape_data (geopandas dataframe or shapely geometry. if shp_filename) – not given, this input will be used as the shape data

  • attribute (str or a list of digit values to rasterize with shape,) – name of the shape attribute to be burned into the raster. The default is None.

  • include_nan (logical, optional) – whether include index of nan cells. The default is False.

Returns:

out_array – Array providing values of one attribute of the shapefile

Return type:

numpy array

rect_clip(clip_extent, return_slice=False)

clip raster according to a rectangle extent

Parameters:
  • clip_extent – list of [left, right, bottom, top]

  • return_slice – logical. If True, the slices of object to clip array will be returned as an additional return value.

Returns:

a new raster object

Return type:

Raster

reproject(dst_epsg, output_file=None)

Reproject the raster to a different coordinate referenece system

Parameters:
  • output_file – a string to give output file name

  • src_epsg – int scalar to give EPSG code of the coordinate reference system of the original dataset, default is 27700 for BNG

Returns:

destination rasterio dataset

Return type:

dst_rio

resample(new_cellsize, method='bilinear')

Resample the raster object to a new resolution

Parameters:
  • new_cellsize – scalar, the resoltion of the new raster object

  • method – string, one of the values including ‘nearest’, ‘bilinear’,

  • 'cubic'

  • 'cubic_spline'

  • 'lanczos'

  • 'average'

  • 'mode'

  • 'gauss'

:param : :param ‘max’: :param ‘min’: :param ‘med’: :param ‘q1’: :param ‘q3’:

Returns:

Raster object

set_crs(crs)

set reference coordinate system :param crs: epsg code|wkt|asterio.crs object :type crs: int|string|rasterio.crs object

set_meta(src_epsg=27700)

set rasterio meta data

Parameters:

src_epsg (int, optional) – epsg code. Defaults to None.

set_nodata(NODATA_value)

Set nodata value of the object

Parameters:

NODATA_value (int) – nodata value

to_int(dtype='int32')

Convert data array to int type nan value will be replaced as NODATA_value, default: -9999

Return type:

None.

to_points()

Get X and Y coordinates of all raster cells

Returns:

coordinates of the raster object

Return type:

numpy array

to_rasterio_ds()

convert object to a rasterio dataset

Returns:

ds_rio

Return type:

rasterio dataset

vectorize(valid_mask=None)

vectorize raster data array to a geopandas polygon dataframe which can be written as ESRI shapefile or other formats

Parameters:

valid_mask (logical numpy array, optional) – define the cells to be rasterized. The default is None.

Returns:

gdf

Return type:

geopandas dataframe

vectorshow(obj_y, **kwargs)

plot velocity map of U and V, whose values stored in two raster objects seperately

write(output_file, compression=False)

Export to a file, tif, asc, txt, or gz

Parameters:
  • output_file (string) – file name, ends with tif, asc, txt, or gz.

  • compression (bool, optional) – flag to indicate whether compress or not. The default is False.. Defaults to False.

write_asc(output_file, compression=False, export_prj=False)

write raster as asc format file

Parameters:
  • output_file (string) – output file path

  • compression (bool, optional) – _description_. Defaults to False.

  • export_prj (bool, optional) – indicate whether compress write the asc file as gz. Defaults to False.

write_tif(output_file, src_epsg=27700, dtype='float64')

Convert to a rasterio dataset

Parameters:
  • output_file – a string to give output file name

  • src_epsg – int scalar to give EPSG code of the coordinate reference system of the original dataset, default is 27700 for BNG

hydro_raster.Raster.main()

Main function

hydro_raster.Raster.merge(obj_origin, obj_target, resample_method='bilinear')

Merge the obj_origin to obj_target

assign grid values in the origin Raster to the cooresponding grid cells in the target object. If cellsize are not equal, the origin Raster will be firstly resampled to the target object.

Parameters:
  • obj_origin – (Raster) original raster

  • obj_target – (Raster) target raster