# How to calculate difference in altitude along lines using GRASS?

Using SRTM altitude information and OpenStreetmap roads, I want to calculate altitude differences (sum of meters uphill and downhill separated = two values) per road element.

What would be the fastest way to achieve this?

Dylan Beaudette has an article on calculating raster profiles along a line segment that may prove helpful. The basic approach is to convert the lines information into regularly spaced points with `v.to.points` (docs), and then extract the raster values at those locations using `v.drape` (docs). This will get you the first step of the elevations along road segments, next you'd want to categorize the elevation pairs along a particular road. For example, given a raster `srtm_dem` and a road layer `osm_road` the analysis might look like this:

``````# convert line to points; dmax = distance between points

# match resolution and extents of the DEM
g.region rast=srtm_dem

# extract raster values at our points
# use cubic convolution for interpolation between DEM locations
rast=srtm_dem method=cubic

v.out.ascii osm_pts_srtm_elevs > osm_pts_srtm_elevs.txt
``````

From there, you could use a shell script, R, or Python to calculate the distance differences. In Python, that might look something like:

``````last = None
increase = 0
decrease = 0
with open('osm_pts_srtm_elevs.txt') as f:
for line in f:
elev = float(line)
if last:
change = elev - last
if change > 0:
increase += change
else:
decrease += change
last = elev

print "total increase: %.2f" % increase
print "total decrease: %.2f" % decrease
``````

This is just an example for a single road, but could be scripted to run repeatedly across many roads.

If QGIS is an option for you, the Climb Processing Plugin (plugins.qgis.org/plugins/Climb) will do exactly what you want. It can use a DEM to calculate the total climb (and total descent) for each line in an input dataset.

The documentation:

The total climb and descent along the line geometries of the input line layer are calculated using the Z values for the points making up the lines. Z values can be provided by the line geometries or a DEM (by using the Drape (set z-value from raster) algorithm to assign Z values to the points that make up the lines). If a DEM is specified, Z values will be taken from the DEM and not the line layer. The output layer (OUTPUT) has two extra fields (climb and descent) that shall contain the total climb and the total descent for each line geometry. If these fields exist in the input layer the original fields will be removed. The layer totals are returned in the TOTALCLIMB and TOTALDESCENT output parameters.