Examples¶
Four self-contained scripts of increasing complexity, meant as a starting
point for pyrockfall. They live in the examples/ directory of the
repository. Examples 1-3 share the same synthetic slope (45 m high, 75 deg
face) and the same 1000 kg / 2700 kg/m3 rock. Example 4 switches to
a slope with realistic roughness loaded from data files.
Each script is runnable directly, e.g.:
python 01_deterministic_no_roughness.py
Requires pyrockfall, numpy and matplotlib.
1. Deterministic rockfall, no roughness¶
One rock, one run. Fixed rn=0.5, rt=0.9, phi=30 deg, no
roughness. Plots the trajectory and the kinetic energy along it.
"""
Example 1 - Deterministic rockfall, smooth slope (no roughness)
=================================================================
The simplest possible PyRockfall simulation:
- a single straight rock face followed by a flat run-out,
- a single material with fixed (deterministic) rn, rt, phi,
- a single rock, thrown once.
The block is seeded 0.5 m above and 0.1 m to the right of the crest, so it
free-falls that 0.5 m before its first impact - this is what gives it its
initial kinetic energy, instead of setting an initial velocity by hand.
Run with:
python 01_deterministic_no_roughness.py
"""
import numpy as np
import matplotlib.pyplot as plt
import pyrockfall as pr
# ---------------------------------------------------------------------
# 1. Slope geometry
# ---------------------------------------------------------------------
# A rock face of a given height and angle, followed by a flat run-out
# where the block can roll/slide to a stop.
height = 45.0 # [m] height of the rock face
slope_angle = 75.0 # [deg] angle of the face from horizontal
runout_length = 40.0 # [m] flat ground at the toe of the slope
run = height / np.tan(np.radians(slope_angle))
nodes = np.array([
[0.0, height], # crest
[run, 0.0], # toe of the face
[run + runout_length, 0.0], # end of the flat run-out
])
geometry = pr.Geometry(nodes)
# ---------------------------------------------------------------------
# 2. Material: deterministic rn, rt, phi, no roughness
# ---------------------------------------------------------------------
material = pr.Material(
name="Rock face",
normalRestitution=0.5, # rn
tangentialRestitution=0.9, # rt
frictionAngle=30.0, # phi [deg]
roughness=0.0, # perfectly smooth surface
)
# A single material applies to the whole slope (every segment).
slope = pr.Slope(geometry, materials=material)
# ---------------------------------------------------------------------
# 3. Rock and seeder
# ---------------------------------------------------------------------
rock = pr.Rock(name="Boulder", mass=1000.0, density=2700.0)
seed_point = np.array([0.1, height + 0.5])
seeder = pr.Seeder(seed_point, rocks=[rock])
seeder.numberOfRocks = 1
seeder.translationalVelocity = [0.0, 0.0] # released from rest
seeder.angularVelocity = [0.0]
# ---------------------------------------------------------------------
# 4. Run the analysis
# ---------------------------------------------------------------------
analysis = pr.Analysis()
analysis.slope = slope
analysis.seeders = [seeder]
analysis.scaleByVelocity = True # restitution scales with impact speed
analysis.considerRotationalVelocity = True # rocks can roll/spin
analysis.run()
traj = analysis.trajectories
# ---------------------------------------------------------------------
# 5. Kinetic energy along the trajectory
# ---------------------------------------------------------------------
numPoints = 300
time = np.linspace(traj.startTime, traj.stopTime, numPoints) # (numPoints, 1)
pos = traj.position(time) # (2, numPoints, 1)
vel, w = traj.velocity(time, angVel=True) # (2, numPoints, 1), (1, numPoints, 1)
x, y = pos[0, :, 0], pos[1, :, 0]
translational_KE = 0.5 * traj.mass * np.sum(vel[:, :, 0] ** 2, axis=0)
rotational_KE = 0.5 * traj.inertia * w[0, :, 0] ** 2
kinetic_energy = (translational_KE + rotational_KE) / 1000.0 # [kJ]
# ---------------------------------------------------------------------
# 6. Plots
# ---------------------------------------------------------------------
fig, (ax_traj, ax_ke) = plt.subplots(1, 2, figsize=(11, 4.5))
ax_traj.plot(slope.nodes[:, 0], slope.nodes[:, 1], "k-", linewidth=1.5, label="Slope")
ax_traj.plot(x, y, "r-", linewidth=1.0, label="Trajectory")
ax_traj.scatter(*seed_point, color="b", marker="x", label="Seeder")
ax_traj.set_xlabel("x [m]")
ax_traj.set_ylabel("y [m]")
ax_traj.set_aspect("equal", adjustable="box")
ax_traj.legend()
ax_traj.grid(True)
ax_ke.plot(x, kinetic_energy, "r-")
ax_ke.set_xlabel("x [m]")
ax_ke.set_ylabel("Kinetic energy [kJ]")
ax_ke.grid(True)
fig.tight_layout()
plt.show()
2. Stochastic material properties¶
rn, rt and phi become truncated normal distributions. 1000
rocks are thrown; all trajectories are plotted, and the mean/90th-percentile
kinetic energy vs. x is computed.
"""
Example 2 - Stochastic rockfall, smooth slope (no roughness)
==============================================================
Same slope, rock and seeder as example 1, but now rn, rt and phi are
random variables instead of fixed numbers:
rn ~ TruncatedNormal(mean=0.5, std=0.1) in [0, 1]
rt ~ TruncatedNormal(mean=0.9, std=0.1) in [0, 1]
phi ~ TruncatedNormal(mean=30, std=2) in [24, 36]
1000 independent rocks are thrown from the same seed point. Because each
one samples its own rn/rt/phi, every trajectory is a bit different. We
plot all of them, then summarise the kinetic energy with its mean and
90th percentile as a function of x.
Run with:
python 02_stochastic_material.py
"""
import numpy as np
import matplotlib.pyplot as plt
import pyrockfall as pr
from pyrockfall import stats
# ---------------------------------------------------------------------
# 1. Slope geometry (identical to example 1)
# ---------------------------------------------------------------------
height = 45.0
slope_angle = 75.0
runout_length = 40.0
run = height / np.tan(np.radians(slope_angle))
nodes = np.array([
[0.0, height],
[run, 0.0],
[run + runout_length, 0.0],
])
geometry = pr.Geometry(nodes)
# ---------------------------------------------------------------------
# 2. Material: every parameter is now a truncated normal distribution
# ---------------------------------------------------------------------
normal_restitution = stats.Truncate(stats.Normal(0.5, 0.1), lower=0.0, upper=1.0)
tangential_restitution = stats.Truncate(stats.Normal(0.9, 0.1), lower=0.0, upper=1.0)
friction_angle = stats.Truncate(stats.Normal(30.0, 2.0), lower=24.0, upper=36.0)
material = pr.Material(
name="Rock face",
normalRestitution=normal_restitution,
tangentialRestitution=tangential_restitution,
frictionAngle=friction_angle,
roughness=0.0, # still perfectly smooth - see example 3
)
slope = pr.Slope(geometry, materials=material)
# ---------------------------------------------------------------------
# 3. Rock and seeder: same as example 1, thrown 1000 times
# ---------------------------------------------------------------------
rock = pr.Rock(name="Boulder", mass=1000.0, density=2700.0)
seed_point = np.array([0.1, height + 0.5])
seeder = pr.Seeder(seed_point, rocks=[rock])
seeder.numberOfRocks = 1000
# ---------------------------------------------------------------------
# 4. Run the analysis
# ---------------------------------------------------------------------
analysis = pr.Analysis()
analysis.slope = slope
analysis.seeders = [seeder]
analysis.scaleByVelocity = True
analysis.considerRotationalVelocity = True
analysis.useSpecificSeed = True # reproducible sampling
analysis.specificSeed = 42
analysis.run()
traj = analysis.trajectories
# ---------------------------------------------------------------------
# 5. Kinetic energy along every trajectory
# ---------------------------------------------------------------------
# Each of the 1000 blocks stops at its own time, so `traj.startTime`/
# `traj.stopTime` are arrays (one value per block) and `time` below is a
# (numPoints, numSamples) grid: one normalised time axis per block.
numPoints = 300
time = np.linspace(traj.startTime, traj.stopTime, numPoints) # (numPoints, 1000)
pos = traj.position(time) # (2, numPoints, 1000)
vel, w = traj.velocity(time, angVel=True) # (2, ...), (1, ...)
x = pos[0] # (numPoints, 1000)
translational_KE = 0.5 * traj.mass * np.sum(vel ** 2, axis=0) # (numPoints, 1000)
rotational_KE = 0.5 * traj.inertia * w[0] ** 2
kinetic_energy = (translational_KE + rotational_KE) / 1000.0 # [kJ]
# ---------------------------------------------------------------------
# 6. Resample every trajectory onto a common x-grid, then summarise
# ---------------------------------------------------------------------
x_grid = np.linspace(seed_point[0], np.nanmax(x), 200)
energy_on_grid = np.full((x_grid.size, x.shape[1]), np.nan)
for s in range(x.shape[1]):
energy_on_grid[:, s] = np.interp(x_grid, x[:, s], kinetic_energy[:, s], left=np.nan, right=np.nan)
mean_energy = np.nanmean(energy_on_grid, axis=1)
p90_energy = np.nanpercentile(energy_on_grid, 90, axis=1)
# ---------------------------------------------------------------------
# 7. Plots
# ---------------------------------------------------------------------
fig, (ax_traj, ax_ke) = plt.subplots(1, 2, figsize=(11, 4.5))
ax_traj.plot(slope.nodes[:, 0], slope.nodes[:, 1], "k-", linewidth=1.5, zorder=3, label="Slope")
ax_traj.plot(x, pos[1], "r-", linewidth=0.3, alpha=0.1)
ax_traj.set_xlabel("x [m]")
ax_traj.set_ylabel("y [m]")
ax_traj.set_aspect("equal", adjustable="box")
ax_traj.legend()
ax_traj.grid(True)
ax_ke.plot(x_grid, mean_energy, "b-", label="Mean")
ax_ke.plot(x_grid, p90_energy, "r--", label="90th percentile")
ax_ke.set_xlabel("x [m]")
ax_ke.set_ylabel("Kinetic energy [kJ]")
ax_ke.legend()
ax_ke.grid(True)
fig.tight_layout()
plt.show()
3. Stochastic material with surface roughness¶
Same as example 2, with a random roughness added to the material to
represent small-scale surface irregularities.
"""
Example 3 - Stochastic rockfall with surface roughness
=========================================================
Identical to example 2, except the material now also has a `roughness`:
a small random perturbation (in degrees) applied to the slope's surface
normal at each impact, used to emulate small-scale irregularities of the
real rock face that are not captured by the coarse slope geometry.
roughness ~ TruncatedNormal(mean=3, std=1.5) in [0, 10] degrees
Everything else - slope, rock, seeder, number of samples, plots - is the
same as example 2, so you can directly compare the two figures to see
the effect roughness has on the spread of trajectories and impact energies.
Run with:
python 03_stochastic_with_roughness.py
"""
import numpy as np
import matplotlib.pyplot as plt
import pyrockfall as pr
from pyrockfall import stats
# ---------------------------------------------------------------------
# 1. Slope geometry (identical to examples 1 and 2)
# ---------------------------------------------------------------------
height = 45.0
slope_angle = 75.0
runout_length = 40.0
run = height / np.tan(np.radians(slope_angle))
nodes = np.array([
[0.0, height],
[run, 0.0],
[run + runout_length, 0.0],
])
geometry = pr.Geometry(nodes)
# ---------------------------------------------------------------------
# 2. Material: same distributions as example 2, plus roughness
# ---------------------------------------------------------------------
normal_restitution = stats.Truncate(stats.Normal(0.5, 0.1), lower=0.0, upper=1.0)
tangential_restitution = stats.Truncate(stats.Normal(0.9, 0.1), lower=0.0, upper=1.0)
friction_angle = stats.Truncate(stats.Normal(30.0, 2.0), lower=24.0, upper=36.0)
roughness = stats.Truncate(stats.Normal(3.0, 1.5), lower=0.0, upper=10.0) # [deg]
material = pr.Material(
name="Rock face",
normalRestitution=normal_restitution,
tangentialRestitution=tangential_restitution,
frictionAngle=friction_angle,
roughness=roughness,
)
slope = pr.Slope(geometry, materials=material)
# ---------------------------------------------------------------------
# 3. Rock and seeder: same as example 2
# ---------------------------------------------------------------------
rock = pr.Rock(name="Boulder", mass=1000.0, density=2700.0)
seed_point = np.array([0.1, height + 0.5])
seeder = pr.Seeder(seed_point, rocks=[rock])
seeder.numberOfRocks = 1000
# ---------------------------------------------------------------------
# 4. Run the analysis
# ---------------------------------------------------------------------
analysis = pr.Analysis()
analysis.slope = slope
analysis.seeders = [seeder]
analysis.scaleByVelocity = True
analysis.considerRotationalVelocity = True
analysis.useSpecificSeed = True
analysis.specificSeed = 42
analysis.run()
traj = analysis.trajectories
# ---------------------------------------------------------------------
# 5. Kinetic energy along every trajectory
# ---------------------------------------------------------------------
numPoints = 300
time = np.linspace(traj.startTime, traj.stopTime, numPoints) # (numPoints, 1000)
pos = traj.position(time) # (2, numPoints, 1000)
vel, w = traj.velocity(time, angVel=True) # (2, ...), (1, ...)
x = pos[0] # (numPoints, 1000)
translational_KE = 0.5 * traj.mass * np.sum(vel ** 2, axis=0) # (numPoints, 1000)
rotational_KE = 0.5 * traj.inertia * w[0] ** 2
kinetic_energy = (translational_KE + rotational_KE) / 1000.0 # [kJ]
# ---------------------------------------------------------------------
# 6. Resample every trajectory onto a common x-grid, then summarise
# ---------------------------------------------------------------------
x_grid = np.linspace(seed_point[0], np.nanmax(x), 200)
energy_on_grid = np.full((x_grid.size, x.shape[1]), np.nan)
for s in range(x.shape[1]):
energy_on_grid[:, s] = np.interp(x_grid, x[:, s], kinetic_energy[:, s], left=np.nan, right=np.nan)
mean_energy = np.nanmean(energy_on_grid, axis=1)
p90_energy = np.nanpercentile(energy_on_grid, 90, axis=1)
# ---------------------------------------------------------------------
# 7. Plots
# ---------------------------------------------------------------------
fig, (ax_traj, ax_ke) = plt.subplots(1, 2, figsize=(11, 4.5))
ax_traj.plot(slope.nodes[:, 0], slope.nodes[:, 1], "k-", linewidth=1.5, zorder=3, label="Slope")
ax_traj.plot(x, pos[1], "r-", linewidth=0.3, alpha=0.1)
ax_traj.set_xlabel("x [m]")
ax_traj.set_ylabel("y [m]")
ax_traj.set_aspect("equal", adjustable="box")
ax_traj.legend()
ax_traj.grid(True)
ax_ke.plot(x_grid, mean_energy, "b-", label="Mean")
ax_ke.plot(x_grid, p90_energy, "r--", label="90th percentile")
ax_ke.set_xlabel("x [m]")
ax_ke.set_ylabel("Kinetic energy [kJ]")
ax_ke.legend()
ax_ke.grid(True)
fig.tight_layout()
plt.show()
4. Stochastic simulation from input files¶
Instead of building the slope and materials in the script, everything
(materials.ini, rocks.ini, profile.txt, seeders.txt,
settings.ini) is loaded from files. Same trajectory and kinetic energy
plots as examples 2 and 3, now on a multi-material slope.
"""
Example 4 - Stochastic rockfall from real project files
==========================================================
Unlike examples 1-3, which build the slope/material/rock/seeder in the
script itself, this example loads everything from files exported by a
real rockfall analysis project (RocFall-style .ini/.txt files):
materials.ini - material library (rn, rt, phi, roughness, ... per material)
rocks.ini - rock groups (mass, density)
profile.txt - slope geometry with a material ID per segment
seeders.txt - seeder location(s), velocities and number of rocks
settings.ini - analysis settings (sampling method, physics options, ...)
The slope here has several different materials along its length (each
with its own, possibly random, roughness), so this is the closest of the
four examples to a real FYP rockfall study. The plots are the same as in
examples 1-3: all trajectories, and the mean/90th-percentile kinetic
energy vs x.
Run with:
python 04_stochastic_real_roughness.py
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.patches import Patch
import pyrockfall as pr
from pyrockfall import stats
# ---------------------------------------------------------------------
# 1. Load materials, rocks, slope, seeders and settings from file
# ---------------------------------------------------------------------
folder = os.path.dirname(os.path.abspath(__file__))
rocks = pr.importRocks(os.path.join(folder, "rocks.ini"))
materials = pr.importMaterials(os.path.join(folder, "materials.ini"))
mColors = np.array([m.color for m in materials], dtype=float) / 255.0
analysis = pr.importSettings(os.path.join(folder, "settings.ini"))
slope = pr.importSlope(os.path.join(folder, "profile.txt"), materials=materials)
seeders = pr.importSeeders(os.path.join(folder, "seeders.txt"), rockTypes=rocks)
analysis.slope = slope
analysis.seeders = seeders
# ---------------------------------------------------------------------
# 2. Run the analysis
# ---------------------------------------------------------------------
analysis.run()
traj = analysis.trajectories
# ---------------------------------------------------------------------
# 3. Kinetic energy along every trajectory (see example 2 for details)
# ---------------------------------------------------------------------
numPoints = 300
time = np.linspace(traj.startTime, traj.stopTime, numPoints)
pos = traj.position(time)
vel, w = traj.velocity(time, angVel=True)
x = pos[0]
translational_KE = 0.5 * traj.mass * np.sum(vel ** 2, axis=0)
rotational_KE = 0.5 * traj.inertia * w[0] ** 2
kinetic_energy = (translational_KE + rotational_KE) / 1000.0 # [kJ]
# Resample every trajectory onto a common x-grid so the samples can be
# averaged even though each block stops at a different x.
x0 = np.nanmin(x[0, :])
x_grid = np.linspace(x0, np.nanmax(x), 200)
energy_on_grid = np.full((x_grid.size, x.shape[1]), np.nan)
for s in range(x.shape[1]):
energy_on_grid[:, s] = np.interp(x_grid, x[:, s], kinetic_energy[:, s], left=np.nan, right=np.nan)
mean_energy = np.nanmean(energy_on_grid, axis=1)
p90_energy = np.nanpercentile(energy_on_grid, 90, axis=1)
# ---------------------------------------------------------------------
# 4. Plots
# ---------------------------------------------------------------------
fig, (ax_traj, ax_ke) = plt.subplots(1, 2, figsize=(11, 4.5))
# Slope, coloured by material
nodes = slope.nodes
segments = np.stack([nodes[:-1], nodes[1:]], axis=1)
colors = [mColors[m] for m in slope.materialIDs]
ax_traj.add_collection(LineCollection(segments, colors=colors, linewidths=1.5, zorder=3))
for seeder in seeders:
ax_traj.scatter(seeder.points[0], seeder.points[1], color="k", marker="x", zorder=4)
ax_traj.plot(x, pos[1], "r-", linewidth=0.3, alpha=0.1)
handles = [
Patch(facecolor=mColors[i], edgecolor="k", label=materials[i].name)
for i in np.unique(slope.materialIDs).astype(int)
]
ax_traj.legend(handles=handles, fontsize=7, loc="upper right")
ax_traj.set_xlabel("x [m]")
ax_traj.set_ylabel("y [m]")
ax_traj.set_xlim(nodes[:, 0].min(), nodes[:, 0].max())
ax_traj.set_aspect("equal", adjustable="box")
ax_traj.grid(True)
ax_ke.plot(x_grid, mean_energy, "b-", label="Mean")
ax_ke.plot(x_grid, p90_energy, "r--", label="90th percentile")
ax_ke.set_xlabel("x [m]")
ax_ke.set_ylabel("Kinetic energy [kJ]")
ax_ke.legend()
ax_ke.grid(True)
fig.tight_layout()
plt.show()