Random Walk

Setup

# Import modules
import io
import sys
import subprocess
from pathlib import Path
import numpy as np

# Find GRASS Python packages
sys.path.append(
  subprocess.check_output(
    ["grass", "--config", "python_path"],
    text=True
    ).strip()
  )

# Import GRASS packages
import grass.script as gs
import grass.jupyter as gj
from grass.tools import Tools

# Create GRASS project
gs.create_project("cartesian", overwrite=True)
gj.init("cartesian")
tools = Tools(overwrite=True)
tools.g_proj(format="plain", flags="p").text
'XY location (unprojected)'

Set region

# Set region
tools.g_region(n=200, s=0, e=800, w=0, res=1)

Random steps

# Set variables
start = [400, 100]
i = 25000 # Iterations
mu = 0.0 # Mean
sigma = 1 # Standard deviation

# Instantiate random number generator
rng = np.random.default_rng()

# Generate random steps
u = rng.normal(mu, sigma, i)
v = rng.normal(mu, sigma, i)

# Solve position
x = start[0] + np.cumsum(u)
y = start[1] + np.cumsum(v)
# Filter values
x = np.where(x < 800, x, 800)
x = np.where(x > 0, x, 0)
y = np.where(y < 200, y, 200)
y = np.where(y > 0, y, 0)
# Stream array
buffer = io.StringIO()
np.savetxt(buffer, np.column_stack((x, y)), delimiter=",")
buffer.seek(0)

# Import array as points
tools.v_in_ascii(input=buffer, output="walk", separator="comma")

# Visualize
m = gj.Map(width=800, use_region=True)
m.d_vect(map="walk", icon="basic/point", size=5, color="black", fill_color="black")
m.show()

# Set start and stop
start = f"{x[0]}, {y[0]}"
stop = f"{x[-1]}, {y[-1]}"

# Convert to raster
tools.v_to_rast(input="walk", output="walk", use="val", value=1)

# Convert to cost surface
tools.r_mapcalc(expression="cost = if(isnull(walk), 10, 0)")

# Calculate cumulative cost
tools.r_cost(input="cost", output="cost", outdir="direction", start_coordinates=start, stop_coordinates=stop) # start_points=None, stop_points=None, start_raster=None, start_coordinates=None, stop_coordinates=None

# Visualize
m = gj.Map(width=800, use_region=True)
m.d_rast(map="cost")
m.show()

# Calculate least cost path
tools.r_path(
    input="direction",
    start_coordinates=[start, stop],
    raster_path="path",
    vector_path="path")

# Visualize
m = gj.Map(width=800, use_region=True)
m.d_rast(map="cost")
m.d_vect(map="path", color="white", width=3)
m.show()