# Difference between revisions of "Cost surfaces"

Q: I have a friction map, a start polygon and an end polygon and would like to find the least cost path, meaning not a corridor but a thin line. The r.drain manual says: "If the input surface (a raster map layer) is a cumulative cost map generated by the r.walk or r.cost modules, the -d flag and a movement direction surface "indir" must be specified." I assume it's a kind of flow direction or aspect, but what is the physical meaning, and how can I calculate it?

A: The physical meaning is movement direction in degrees CCW from East, similar to e.g. flow direction output of r.watershed. The direction map is an optional output of r.cost and r.walk, and should be used with the indir option for r.drain.

The workflow would thus be:

1. convert the first polygon to a raster map
2. use all cells of the first polygon as start points for r.walk, include the friction map
3. convert the second polygon to a raster map
4. use the second polygon as a MASK and get the coordinates of the cell with the lowest cost
5. use these coordinates as start coordinates for r.drain, together with the movement direction map and the cumulative cost map produced by r.drain

A little example in the NC dataset:

```# walking from Macon county to Dare county
```
```g.region -p rast=elev_state_500m@PERMANENT
```
```v.to.rast in=boundary_county@PERMANENT use=val val=1 where="NAME = 'DARE'" out=dare
```
```v.to.rast in=boundary_county@PERMANENT use=val val=1 where="NAME = 'MACON'" out=macon
```
```r.mapcalc "friction = 0.0001"
```
```# use Knight's move
r.walk elevation=elev_state_500m@PERMANENT friction=friction output=dare_cost outdir=dare_dir start_rast=dare -k
```
```r.mask raster=macon
```
```r.out.xyz in=dare_cost out=- | sort -t "|" -k 3 | head -n3
```
```# gives
# 234250|147750|490937.498669579
# 234250|147250|491132.5043559544
# 234250|146750|491258.3433474401
```
```# Coordinates with lowest cost in Macon county are 234250,147750, and the lowest cost is > zero.
```
```r.mask -r
```
```# use directions input because the input is a cost surface
# and vector output because of Knight's move in r.walk
```
```r.drain -d input=dare_cost indir=dare_dir output=macon2dare vector_output=macon2dare start_coordinates=234250,147750
```