Least cost path (LCP) analysis is the raster equivalent of network analysis, which is used to find the optimal path between two points in a raster. In this recipe, we'll perform LCP analysis on a digital elevation model (DEM).
You need to download the following DEM and extract the ZIP file to your qgis_data/rasters
directory: https://geospatialpython.googlecode.com/svn/lcp.zip
We will load our DEM and two shapefiles consisting of start and end points. Then, we'll use GRASS through the Processing Toolbox to create a cumulative cost layer that assigns a cost to each cell in a raster based on its elevation, the value of the other cells around it, and its distance to and from the end points.
Then, we'll use a SAGA processing algorithm to find the least cost path between two points. Finally, we'll load the output onto the map. To do this, we need to perform the following steps:
import processing
path = "/Users/joellawhead/qgis_data/rasters"/" dem = path + "dem.asc" start = path + "start-point.shp" finish = path + "end-point.shp"
demLyr = QgsRasterLayer(dem, "DEM") ext = demLyr.extent() xmin = ext.xMinimum() ymin = ext.yMinimum() xmax = ext.xMaximum() ymax = ext.xMaximum() box = "%s,%s,%s,%s" % (xmin,xmax,ymin,ymax)
a = QgsVectorLayer(start, "Start", "ogr") b = QgsVectorLayer(finish, "End", "ogr")
tmpCost = processing.runalg("grass:r.cost",dem,a,b, False,False,box,0,-1,0.0001,None) cost = tmpCost["output"]
tmpMerge = processing.runalg("saga:mergeshapeslayers",start,finish,None) merge = tmpMerge["OUT"]
vLyr = QgsVectorLayer(merge, "Destination Points", "ogr") rLyr = QgsRasterLayer(cost, "Accumulated Cost") line = path + "path.shp"
results = processing.runalg("saga:leastcostpaths",lyr,rLyr,demLyr,None,line)
path = QgsVectorLayer(line, "Least Cost Path", "ogr") QgsMapLayerRegistry.instance().addMapLayers([demLyr, vLyr, path])
GRASS has an LCP algorithm too, but the SAGA algorithm is easier to use. GRASS does a great job of creating the cost grid. Processing Toolbox algorithms allow you to create temporary files that are deleted when QGIS closes. So, we use temporary files for the intermediate products, including the cost grid and the merged shapefile.