SEM in 3-D · acoustic, elastic, topography and Biot¶
In 3-D PropSEM takes the same constructor and call with one more axis:
shape=(nz, ny, nx), positions [ix, iy, iz], and a topography of shape (ny, nx).
This notebook runs:
- Acoustic —
AcousticSEM3Don a two-layer model, a 2-D receiver grid on the surface - Elastic —
ElasticVSSEM3D, three-component records - Moment-tensor sources — the explosion and the three shear moments
- Topography —
AcousticSEM3DDeformedunder a 3-D hill - A gradient — one
.backward()in 3-D - A poroelastic rock —
BiotVSSEM3DDeformed, the fast and the slow P wave
The first five run on the CUDA kernels (impl='c'; on the CPU they run eager,
much more slowly), the poroelastic one on eager, for its snapshots. About two minutes on a GPU,
most of it the poroelastic run, which needs 13 GB of GPU memory.
import time
import numpy as np
import torch
import matplotlib.pyplot as plt
from sweep.sem import PropSEM
from matplotlib.patches import Circle
from sweep.sem.equations import (AcousticSEM3D, AcousticSEM3DDeformed, ElasticVSSEM3D,
BiotVSSEM3DDeformed)
from sweep.equations.biot import biot_from_rock, biot_wave_velocities
from sweep.signal import ricker
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('device:', device)
dh, n_order = 10.0, 4
shape = (41, 61, 61) # (nz, ny, nx): 400 m deep, 600 m x 600 m
nz, ny, nx = shape
dt, nt = 0.6e-3, 1000
device: cuda
1. Acoustic¶
A free surface on top and the C-PML on the five other sides (abcn cells, as in
2-D). The source is in the middle, 20 m deep; the receivers fill the surface every
20 m, so receivers has shape (1, nrec, 3) with columns [ix, iy, iz].
f0 = 10.0
wavelet = ricker(np.arange(nt) * dt - 1.2 / f0, f=f0).astype(np.float32)
vp = torch.full(shape, 1500.0, device=device)
vp[20:] = 2500.0 # interface at 200 m
src = np.array([[nx // 2, ny // 2, 2]]) # [ix, iy, iz]
iy, ix = np.meshgrid(np.arange(0, ny, 2), np.arange(0, nx, 2), indexing='ij')
receivers = np.stack([ix.ravel(), iy.ravel(), np.full(ix.size, 2)], axis=1)[None]
print('sources', src.shape, ' receivers', receivers.shape)
solver = PropSEM(AcousticSEM3D, shape=shape, dh=dh, dt=dt, n_order=n_order,
abcn=20, free_surface=True, f_dominant=f0, device=device)
m = solver.mesh
print('impl', solver.impl, '| mesh', type(m).__name__, m.n_elements, 'elements,',
m.n_global, 'GLL nodes')
t0 = time.perf_counter()
with torch.no_grad():
seis = solver(wavelet, src, receivers, models=[vp])
if device == 'cuda':
torch.cuda.synchronize()
print('record', tuple(seis.shape), f' {time.perf_counter() - t0:.2f} s')
sources (1, 3) receivers (1, 961, 3)
impl c | mesh Hex8Mesh 9375 elements, 622261 GLL nodes
record (1, 1000, 961, 1) 0.63 s
The record is (nshots, nt, nrec, 1) as in 2-D. Reshaped to the receiver grid it
gives the surface wavefield at any time (a time slice), and one row of it a
2-D gather:
rec = seis[0, :, :, 0].cpu().numpy().reshape(nt, *ix.shape) # (nt, ny', nx')
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2), constrained_layout=True)
for ax, ts in zip(axes[:2], (0.25, 0.45)):
sl = rec[int(round(ts / dt))]
lim = np.percentile(np.abs(sl[sl != 0]), 99)
ax.imshow(sl, cmap='seismic', vmin=-lim, vmax=lim, origin='lower',
extent=[0, (nx - 1) * dh, 0, (ny - 1) * dh])
ax.set_title(f'surface, t = {ts:.2f} s'); ax.set_xlabel('x (m)'); ax.set_ylabel('y (m)')
g = rec[:, ix.shape[0] // 2, :]
lim = np.percentile(np.abs(g[g != 0]), 98)
axes[2].imshow(g, cmap='seismic', vmin=-lim, vmax=lim, aspect='auto',
extent=[0, (nx - 1) * dh, nt * dt, 0])
axes[2].set_title('gather along y = 300 m'); axes[2].set_xlabel('x (m)')
axes[2].set_ylabel('time (s)')
plt.show()
The time slices show the direct wave as a ring and, at 0.45 s, the reflection from the interface behind it; the gather shows the same two and their free-surface multiple.
2. Elastic¶
ElasticVSSEM3D takes [vp, vs, rho] and records vx, vy, vz. The default
source is a vertical force (source_type=['vz']; ['vx'] and ['vy'] are the
horizontal forces). One line of receivers along x:
f0 = 8.0
wavelet = ricker(np.arange(nt) * dt - 1.2 / f0, f=f0).astype(np.float32)
vp = torch.full(shape, 2000.0, device=device); vp[20:] = 2800.0
vs = torch.full(shape, 1200.0, device=device); vs[20:] = 1600.0
rho = torch.full(shape, 2000.0, device=device); rho[20:] = 2200.0
rx = np.arange(0, nx)
line = np.stack([rx, np.full_like(rx, ny // 2 + 10), np.full_like(rx, 2)], axis=1)[None]
solver_el = PropSEM(ElasticVSSEM3D, shape=shape, dh=dh, dt=dt, n_order=n_order,
abcn=20, free_surface=True, f_dominant=f0,
receiver_type=['vx', 'vy', 'vz'], device=device)
t0 = time.perf_counter()
with torch.no_grad():
seis_el = solver_el(wavelet, src, line, models=[vp, vs, rho])
if device == 'cuda':
torch.cuda.synchronize()
print('impl', solver_el.impl, ' record', tuple(seis_el.shape),
f' {time.perf_counter() - t0:.2f} s')
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2), sharey=True, constrained_layout=True)
for c, (ax, name) in enumerate(zip(axes, ['vx', 'vy', 'vz'])):
g = seis_el[0, :, :, c].cpu().numpy()
lim = np.percentile(np.abs(g[g != 0]), 98)
ax.imshow(g, cmap='seismic', vmin=-lim, vmax=lim, aspect='auto',
extent=[0, (nx - 1) * dh, nt * dt, 0])
ax.set_title(name); ax.set_xlabel('x (m)')
axes[0].set_ylabel('time (s)')
plt.show()
impl c record (1, 1000, 61, 3) 0.58 s
The line runs 100 m off the source in y, so all three components move: vz is
dominated by the surface wave, vx changes sign where the line passes the
source, and vy is the motion across the line.
3. Moment-tensor sources¶
In 3-D source_type also takes the moment tensor: ['sxx', 'syy', 'szz'] is an
explosion, and ['sxy'], ['sxz'], ['syz'] are the three shear moments, each
a double couple. As in 2-D the wavelet is the moment rate. Each source 200 m deep
in a homogeneous half-space, and vz on the receiver grid of section 1 when the
P wave reaches the surface:
src_deep = np.array([[nx // 2, ny // 2, 20]]) # 200 m deep
homogeneous = [torch.full(shape, v, device=device) for v in (2000.0, 1200.0, 2000.0)]
k = int(round(0.27 / dt))
fig, axes = plt.subplots(1, 4, figsize=(16, 4.4), constrained_layout=True)
for ax, stype in zip(axes, (['sxx', 'syy', 'szz'], ['sxy'], ['sxz'], ['syz'])):
s = PropSEM(ElasticVSSEM3D, shape=shape, dh=dh, dt=dt, n_order=n_order, abcn=20,
free_surface=True, f_dominant=f0, source_type=stype, receiver_type=['vz'],
device=device)
with torch.no_grad():
out = s(wavelet, src_deep, receivers, models=homogeneous)
sl = out[0, k, :, 0].cpu().numpy().reshape(ix.shape) # (ny', nx')
v = np.abs(sl).max()
ax.imshow(sl, cmap='seismic', vmin=-v, vmax=v, origin='lower',
extent=[0, (nx - 1) * dh, 0, (ny - 1) * dh])
ax.set_title(f"{', '.join(stype)}: vz, t = {k * dt:.2f} s"); ax.set_xlabel('x (m)')
axes[0].set_ylabel('y (m)')
print('impl', s.impl)
plt.show()
impl c
The explosion sends the same P wave in every direction: a ring. sxy, a
vertical strike-slip fault along x or y, puts four lobes of alternating sign
around the source, with nodal lines along the two axes. sxz and syz put two
lobes of opposite sign on either side of the source, along x and along y.
4. Topography¶
topography is the surface row at every (iy, ix), shape (ny, nx), fractional
allowed; it needs a deformable (hex27) equation such as AcousticSEM3DDeformed.
A 100 m hill in the middle, the source under its crest:
f0 = 10.0
wavelet = ricker(np.arange(nt) * dt - 1.2 / f0, f=f0).astype(np.float32)
yy, xx = np.meshgrid(np.arange(ny), np.arange(nx), indexing='ij')
topo = 12.0 - 10.0 * np.exp(-((xx - nx // 2) ** 2 + (yy - ny // 2) ** 2) / 15.0 ** 2)
vp = torch.full(shape, 1500.0, device=device); vp[25:] = 2500.0
solver_t = PropSEM(AcousticSEM3DDeformed, shape=shape, dh=dh, dt=dt, n_order=n_order,
abcn=20, topography=topo, f_dominant=f0, device=device)
src_t = np.array([[nx // 2, ny // 2, 6]]) # 40 m below the crest
rx = np.arange(1, nx - 1) # inside the model edges
line_t = np.stack([rx, np.full_like(rx, ny // 2), np.ceil(topo[ny // 2, rx]) + 1],
axis=1)[None] # just below the surface
with torch.no_grad():
seis_t = solver_t(wavelet, src_t, line_t, models=[vp])
print('impl', solver_t.impl, ' mesh', type(solver_t.mesh).__name__, ' record', tuple(seis_t.shape))
fig, axes = plt.subplots(1, 2, figsize=(13, 4.2), constrained_layout=True)
im = axes[0].imshow(topo * dh, cmap='terrain_r', origin='lower',
extent=[0, (nx - 1) * dh, 0, (ny - 1) * dh])
axes[0].plot(rx * dh, np.full_like(rx, ny // 2) * dh, 'k-', lw=1)
axes[0].set_title('surface depth (m)'); axes[0].set_xlabel('x (m)'); axes[0].set_ylabel('y (m)')
fig.colorbar(im, ax=axes[0])
g = seis_t[0, :, :, 0].cpu().numpy()
lim = np.percentile(np.abs(g[g != 0]), 98)
axes[1].imshow(g, cmap='seismic', vmin=-lim, vmax=lim, aspect='auto',
extent=[0, (nx - 1) * dh, nt * dt, 0])
axes[1].set_title('gather along the black line'); axes[1].set_xlabel('x (m)')
axes[1].set_ylabel('time (s)')
plt.show()
impl c mesh Hex27Mesh record (1, 1000, 59, 1)
5. A gradient¶
The 3-D call is differentiable like the 2-D one. One shot, a homogeneous initial
model against the two-layer data of section 1; the gradient comes back on the
(nz, ny, nx) grid. On impl='c' the default memory strategy is boundary
saving (solver.memory_strategy says so), which matters most in 3-D, where a
full forward history grows as nz x ny x nx x nt; see SEM gradients for the
options.
vp_true = torch.full(shape, 1500.0, device=device); vp_true[20:] = 2500.0
with torch.no_grad():
obs = solver(wavelet, src, receivers, models=[vp_true])
scale = 1.0 / float(obs.pow(2).mean().sqrt()) # O(1) data, see notebook 5
vp0 = torch.full(shape, 1500.0, device=device, requires_grad=True)
pred = solver(wavelet * scale, src, receivers, models=[vp0])
loss = 0.5 * (pred - obs * scale).pow(2).sum()
loss.backward()
print('memory strategy', solver.memory_strategy, ' loss %.3e' % loss.item(),
' grad', tuple(vp0.grad.shape))
g = vp0.grad.cpu().numpy()
fig, axes = plt.subplots(1, 2, figsize=(13, 3.8), constrained_layout=True)
for ax, img, title, ext in [
(axes[0], g[:, ny // 2, :], 'x-z slice, y = 300 m', [0, (nx - 1) * dh, (nz - 1) * dh, 0]),
(axes[1], g[:, :, nx // 2], 'y-z slice, x = 300 m', [0, (ny - 1) * dh, (nz - 1) * dh, 0])]:
lim = np.percentile(np.abs(img[6:][img[6:] != 0]), 98)
ax.imshow(img, cmap='seismic', vmin=-lim, vmax=lim, extent=ext)
ax.axhline(200, color='k', lw=0.5, ls='--')
ax.set_title(title); ax.set_ylabel('z (m)')
plt.show()
memory strategy boundary loss 3.066e+04 grad (41, 61, 61)
The gradient is strongest along the interface at 200 m (dashed), where the initial model is missing the velocity increase, and along the wavepaths from the source down to it; the two slices are the same, as the problem is symmetric in x and y around the source.
6. A poroelastic rock¶
BiotVSSEM3DDeformed is the Biot equation of
SEM anisotropic and poroelastic rocks on the Hex27 mesh, with the same
eight coefficients. It runs on the CUDA kernels too; the snapshots here need eager. An explosion
in the middle of a cube of the sandstone of that notebook, with kappa = 1e-8 m^2, where the slow
P wave propagates; the snapshots are x-z slices through the source of the solid's vertical
velocity and of the pore pressure, with circles at the two P speeds. The run needs about 13 GB of
GPU memory.
coef = biot_from_rock(kappa=1e-8, k_s=36e9, rho_s=2650.0, k_f=2.25e9, rho_f=1000.0,
eta=1e-3, k_d=9e9, mu=7e9, phi=0.25, tortuosity=2.0)
v_fast, v_slow, v_s = (float(v) for v in biot_wave_velocities(coef))
shape_b, dh_b, dt_b, f0_b = (169, 169, 169), 2.0, 1e-4, 30.0 # a 336 m cube, 8 m elements
c_b = 86 # the source: the middle of an element
k_snap = 727 # 0.073 s
wavelet_b = ricker(np.arange(k_snap + 1) * dt_b - 1.2 / f0_b, f=f0_b).astype(np.float32)
biot = PropSEM(BiotVSSEM3DDeformed, shape=shape_b, dh=dh_b, dt=dt_b, n_order=n_order,
abcn=16, f_dominant=f0_b, receiver_type=['vz', 'p'], device=device,
impl='eager') # snapshots need eager
print('models:', biot.model_names, ' source:', biot.source_type, ' impl:', biot.impl,
' memory:', biot.memory_strategy)
t0 = time.perf_counter()
with torch.no_grad():
_, snap = biot(wavelet_b, np.array([[c_b, c_b, c_b]]), np.array([[[c_b, c_b, c_b + 20]]]),
models=[torch.full(shape_b, float(c), device=device) for c in coef],
return_wavefield=True, snapshot_times=[k_snap])
print(f'{time.perf_counter() - t0:.0f} s with compiling')
t = k_snap * dt_b - 1.2 / f0_b
lo_m, hi_m = -c_b * dh_b, (shape_b[0] - 1 - c_b) * dh_b # metres from the source
fig, axes = plt.subplots(1, 2, figsize=(12, 5.6), constrained_layout=True)
for ax, name in zip(axes, ['v_z', 'p']):
img = snap[0, biot.snapshot_fields.index(name), 0, 0, 16:-16, c_b + 16, 16:-16].cpu().numpy()
lim = np.percentile(np.abs(img), 99.5)
ax.imshow(img, cmap='seismic', vmin=-lim, vmax=lim, extent=[lo_m, hi_m, hi_m, lo_m],
interpolation='bilinear')
for vel, label in [(v_fast, 'fast P'), (v_slow, 'slow P')]:
ax.add_patch(Circle((0, 0), vel * t, fill=False, ls='--', color='k', lw=0.8))
ax.text(vel * t * 0.71 + 3, -vel * t * 0.71 - 3, label, fontsize=9)
ax.set_title(f'{name}, x-z slice through the source'); ax.set_xlabel('x (m)')
axes[0].set_ylabel('z (m)')
plt.show()
models: ['H', 'mu', 'C', 'M', 'rho', 'rho_f', 'm', 'b'] source: ['sxx', 'syy', 'szz'] impl: eager memory: ckpt
sweep: torch.compile is compiling the BiotVSSEM3DDeformed step for a 169x169x169 grid; the first call on each new grid size takes seconds to a few minutes (cached on disk for later runs). EagerOptions(use_compile=False) runs uncompiled instead.
142 s with compiling
Both P waves sit on their circles, as in 2-D: the fast one dominates the solid's
velocity, the slow one, the fluid moving against the solid, the pore pressure.
In v_z each ring is cut at the horizontal, where the radial motion has no
vertical component, and changes sign across it; the pore pressure has no
direction, and its rings are whole. The 3-D class takes the 2-D sources with y added (the moment
tensor, the forces, the injection p), fluid and dry regions, the open-pore
surface and viscous_q; it has no anisotropic drag and no attenuating frame.
Summary¶
| 2-D | 3-D | |
|---|---|---|
shape |
(nz, nx) |
(nz, ny, nx) |
| positions | [ix, iz] |
[ix, iy, iz] |
topography |
(nx,) |
(ny, nx) |
edges for free_surface |
top, bottom, left, right | adds front, back |
| moment tensor | ['sxx', 'szz'], ['sxz'] |
['sxx', 'syy', 'szz'], ['sxy'], ['sxz'], ['syz'] |
impl='c' equations |
all but AcousticSEM2D(Deformed), ElasticSEM2D, ElasticSHSEM2DDeformed, ViscoAcousticPotentialSEM2D, ViscoElasticSEM2DDeformed |
all |
| Biot | BiotVSSEM2DDeformed and its variants |
BiotVSSEM3DDeformed |
Larger 3-D models run across several GPUs with sweep.sem.dd; see the
SEM user guide.
Next: SEM anisotropic and poroelastic rocks · VTI, TTI and Biot.
Download this notebook — 56_sem_3d.ipynb · or view on GitHub