Skip to content

Laterally Loaded Pile

This example embeds a circular beam-column pile in a graded three-dimensional soil domain and applies a static horizontal load at the pile head.

Application Static pile-soil interaction
Soil 3D elastic brick domain with geometric grading
Pile 20 displacement-based beam-column elements from -10 m to 1 m
Coupling Embedded beam-solid interface
Loading 1 MN horizontal pile-head load
Output Domain displacement and pile section forces

Model

The translucent grid is the complete soil domain. Orange cells are the neighborhood selected by the embedded interface, the dark line is the pile axis, and the blue envelope represents the circular pile radius used during cell discovery. The pile continues above the ground surface so its loaded head is not hidden by the soil mesh.

Why The Domain Is Split Into Four Parts

The soil extends 8 m from the pile in both horizontal directions and 10 m below the surface. Four geometric mesh parts meet at the pile axis. Their element spacing grows toward the exterior boundaries, concentrating resolution where pile-soil interaction is strongest without using the same fine spacing over the full domain.

The four parts are assembled as one soil section with point merging enabled. The pile is placed in a separate section because its nodes have six degrees of freedom while the brick nodes have three. The embedded interface creates the intended coupling; coincident point merging does not.

Worked Workflow

The four blocks use reciprocal grading ratios so cells remain compatible across the central planes and become larger away from the pile.

OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
model = Model(
    model_name="laterally_loaded_pile",
    model_path=str(OUTPUT_DIR.resolve()),
)
model.set_results_folder(RESULTS_DIR.resolve().as_posix())

soil_material = model.material.nd.elastic_isotropic(
    user_name="elastic_soil",
    E=2.0e8,
    nu=0.4,
    rho=2100.0,
)
soil_element = model.element.brick.std(
    ndof=3,
    material=soil_material,
)

x_min, x_max, y_min, y_max, z_min, z_max = SOIL_BOUNDS
nx, ny, nz = SOIL_DIVISIONS
r = SOIL_GRADING_RATIO
soil_blocks = [
    ("soil_sw", x_min, 0.0, y_min, 0.0, r, r),
    ("soil_se", 0.0, x_max, y_min, 0.0, 1.0 / r, r),
    ("soil_nw", x_min, 0.0, 0.0, y_max, r, 1.0 / r),
    ("soil_ne", 0.0, x_max, 0.0, y_max, 1.0 / r, 1.0 / r),
]

soil_part_names = []
for name, block_x_min, block_x_max, block_y_min, block_y_max, x_ratio, y_ratio in soil_blocks:
    model.meshpart.volume.geometric_rectangular_grid(
        user_name=name,
        element=soil_element,
        x_min=block_x_min,
        x_max=block_x_max,
        y_min=block_y_min,
        y_max=block_y_max,
        z_min=z_min,
        z_max=z_max,
        nx=nx,
        ny=ny,
        nz=nz,
        x_ratio=x_ratio,
        y_ratio=y_ratio,
        z_ratio=r,
    )
    soil_part_names.append(name)

Circular section properties are calculated from the one-meter diameter, then passed to a displacement-based beam-column element with a PDelta transformation.

pile_radius = PILE_DIAMETER / 2.0
pile_E = 1.0e10
pile_nu = 0.3
pile_G = pile_E / (2.0 * (1.0 + pile_nu))
pile_area = math.pi * PILE_DIAMETER**2 / 4.0
pile_I = math.pi * PILE_DIAMETER**4 / 64.0
pile_J = math.pi * PILE_DIAMETER**4 / 32.0

pile_section = model.section.beam.elastic(
    user_name="pile_section",
    E=pile_E,
    A=pile_area,
    Iz=pile_I,
    Iy=pile_I,
    G=pile_G,
    J=pile_J,
)
pile_transformation = model.transformation.transformation3d(
    transf_type="PDelta",
    vecxz_x=-1.0,
    vecxz_y=0.0,
    vecxz_z=0.0,
)
pile_element = model.element.beam.disp(
    ndof=6,
    section=pile_section,
    transformation=pile_transformation,
    numIntgrPts=5,
)
model.meshpart.line.single_line(
    user_name="pile",
    element=pile_element,
    x0=PILE_BOTTOM[0],
    y0=PILE_BOTTOM[1],
    z0=PILE_BOTTOM[2],
    x1=PILE_HEAD[0],
    y1=PILE_HEAD[1],
    z1=PILE_HEAD[2],
    number_of_lines=PILE_ELEMENTS,
)

The interface is declared first. During assembly it finds the solid cells crossed by the pile envelope and creates the embedded coupling data.

pile_soil_interface = model.interface.beam_solid_interface(
    name="pile_soil_interface",
    beam_part="pile",
    solid_parts=soil_part_names,
    radius=pile_radius,
    n_peri=8,
    n_long=4,
    penalty_param=1.0e12,
    g_penalty=True,
)

model.assembler.create_section(
    meshparts=soil_part_names,
    num_partitions=0,
    merge_points=True,
    tolerance=5.0e-2,
)
model.assembler.create_section(
    meshparts=["pile"],
    num_partitions=0,
    merge_points=False,
)
model.assembler.assemble(merge_points=True, progress_callback=lambda *_: None)

model.constraint.sp.fix_macro_x_min(dofs=[1, 1, 1], tol=1.0e-6)
model.constraint.sp.fix_macro_x_max(dofs=[1, 1, 1], tol=1.0e-6)
model.constraint.sp.fix_macro_y_min(dofs=[1, 1, 1], tol=1.0e-6)
model.constraint.sp.fix_macro_y_max(dofs=[1, 1, 1], tol=1.0e-6)
model.constraint.sp.fix_macro_z_min(dofs=[1, 1, 1], tol=1.0e-6)

A geometric node mask selects the pile head. The beam-force recorder tracks all pile elements without requiring their solver tags in advance.

pile_head_nodes = model.mask.nodes.near_point(point=PILE_HEAD, radius=1.0e-4)
if len(pile_head_nodes) != 1:
    raise RuntimeError(f"Expected one pile-head node, found {len(pile_head_nodes)}")

load_series = model.time_series.linear(factor=1.0)
lateral_pattern = model.pattern.plain(time_series=load_series)
lateral_pattern.add_load.node(
    node_mask=pile_head_nodes,
    values=[HEAD_LOAD, 0.0, 0.0, 0.0, 0.0, 0.0],
)

domain_recorder = model.recorder.vtkhdf(
    file_base_name="pile_response.vtkhdf",
    resp_types=["disp"],
)
pile_force_recorder = model.recorder.beam_force(
    meshparts=["pile"],
    force_type="globalForce",
    file_prefix="pile_force",
    include_time=True,
    output_format="xml",
)

The static load is applied in 100 increments. A penalty handler enforces the interface constraints while Modified Newton solves each equilibrium step.

static_analysis = model.analysis.static(
    name="lateral_head_load",
    constraint_handler=model.analysis.constraint.penalty(
        alpha_s=1.0e15,
        alpha_m=1.0e15,
    ),
    numberer=model.analysis.numberer.rcm(),
    system=model.analysis.system.bandgeneral(),
    algorithm=model.analysis.algorithm.modifiednewton(factor_once=True),
    test=model.analysis.test.normdispincr(
        tol=1.0e-3,
        max_iter=5,
        print_flag=2,
    ),
    integrator=model.analysis.integrator.loadcontrol(incr=0.01),
    num_steps=100,
)

model.process.add_step(lateral_pattern, "Apply the lateral pile-head load")
model.process.add_step(domain_recorder, "Record the soil and pile displacement")
model.process.add_step(pile_force_recorder, "Record pile forces and moments")
model.process.add_step(static_analysis, "Run the static loading analysis")

Results And Post-Processing

After OpenSees completes, run:

python examples/soil_structure_interaction/laterally_loaded_pile_postprocess.py

The postprocessor reads the XML beam-force recorder and reconstructs the force and moment distributions from the pile toe to its head. It also reads the VTKHDF displacement history and creates a complete-model deformation movie. The movie shows static load progression, so its annotation reports load factor rather than physical time.

def generate_force_plot() -> Path:
    """Plot the final pile force and moment distributions."""
    element_count, history = read_beam_force_xml(FORCE_FILE)
    response = end_distributions(element_count, history[-1])
    depths = np.linspace(LEGACY_PLOT_BOTTOM, LEGACY_PLOT_TOP, element_count + 1)

    # Keep the legacy arrangement and Matplotlib defaults for direct comparison
    # with examples/SoilStructureInteraction/Example0/plot_moment.py.
    figure, axes = plt.subplots(3, 2, figsize=(6, 8), constrained_layout=True)
    components = (
        ("Px", axes[0, 0], "Shear Forces Px"),
        ("Py", axes[0, 1], "Shear Forces Py"),
        ("Pz", axes[1, 0], "Axial Forces Pz"),
        ("Mx", axes[1, 1], "Moments Mx"),
        ("My", axes[2, 0], "Moments My"),
        ("Mz", axes[2, 1], "Torsional Moments Mz"),
    )
    for component, axis, title in components:
        axis.plot(response[component], depths, "-", alpha=1.0)
        axis.set_title(title)
        axis.grid(True, which="both", linestyle="--", alpha=0.5)
        axis.set_xlabel("Force / Moment")
        axis.set_ylabel("Depth")
        axis.axvline(0, color="black", linewidth=0.8, linestyle="-", alpha=0.7)

    OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
    figure.savefig(OUTPUT_FILE, dpi=300, bbox_inches="tight")
    plt.close(figure)
    return OUTPUT_FILE


def generate_deformation_movie() -> Path:
    """Animate the complete model through the static load progression."""
    result_pattern = str(RESULTS_DIR / "pile_response*.vtkhdf")
    with fm.results.open(result_pattern) as results:
        if results.number_of_partitions != 1:
            raise ValueError("This serial example expects one VTKHDF result file")

        reader = results.readers[0]
        mesh = results.mesh(copy=True)
        original_points = mesh.points.copy()
        line_cells = mesh.celltypes == int(pv.CellType.LINE)
        pile_mesh = mesh.extract_cells(line_cells)
        pile_point_ids = np.asarray(
            pile_mesh.point_data["vtkOriginalPointIds"],
            dtype=int,
        )

        undeformed = mesh.copy(deep=True)
        displacement = reader.point_frame("displacement", 0)
        magnitude = np.linalg.norm(displacement[:, :3], axis=1)
        final_displacement = reader.point_frame("displacement", -1)[:, :3]
        maximum_displacement = float(
            max(np.linalg.norm(final_displacement, axis=1).max(), 1.0e-12)
        )
        mesh.point_data["Displacement magnitude"] = magnitude

        plotter = pv.Plotter(off_screen=True, window_size=(1100, 680))
        # plotter.add_mesh(
        #     undeformed,
        #     color="#aeb8b8",
        #     opacity=0.08,
        #     show_edges=True,
        #     edge_color="#718083",
        #     line_width=0.5,
        # )
        plotter.add_mesh(
            mesh,
            scalars="Displacement magnitude",
            cmap="cividis",
            opacity=1.0,
            show_edges=True,
            edge_color="#9b9687",
            line_width=0.6,
            clim=(0.0, maximum_displacement*0.05),
            # scalar_bar_args={"title": "Displacement (m)"},
            show_scalar_bar= False

        )
        plotter.add_mesh(
            pile_mesh,
            color="#17252b",
            line_width=10,
            render_lines_as_tubes=True,
        )
        plotter.add_text(
            f"Load factor: 0.00   Deformation scale: {DEFORMATION_SCALE:g}x",
            name="load-factor",
            font_size=12,
        )

        plotter.view_xz()
        #  goes a liittle up to show the pile head
        plotter.camera.elevation = 30
        # plotter.enable_parallel_projection()


        # plotter.camera_position = [
        #     (0.0, -34.0, -3.5),
        #     (0.0, 0.0, -3.5),
        #     (0.0, 0.0, 1.0),
        # ]
        plotter.set_background("#f6f4ef")

        MOVIE_FILE.parent.mkdir(parents=True, exist_ok=True)
        plotter.open_movie(
            str(MOVIE_FILE),
            framerate=MOVIE_FRAME_RATE,
            quality=7,
        )
        load_factors = results.times
        if load_factors is None:
            load_factors = np.linspace(0.0, 1.0, results.number_of_steps)

        try:
            for step in tqdm(
                range(results.number_of_steps),
                desc="Rendering lateral deformation",
                unit="frame",
            ):
                displacement = reader.point_frame("displacement", step)[:, :3]
                mesh.points = original_points + DEFORMATION_SCALE * displacement
                mesh.point_data["Displacement magnitude"] = np.linalg.norm(
                    displacement,
                    axis=1,
                )
                pile_mesh.points = mesh.points[pile_point_ids]
                plotter.add_text(
                    (
                        f"Load factor: {float(load_factors[step]):.2f}   "
                        f"Deformation scale: {DEFORMATION_SCALE:g}x"
                    ),
                    name="load-factor",
                    font_size=12,
                )
                plotter.write_frame()
        finally:
            plotter.close()
    return MOVIE_FILE


def generate_results() -> tuple[Path, ...]:
    """Generate the standard static result figures."""
    return (generate_force_plot(),)


def generate_animations() -> tuple[Path, ...]:
    """Generate the optional complete-model deformation animation."""
    return (generate_deformation_movie(),)


def main() -> None:
    generated = (*generate_results(), *generate_animations())
    print("Post-processing outputs:")
    for output in generated:
        print(f"  {output.resolve()}")


if __name__ == "__main__":
    main()
Complete post-processing source
# =============================================================================
# Femora: Fast Efficient Meta-modeling for OpenSees-based Resilience Analysis
# Copyright 2026 Amin Pakzad and Pedro Arduino
# Developed at the UW Geotechnical Lab
# SPDX-License-Identifier: Apache-2.0
# =============================================================================

"""Plot and animate the laterally loaded pile response."""

from __future__ import annotations

from pathlib import Path
import re
from xml.etree import ElementTree

import femora as fm
import matplotlib.pyplot as plt
import numpy as np
import pyvista as pv
from tqdm import tqdm


ROOT = Path(__file__).resolve().parents[2]
RESULTS_DIR = ROOT / "example_outputs" / "laterally_loaded_pile" / "results"
FORCE_FILE = RESULTS_DIR / "pile_force_pile_Core0_globalForce.xml"
POSTPROCESS_DIR = RESULTS_DIR.parent / "post_processing"
OUTPUT_FILE = POSTPROCESS_DIR / "pile_forces_moments.png"
MOVIE_FILE = POSTPROCESS_DIR / "lateral-deformation.mp4"
PILE_BOTTOM_Z = -10.0
PILE_HEAD_Z = 1.0
# These are intentionally separate from the physical pile elevations. They
# reproduce the depth range used by the legacy comparison plot.
LEGACY_PLOT_BOTTOM = -5.0
LEGACY_PLOT_TOP = 2.0
DEFORMATION_SCALE = 100.0
MOVIE_FRAME_RATE = 24


def read_beam_force_xml(path: Path) -> tuple[int, np.ndarray]:
    """Return the element count and numeric recorder rows from OpenSees XML."""
    root = ElementTree.parse(path).getroot()
    element_count = len(root.findall(".//ElementOutput"))
    data_node = root.find(".//Data")
    if element_count == 0 or data_node is None or not data_node.text:
        raise ValueError(f"Incomplete beam-force recorder: {path}")

    number_pattern = re.compile(r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?")
    rows = [
        [float(value) for value in number_pattern.findall(line)]
        for line in data_node.text.splitlines()
        if line.strip()
    ]
    if not rows:
        raise ValueError(f"No force data found in {path}")
    return element_count, np.asarray(rows, dtype=float)


def end_distributions(element_count: int, row: np.ndarray) -> dict[str, np.ndarray]:
    """Collect i-end values and the final j-end value along the pile."""
    values = row[1:].reshape(element_count, 12)
    names = ("Px", "Py", "Pz", "Mx", "My", "Mz")
    return {
        name: np.concatenate((values[:, index], [-values[-1, index + 6]]))
        for index, name in enumerate(names)
    }


def generate_force_plot() -> Path:
    """Plot the final pile force and moment distributions."""
    element_count, history = read_beam_force_xml(FORCE_FILE)
    response = end_distributions(element_count, history[-1])
    depths = np.linspace(LEGACY_PLOT_BOTTOM, LEGACY_PLOT_TOP, element_count + 1)

    # Keep the legacy arrangement and Matplotlib defaults for direct comparison
    # with examples/SoilStructureInteraction/Example0/plot_moment.py.
    figure, axes = plt.subplots(3, 2, figsize=(6, 8), constrained_layout=True)
    components = (
        ("Px", axes[0, 0], "Shear Forces Px"),
        ("Py", axes[0, 1], "Shear Forces Py"),
        ("Pz", axes[1, 0], "Axial Forces Pz"),
        ("Mx", axes[1, 1], "Moments Mx"),
        ("My", axes[2, 0], "Moments My"),
        ("Mz", axes[2, 1], "Torsional Moments Mz"),
    )
    for component, axis, title in components:
        axis.plot(response[component], depths, "-", alpha=1.0)
        axis.set_title(title)
        axis.grid(True, which="both", linestyle="--", alpha=0.5)
        axis.set_xlabel("Force / Moment")
        axis.set_ylabel("Depth")
        axis.axvline(0, color="black", linewidth=0.8, linestyle="-", alpha=0.7)

    OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
    figure.savefig(OUTPUT_FILE, dpi=300, bbox_inches="tight")
    plt.close(figure)
    return OUTPUT_FILE


def generate_deformation_movie() -> Path:
    """Animate the complete model through the static load progression."""
    result_pattern = str(RESULTS_DIR / "pile_response*.vtkhdf")
    with fm.results.open(result_pattern) as results:
        if results.number_of_partitions != 1:
            raise ValueError("This serial example expects one VTKHDF result file")

        reader = results.readers[0]
        mesh = results.mesh(copy=True)
        original_points = mesh.points.copy()
        line_cells = mesh.celltypes == int(pv.CellType.LINE)
        pile_mesh = mesh.extract_cells(line_cells)
        pile_point_ids = np.asarray(
            pile_mesh.point_data["vtkOriginalPointIds"],
            dtype=int,
        )

        undeformed = mesh.copy(deep=True)
        displacement = reader.point_frame("displacement", 0)
        magnitude = np.linalg.norm(displacement[:, :3], axis=1)
        final_displacement = reader.point_frame("displacement", -1)[:, :3]
        maximum_displacement = float(
            max(np.linalg.norm(final_displacement, axis=1).max(), 1.0e-12)
        )
        mesh.point_data["Displacement magnitude"] = magnitude

        plotter = pv.Plotter(off_screen=True, window_size=(1100, 680))
        # plotter.add_mesh(
        #     undeformed,
        #     color="#aeb8b8",
        #     opacity=0.08,
        #     show_edges=True,
        #     edge_color="#718083",
        #     line_width=0.5,
        # )
        plotter.add_mesh(
            mesh,
            scalars="Displacement magnitude",
            cmap="cividis",
            opacity=1.0,
            show_edges=True,
            edge_color="#9b9687",
            line_width=0.6,
            clim=(0.0, maximum_displacement*0.05),
            # scalar_bar_args={"title": "Displacement (m)"},
            show_scalar_bar= False

        )
        plotter.add_mesh(
            pile_mesh,
            color="#17252b",
            line_width=10,
            render_lines_as_tubes=True,
        )
        plotter.add_text(
            f"Load factor: 0.00   Deformation scale: {DEFORMATION_SCALE:g}x",
            name="load-factor",
            font_size=12,
        )

        plotter.view_xz()
        #  goes a liittle up to show the pile head
        plotter.camera.elevation = 30
        # plotter.enable_parallel_projection()


        # plotter.camera_position = [
        #     (0.0, -34.0, -3.5),
        #     (0.0, 0.0, -3.5),
        #     (0.0, 0.0, 1.0),
        # ]
        plotter.set_background("#f6f4ef")

        MOVIE_FILE.parent.mkdir(parents=True, exist_ok=True)
        plotter.open_movie(
            str(MOVIE_FILE),
            framerate=MOVIE_FRAME_RATE,
            quality=7,
        )
        load_factors = results.times
        if load_factors is None:
            load_factors = np.linspace(0.0, 1.0, results.number_of_steps)

        try:
            for step in tqdm(
                range(results.number_of_steps),
                desc="Rendering lateral deformation",
                unit="frame",
            ):
                displacement = reader.point_frame("displacement", step)[:, :3]
                mesh.points = original_points + DEFORMATION_SCALE * displacement
                mesh.point_data["Displacement magnitude"] = np.linalg.norm(
                    displacement,
                    axis=1,
                )
                pile_mesh.points = mesh.points[pile_point_ids]
                plotter.add_text(
                    (
                        f"Load factor: {float(load_factors[step]):.2f}   "
                        f"Deformation scale: {DEFORMATION_SCALE:g}x"
                    ),
                    name="load-factor",
                    font_size=12,
                )
                plotter.write_frame()
        finally:
            plotter.close()
    return MOVIE_FILE


def generate_results() -> tuple[Path, ...]:
    """Generate the standard static result figures."""
    return (generate_force_plot(),)


def generate_animations() -> tuple[Path, ...]:
    """Generate the optional complete-model deformation animation."""
    return (generate_deformation_movie(),)


def main() -> None:
    generated = (*generate_results(), *generate_animations())
    print("Post-processing outputs:")
    for output in generated:
        print(f"  {output.resolve()}")


if __name__ == "__main__":
    main()

This archived benchmark figure is retained from the legacy example so the migration does not require another solver run. The six distributions check the dominant lateral shear and bending response and expose unintended out-of-plane or torsional force. Regenerate it with the maintained postprocessor when current analysis results are available.

Pile force and moment distributions

The animation shows the complete soil-pile model as the lateral load is applied. The soil mesh remains visible while the pile is overlaid as a dark line, making the relative deformation and pile position easy to inspect. The annotation reports load factor because this is a static analysis.

Run The Example

For local model export:

python examples/soil_structure_interaction/laterally_loaded_pile.py

To execute OpenSees as well:

$env:FEMORA_OPENSEES = "D:\path\to\OpenSees.exe"
python examples/soil_structure_interaction/laterally_loaded_pile.py
Complete source
# =============================================================================
# Femora: Fast Efficient Meta-modeling for OpenSees-based Resilience Analysis
# Copyright 2026 Amin Pakzad and Pedro Arduino
# Developed at the UW Geotechnical Lab
# SPDX-License-Identifier: Apache-2.0
# =============================================================================

# femora-postprocess: examples/soil_structure_interaction/laterally_loaded_pile_postprocess.py

# %% [markdown]
# # Laterally Loaded Pile
#
# Embed a displacement-based pile in a graded elastic soil domain, apply a
# horizontal head load, and recover the pile force and moment distributions.

# %%
"""Build and optionally run the laterally loaded pile example."""

from __future__ import annotations

import math
import os
from pathlib import Path

from femora import Model, runtime


OUTPUT_DIR = Path("example_outputs") / "laterally_loaded_pile"
RESULTS_DIR = OUTPUT_DIR / "results"
OPENSEES = os.environ.get("FEMORA_OPENSEES")
PLOT_MODEL = False

SOIL_BOUNDS = (-8.0, 8.0, -8.0, 8.0, -10.0, 0.0)
SOIL_DIVISIONS = (8, 8, 10)
SOIL_GRADING_RATIO = 0.8

PILE_BOTTOM = (0.0, 0.0, -10.0)
PILE_HEAD = (0.0, 0.0, 1.0)
PILE_DIAMETER = 1.0
PILE_ELEMENTS = 20
HEAD_LOAD = 1.0e6


# %% [markdown]
# ## Build the graded soil domain
#
# Four independently graded mesh parts place smaller cells near the pile while
# preserving a wider far-field boundary. All values use a consistent N-m-s
# unit system.

# %%
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
model = Model(
    model_name="laterally_loaded_pile",
    model_path=str(OUTPUT_DIR.resolve()),
)
model.set_results_folder(RESULTS_DIR.resolve().as_posix())

soil_material = model.material.nd.elastic_isotropic(
    user_name="elastic_soil",
    E=2.0e8,
    nu=0.4,
    rho=2100.0,
)
soil_element = model.element.brick.std(
    ndof=3,
    material=soil_material,
)

x_min, x_max, y_min, y_max, z_min, z_max = SOIL_BOUNDS
nx, ny, nz = SOIL_DIVISIONS
r = SOIL_GRADING_RATIO
soil_blocks = [
    ("soil_sw", x_min, 0.0, y_min, 0.0, r, r),
    ("soil_se", 0.0, x_max, y_min, 0.0, 1.0 / r, r),
    ("soil_nw", x_min, 0.0, 0.0, y_max, r, 1.0 / r),
    ("soil_ne", 0.0, x_max, 0.0, y_max, 1.0 / r, 1.0 / r),
]

soil_part_names = []
for name, block_x_min, block_x_max, block_y_min, block_y_max, x_ratio, y_ratio in soil_blocks:
    model.meshpart.volume.geometric_rectangular_grid(
        user_name=name,
        element=soil_element,
        x_min=block_x_min,
        x_max=block_x_max,
        y_min=block_y_min,
        y_max=block_y_max,
        z_min=z_min,
        z_max=z_max,
        nx=nx,
        ny=ny,
        nz=nz,
        x_ratio=x_ratio,
        y_ratio=y_ratio,
        z_ratio=r,
    )
    soil_part_names.append(name)


# %% [markdown]
# ## Define the pile
#
# The pile is a circular elastic beam-column with six degrees of freedom per
# node. Its line mesh crosses the ground surface and continues one meter above
# it so the loaded head remains visible and accessible.

# %%
pile_radius = PILE_DIAMETER / 2.0
pile_E = 1.0e10
pile_nu = 0.3
pile_G = pile_E / (2.0 * (1.0 + pile_nu))
pile_area = math.pi * PILE_DIAMETER**2 / 4.0
pile_I = math.pi * PILE_DIAMETER**4 / 64.0
pile_J = math.pi * PILE_DIAMETER**4 / 32.0

pile_section = model.section.beam.elastic(
    user_name="pile_section",
    E=pile_E,
    A=pile_area,
    Iz=pile_I,
    Iy=pile_I,
    G=pile_G,
    J=pile_J,
)
pile_transformation = model.transformation.transformation3d(
    transf_type="PDelta",
    vecxz_x=-1.0,
    vecxz_y=0.0,
    vecxz_z=0.0,
)
pile_element = model.element.beam.disp(
    ndof=6,
    section=pile_section,
    transformation=pile_transformation,
    numIntgrPts=5,
)
model.meshpart.line.single_line(
    user_name="pile",
    element=pile_element,
    x0=PILE_BOTTOM[0],
    y0=PILE_BOTTOM[1],
    z0=PILE_BOTTOM[2],
    x1=PILE_HEAD[0],
    y1=PILE_HEAD[1],
    z1=PILE_HEAD[2],
    number_of_lines=PILE_ELEMENTS,
)


# %% [markdown]
# ## Couple and assemble the model
#
# The interface is declared before assembly because it needs to observe the
# assembled pile and soil cells while Femora resolves their coupling.

# %%
pile_soil_interface = model.interface.beam_solid_interface(
    name="pile_soil_interface",
    beam_part="pile",
    solid_parts=soil_part_names,
    radius=pile_radius,
    n_peri=8,
    n_long=4,
    penalty_param=1.0e12,
    g_penalty=True,
)

model.assembler.create_section(
    meshparts=soil_part_names,
    num_partitions=0,
    merge_points=True,
    tolerance=5.0e-2,
)
model.assembler.create_section(
    meshparts=["pile"],
    num_partitions=0,
    merge_points=False,
)
model.assembler.assemble(merge_points=True, progress_callback=lambda *_: None)

model.constraint.sp.fix_macro_x_min(dofs=[1, 1, 1], tol=1.0e-6)
model.constraint.sp.fix_macro_x_max(dofs=[1, 1, 1], tol=1.0e-6)
model.constraint.sp.fix_macro_y_min(dofs=[1, 1, 1], tol=1.0e-6)
model.constraint.sp.fix_macro_y_max(dofs=[1, 1, 1], tol=1.0e-6)
model.constraint.sp.fix_macro_z_min(dofs=[1, 1, 1], tol=1.0e-6)


# %% [markdown]
# ## Apply the head load and record response

# %%
pile_head_nodes = model.mask.nodes.near_point(point=PILE_HEAD, radius=1.0e-4)
if len(pile_head_nodes) != 1:
    raise RuntimeError(f"Expected one pile-head node, found {len(pile_head_nodes)}")

load_series = model.time_series.linear(factor=1.0)
lateral_pattern = model.pattern.plain(time_series=load_series)
lateral_pattern.add_load.node(
    node_mask=pile_head_nodes,
    values=[HEAD_LOAD, 0.0, 0.0, 0.0, 0.0, 0.0],
)

domain_recorder = model.recorder.vtkhdf(
    file_base_name="pile_response.vtkhdf",
    resp_types=["disp"],
)
pile_force_recorder = model.recorder.beam_force(
    meshparts=["pile"],
    force_type="globalForce",
    file_prefix="pile_force",
    include_time=True,
    output_format="xml",
)


# %% [markdown]
# ## Define the static analysis and process

# %%
static_analysis = model.analysis.static(
    name="lateral_head_load",
    constraint_handler=model.analysis.constraint.penalty(
        alpha_s=1.0e15,
        alpha_m=1.0e15,
    ),
    numberer=model.analysis.numberer.rcm(),
    system=model.analysis.system.bandgeneral(),
    algorithm=model.analysis.algorithm.modifiednewton(factor_once=True),
    test=model.analysis.test.normdispincr(
        tol=1.0e-3,
        max_iter=5,
        print_flag=2,
    ),
    integrator=model.analysis.integrator.loadcontrol(incr=0.01),
    num_steps=100,
)

model.process.add_step(lateral_pattern, "Apply the lateral pile-head load")
model.process.add_step(domain_recorder, "Record the soil and pile displacement")
model.process.add_step(pile_force_recorder, "Record pile forces and moments")
model.process.add_step(static_analysis, "Run the static loading analysis")


# %% [markdown]
# ## Export and optionally execute

# %%
tcl_file = OUTPUT_DIR / "laterally_loaded_pile.tcl"
model.export_to_tcl(
    filename=str(tcl_file.resolve()),
    progress_callback=lambda *_: None,
)

print("\nLaterally loaded pile")
print(f"  Nodes:       {model.assembled_mesh.n_points}")
print(f"  Elements:    {model.assembled_mesh.n_cells}")
print(f"  Soil parts:  {len(soil_part_names)} graded blocks")
print(f"  Pile:        {PILE_ELEMENTS} beam elements")
print(f"  Tcl model:   {tcl_file.resolve()}")

if OPENSEES is None:
    print("  Solver:      not run (set FEMORA_OPENSEES to run OpenSees)")
else:
    runtime.run(
        tcl_file,
        executable=OPENSEES,
        cwd=OUTPUT_DIR.resolve(),
    )
    print("  Solver:      completed")


# %% [markdown]
# ## Optional visualization

# %%
if PLOT_MODEL:
    pile_soil_interface.plot(show_mesh=True, show_envelope=True)