Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

DEM PROGRAM UNDERSTANDING

basin = NLDI().get_basins(station_id)
Here, basin is a dataframe with the geometry or co-ordinates of the basins boundary derived
from NLDI (Hydro Network Linked Data Index)
Now, plot the dataframe using plot() for user to view it at once.
The shape file (SHP file) is openable in google earth.
SHP files can be an ESRI Shapefile, which contains geographical information like street
points, points of interest, and zip code boundaries.
basin.to_file(filename= ‘’,driver=(by default it is ESRI shadefile), mode=’w’)
This writes the GeoDataframe to a file.
GeoPandas is based on the pandas. It extends pandas data types to include geometry columns
and perform spatial operations. So, anyone familiar with pandas can easily adopt GeoPandas.
geopandas.GeoDataFrame.to_file — GeoPandas 0.10.2+0.g04d377f.dirty documentation

Extents of the basin (watershed) is obtained using .total_bounds


extents_basin=basin.total_bounds
Returns a tuple containing min x, min y, max x, max y values for the bounds of the series as a
whole. GeoSeries.total_bounds
Then we will find the bounding extents using math floor and ceil function

math.floor() function returns the largest integer not greater than x. If number is already integer,
same number is returned. Syntax: math.floor(x) Parameter: x: This is a numeric expression.
Math.ceil() returns smallest integer greater than x.
Matplotlib’spyplot API has a convenience function called subplots() which acts as a utility
wrapper and helps in creating common layouts of subplots, including the enclosing figure
object, in a single call.
Plt.subplots(nrows, ncols)
The two integer arguments to this function specify the number of rows and columns of the
subplot grid. The function returns a figure object and a tuple containing axes objects equal to
nrows*ncols. Each axes object is accessible by its index. Here we create a subplot of 2 rows
by 2 columns and display 4 different plots in each subplot.
import matplotlib.pyplot as plt
fig,a = plt.subplots(2,2)
import numpy as np
x = np.arange(1,5)
a[0][0].plot(x,x*x)
a[0][0].set_title('square')
a[0][1].plot(x,np.sqrt(x))
a[0][1].set_title('square root')
a[1][0].plot(x,np.exp(x))
a[1][0].set_title('exp')
a[1][1].plot(x,np.log10(x))
a[1][1].set_title('log')
plt.show()
The subplots() Function

The subplots() function takes three arguments that describes the layout of the figure.

The layout is organized in rows and columns, which are represented by


the first and second argument.

The third argument represents the index of the current plot.

plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.

plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.

So, if we want a figure with 2 rows an 1 column (meaning that the two plots will be displayed
on top of each other instead of side-by-side), we can write the syntax like this:

Example

Draw 2 plots on top of each other:

import matplotlib.pyplot as plt


import numpy as np

#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 1, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 1, 2)
plt.plot(x,y)

plt.show()
Result:

Often you may use subplots to display multiple plots alongside each other in Matplotlib.
Unfortunately, these subplots tend to overlap each other by default.

The easiest way to resolve this issue is by using the Matplotlib tight_layout() function. The
easiest way to resolve this overlapping issue is by using the Matplotlib tight_layout() function.
In some cases you may also have titles for each of your subplots. Unfortunately even the
tight_layout() function tends to cause the subplot titles to overlap. The way to resolve this issue
is by increasing the height padding between subplots using the h_pad argument. If you have an
overall title, you can use the subplots_adjust() function to ensure that it doesn’t overlap with
the subplot titles.
demList=glob.glob(r"D:\Anusha\PHD\UPSKILLING\PYTHON\DEM\USGS_13_n[0-
9][0-9]w[0-9][0-9][0-9].tif")
glob is a general term used to define techniques to match specified patterns according to rules
related to Unix shell. Linux and Unix systems and shells also support glob and also provide
function glob() in system libraries. In this tutorial, we will look glob() function usage in Python
programming language. In order to use glob() and related functions we need to import
the glob module. Keep in mind that glob module contains glob() and other related functions.

In some cases, we may want to match the number range. We can use - dash to specify start
and end numbers. In this example, we will match 0 to 9 with 0-9. In this example, we will
match file and folder names that contain numbers from 0 to 9.
glob.glob("/home/ismail/*[0-9]*")

cmd ="gdal_merge.py -o dem_1_merge.tif"


print(cmd.split()+demList)
subprocess.call(cmd.split()+demList, shell=True)

The Geospatial Data Abstraction Library (GDAL) is a computer software library for reading
and writing raster and vector geospatial data formats, and is released under the permissive
X/MIT style free software license by the Open Source Geospatial Foundation.
This utility will automatically mosaic a set of images. All the images must be in the same
coordinate system and have a matching number of bands, but they may be overlapping, and at
different resolutions. In areas of overlap, the last image will be copied over earlier ones.

-o <out_filename>
The name of the output file, which will be created if it does not already exist (defaults
to “out.tif”).

Subprocess has a method call() which can be used to start a program. The parameter is a list
of which the first argument must be the program name. The full definition is:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

Call() function in Subprocess Python


This function can be used to run an external command without disturbing it, wait till the
execution is completed, and then return the output. Its syntax is

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)


In this function, the argument

1. arg is the command that needs to be executed. We can pass multiple commands separated
by a semicolon (;)

2. stdin refers to the value of the standard input stream passed as (os.pipe())

3. stdout is the value of the standard output stream

4. stderr is used to handle errors, if any, that occurred from the standard error stream

5. shell is the boolean value. If it is true then the program executes in a new shell.

This function returns the output of the execution. If there is no output, it returns the code that
is executed successfully. It might also give a CalledProcessError exception.

vrt=gdal.BuildVRT(fr'{folder_working}\merged.vrt",demList)

This program builds a VRT (Virtual Dataset) that is a mosaic of the list of input GDAL
datasets. The list of input GDAL datasets can be specified at the end of the command line, or
put in a text file (one filename per line) for very long lists, or it can be a MapServer tileindex
(see ref gdaltindex utility). In the later case, all entries in the tile index will be added to the
VRT.

With -separate, each files goes into a separate band in the VRT dataset. Otherwise, the files
are considered as tiles of a larger mosaic and the VRT file has as many bands as one of the
input files.

If one GDAL dataset is made of several subdatasets and has 0 raster bands, all the subdatasets
will be added to the VRT rather than the dataset itself.

gdalbuildvrt does some amount of checks to assure that all files that will be put in the
resulting VRT have similar characteristics : number of bands, projection, color
interpretation… If not, files that do not match the common characteristics will be skipped.
(This is only true in the default mode, and not when using the -separate option)

If there is some amount of spatial overlapping between files, the order of files appearing in
the list of source matter: files that are listed at the end are the ones from which the content
will be fetched. Note that nodata will be taken into account to potentially fetch data from less
priority datasets, but currently, alpha channel is not taken into account to do alpha
compositing (so a source with alpha=0 appearing on top of another source will override is
content). This might be changed in later versions.

print(basin.crs)

Coordinate Reference Systems (qgis.org)


map() function returns a map object(which is an iterator) of the results after applying the
given function to each item of a given iterable (list, tuple etc.)

map(fun, iter)
Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.

Python Lambda Functions are anonymous function means that the function is without a
name. As we already know that the def keyword is used to define a normal function in
Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
Python Lambda Function Syntax:

lambda arguments: expression


• This function can have any number of arguments but only one expression, which
is evaluated and returned.
• One is free to use lambda functions wherever function objects are required.
• You need to keep in your knowledge that lambda functions are syntactically
restricted to a single expression.
• It has various uses in particular fields of programming besides other types of
expressions in functions

NAD83 / New York West - EPSG:32117

Convert to and from UTM coordinates with pyproj


pyprojis used under the hood of several python packages like basemap,
cartopy, pyresample. So, if you have any of one those above installed,
you probably already have pyproj as well.

from pyproj import Proj


Convert to and from UTM coordinates with pyproj (ocefpaf.github.io)
Projection — Python GDAL/OGR Cookbook 1.0 documentation (pcjericks.github.io)

# create the CoordinateTransformation


coordTrans = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)

You might also like