Skip to content

Planar 5×7-bay grid with mixed unilateral and bilateral members

Part 4 of the unilateral-elements series.

A rectangular grid in the XY plane, 55 m × 42 m:

- 5 bays along X × 7 bays along Y → (nx+1)·(ny+1) = 6×8 = 48 nodes
- each bay is 11 m × 6 m

Every bay is framed like this:

n_ij ────── tie along X ─────── n_(i+1)j
│ \ / │
│ \ diag A / │ struts (diag A and B) are
│ \ / │ compression-only (StrutElement)
│ Y-truss \ / │ the Y-edges are bilateral
│ (bilateral) \ / │ TrussElements; the X-edges
│ \ / │ are tension-only TieElements
│ \/ │
│ /\ │
│ / \ │
│ / \ │
│ / \ │
│ / diag B \ │
│ / \ │
│ / \ │
n_i(j+1) ─── tie along X ───── n_(i+1)(j+1)

The four global-corner nodes are pinned. Every other node is rollerXY (free in x and y, clamped in z only) so the grid stays planar but can deform in-plane.

A −Y force (into the top edge, toward the grid centre) is applied to every node on the top edge that isn’t a corner — four nodes total.

The axial force of every member is computed from the nodal displacements and its unilateral law. A matplotlib figure of the plan view is saved next to the solver output and shown interactively. Each element is colour-coded — blue = compression, red = tension, light gray = slack — and the line width scales with |N|. Pinned corners and load arrows are annotated.

Units: mm / N / MPa.

The model before it is solved: parts, supports and loads

The model before it is solved: its parts, supports (red) and loads (blue).

The result: the deformed shape coloured by displacement (magnitude [mm])

The deformed shape, coloured by displacement (magnitude [mm]), in xfea’s 3D viewer.

Open in 3D turn it, cut it, pick any field: in xfea's viewer, in your browser

examples/scripts/02_core_concepts/unilateral_elements/04_grid_mixed_members.py. Run it from the repository with uv run python examples/scripts/02_core_concepts/unilateral_elements/04_grid_mixed_members.py, or, with xfea-examples installed, xfea-examples run 02_core_concepts/unilateral_elements/04_grid_mixed_members.py.

from __future__ import annotations
import math
from pathlib import Path
from xfea.model import (
ElasticIsotropic,
Model,
Node,
Part,
StrutElement,
StrutSection,
TieElement,
TieSection,
TrussElement,
TrussSection,
)
from xfea.problem import Problem, StaticStep
from xfea.results import DisplacementFieldResults
from xfea_examples import out_dir
# Geometry / material / load
NX, NY = 5, 7 # bays along X and Y
LX_BAY = 11_000.0 # [mm]
LY_BAY = 6_000.0 # [mm]
A_TIE_X = 200.0 # [mm²] slender rod along X (tension only)
A_TRUSS_Y = 500.0 # [mm²] bilateral column member along Y
A_STRUT_DIAG = 300.0 # [mm²] compression-only diagonal brace
P_LOAD = -10_000.0 # [N] force per top-edge (non-corner) node in Y
# negative = pulling the top edge inward
steel = ElasticIsotropic(E=210_000.0, v=0.3, density=7.85e-9, name="steel")
# Model builder
def build_grid() -> tuple[Model, list[list[Node]], list[Node]]:
model = Model(name="grid_mixed_members", description="5×7 bay grid")
part = model.add_part(Part(name="grid"))
tie_x = TieSection(A=A_TIE_X, material=steel)
truss_y = TrussSection(A=A_TRUSS_Y, material=steel)
strut_diag = StrutSection(A=A_STRUT_DIAG, material=steel)
nodes: list[list[Node]] = [[None] * (NY + 1) for _ in range(NX + 1)]
for i in range(NX + 1):
for j in range(NY + 1):
nodes[i][j] = part.add_node(
Node(xyz=[i * LX_BAY, j * LY_BAY, 0.0])
)
# --- TieElement along X: every row, consecutive i, i+1 ---
for j in range(NY + 1):
for i in range(NX):
part.add_element(
TieElement(nodes=[nodes[i][j], nodes[i + 1][j]], section=tie_x)
)
# --- TrussElement along Y: every column, consecutive j, j+1 ---
for i in range(NX + 1):
for j in range(NY):
part.add_element(
TrussElement(nodes=[nodes[i][j], nodes[i][j + 1]], section=truss_y)
)
# --- StrutElement X-bracing: two diagonals per bay ---
for i in range(NX):
for j in range(NY):
part.add_element( # diag A: (i,j) → (i+1, j+1)
StrutElement(
nodes=[nodes[i][j], nodes[i + 1][j + 1]],
section=strut_diag,
)
)
part.add_element( # diag B: (i+1,j) → (i, j+1)
StrutElement(
nodes=[nodes[i + 1][j], nodes[i][j + 1]],
section=strut_diag,
)
)
corners = [nodes[0][0], nodes[NX][0], nodes[0][NY], nodes[NX][NY]]
model.add_pin_bc(nodes=corners)
others = [
nodes[i][j]
for i in range(NX + 1)
for j in range(NY + 1)
if nodes[i][j] not in corners
]
model.add_rollerXY_bc(nodes=others) # free in x, y; clamp z only
top_edge_loaded = [nodes[i][NY] for i in range(1, NX)]
return model, nodes, top_edge_loaded
# Axial force helpers (reconstruct N from nodal displacements)
def _axis(n1: Node, n2: Node) -> tuple[float, float, float]:
dx = float(n2.x) - float(n1.x)
dy = float(n2.y) - float(n1.y)
dz = float(n2.z) - float(n1.z)
mag = math.sqrt(dx * dx + dy * dy + dz * dz)
return (dx / mag, dy / mag, dz / mag)
def _elongation(element, disp_field, time) -> float:
n1, n2 = element.nodes
u1 = disp_field.get_result_at(n1, time=time)
u2 = disp_field.get_result_at(n2, time=time)
du = (
float(u2.x) - float(u1.x),
float(u2.y) - float(u1.y),
float(u2.z) - float(u1.z),
)
ax, ay, az = _axis(n1, n2)
return du[0] * ax + du[1] * ay + du[2] * az
def _axial_mode(element) -> str:
"""Decide which unilateral branch to apply when reconstructing N."""
if isinstance(element, StrutElement):
return "strut"
if isinstance(element, TieElement):
return "tie"
return "bilateral"
def _axial_force(element, disp_field, time) -> float:
L_el = float(element.length)
if L_el <= 0.0:
return 0.0
K = float(element.section.material.E) * float(element.section.A) / L_el
try:
delta = _elongation(element, disp_field, time)
except (TypeError, AttributeError):
return 0.0
if not math.isfinite(delta):
return 0.0
mode = _axial_mode(element)
if mode == "tie":
return K * delta if delta > 0 else 0.0
if mode == "strut":
return K * delta if delta < 0 else 0.0
return K * delta
# Matplotlib view of the axial-force distribution
def plot_axial_forces(
elements,
axial: dict,
corner_nodes,
loaded_nodes,
save_to=None,
show: bool = True,
slack_threshold: float = 1.0,
min_lw: float = 0.6,
max_lw: float = 4.0,
):
"""Draw the grid in plan view (XY) with one coloured line per element.
Colours
-------
- tab:red — tension (N > slack_threshold)
- tab:blue — compression (N < -slack_threshold)
- lightgray — |N| ≤ slack_threshold (the member is slack)
Line width encodes |N| linearly between ``min_lw`` and ``max_lw``.
Pinned corners are drawn as black squares; loaded nodes are annotated
with a load arrow.
"""
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(12, 9))
max_abs_N = max((abs(N) for N in axial.values()), default=1.0) or 1.0
# Sort elements by |N| so the most-loaded members are drawn last
# (and therefore on top of any crossing slack diagonals).
labels = [] # deferred until after the lines are drawn
for el in sorted(elements, key=lambda e: abs(axial.get(e, 0.0))):
N = axial.get(el, 0.0)
n1, n2 = el.nodes
x0, y0 = float(n1.x), float(n1.y)
x1, y1 = float(n2.x), float(n2.y)
if abs(N) <= slack_threshold:
color = "lightgray"
lw = min_lw
z = 1
elif N < 0.0:
color = "tab:blue"
lw = min_lw + (max_lw - min_lw) * (abs(N) / max_abs_N)
z = 2
else:
color = "tab:red"
lw = min_lw + (max_lw - min_lw) * (abs(N) / max_abs_N)
z = 2
ax.plot([x0, x1], [y0, y1], color=color, linewidth=lw,
solid_capstyle="round", zorder=z)
if abs(N) > slack_threshold:
# Put the axial-force label at the element midpoint,
# rotated to sit along the member so the text flows with
# the element's direction. Kilonewtons are the natural
# unit here (everything is in the 10²–10⁴ N range).
mx = 0.5 * (x0 + x1)
my = 0.5 * (y0 + y1)
angle = math.degrees(math.atan2(y1 - y0, x1 - x0))
# Keep the text upright (no upside-down labels).
if angle > 90:
angle -= 180
if angle < -90:
angle += 180
labels.append((mx, my, N, color, angle))
for mx, my, N, color, angle in labels:
text = f"{N / 1000:+.2f} kN"
ax.text(
mx, my, text,
rotation=angle, rotation_mode="anchor",
ha="center", va="center",
fontsize=6, color=color, fontweight="semibold",
bbox=dict(
facecolor="white", edgecolor="none",
alpha=0.85, pad=0.5, boxstyle="round,pad=0.2",
),
zorder=10,
)
# Nodes
all_nodes = {n for el in elements for n in el.nodes}
ax.scatter(
[float(n.x) for n in all_nodes],
[float(n.y) for n in all_nodes],
s=14,
color="black",
zorder=5,
)
# Pinned corner markers
ax.scatter(
[float(n.x) for n in corner_nodes],
[float(n.y) for n in corner_nodes],
s=120,
facecolor="black",
marker="s",
zorder=6,
label="pinned corner",
)
# Load arrows at the loaded nodes (fixed visual length so they're
# legible relative to the bay size regardless of the actual force
# magnitude).
if loaded_nodes:
arrow_len = 0.6 * LY_BAY # mm
dy = -arrow_len if P_LOAD < 0 else +arrow_len
for n in loaded_nodes:
ax.annotate(
"",
xy=(float(n.x), float(n.y) + dy),
xytext=(float(n.x), float(n.y)),
arrowprops=dict(arrowstyle="-|>", color="black", lw=1.8,
shrinkA=0, shrinkB=0),
zorder=7,
)
# Legend
compr = mlines.Line2D([], [], color="tab:blue", lw=3, label="compression")
tens = mlines.Line2D([], [], color="tab:red", lw=3, label="tension")
slack = mlines.Line2D([], [], color="lightgray", lw=1.2, label="slack")
pin = mlines.Line2D([], [], color="black", marker="s", linestyle="None",
markersize=9, label="pinned corner")
ax.legend(handles=[compr, tens, slack, pin], loc="upper right",
framealpha=0.9)
# Style
ax.set_aspect("equal")
ax.set_xlabel("X (mm)")
ax.set_ylabel("Y (mm)")
ax.set_title(
f"Grid axial forces (step end)\n"
f"P_load = {P_LOAD:+.0f} N/node on top edge | "
f"max |N| = {max_abs_N:,.0f} N"
)
ax.grid(True, alpha=0.25, linestyle=":")
# Pad the axis a bit so arrow tips aren't clipped.
ax.margins(0.05)
fig.tight_layout()
if save_to is not None:
fig.savefig(save_to, dpi=150)
print(f" axial-force plot saved: {save_to}")
if show:
print(" (close the matplotlib window to finish)")
plt.show()
else:
plt.close(fig)
# Main
def _classify(element) -> str:
if isinstance(element, StrutElement):
return "strut"
if isinstance(element, TieElement):
return "tie"
return "truss"
def main() -> None:
model, grid, loaded_nodes = build_grid()
elements = list(model.parts[0].elements)
counts = {"truss": 0, "tie": 0, "strut": 0}
for el in elements:
counts[_classify(el)] += 1
print(f"Grid built: {(NX + 1) * (NY + 1)} nodes, {len(elements)} elements")
print(f" TieElement (X, tension-only) : {counts['tie']}")
print(f" TrussElement (Y, bilateral) : {counts['truss']}")
print(f" StrutElement (diag, compression-only): {counts['strut']}")
print(f"Loaded nodes (top edge, Y = {P_LOAD:+.0f} N each) : {len(loaded_nodes)}")
print()
problem = model.add_problem(Problem(name="grid_run"))
step = problem.add_step(
StaticStep(
name="pull_top",
nlgeom=True,
initial_inc_size=0.25,
max_inc_size=1.0,
min_inc_size=1e-4,
max_increments=80,
)
)
step.add_uniform_forcefield(
nodes=loaded_nodes, y=P_LOAD, load_case="pull_top"
)
disp = DisplacementFieldResults()
step.add_field_outputs([disp])
out = Path(out_dir(model.name))
problem.analyse_and_extract(path=out, verbose=True)
# Reconstruct per-element axial force from nodal displacements.
STEP_END = 1.0
axial: dict = {el: _axial_force(el, disp, STEP_END) for el in elements}
print()
print("=" * 70)
print("Results at step end (t = 1.0):")
max_uy = disp.get_max_result("y")
min_uy = disp.get_min_result("y")
print(f" max u_y = {float(max_uy.y):+.3f} mm (node {max_uy.location.key})")
print(f" min u_y = {float(min_uy.y):+.3f} mm (node {min_uy.location.key})")
# Summary of axial forces per element family.
print()
print("Axial force summary (sign: + tension, − compression):")
for kind in ("truss", "tie", "strut"):
forces = [N for el, N in axial.items() if _classify(el) == kind]
if not forces:
continue
peak_t = max(forces)
peak_c = min(forces)
slack = sum(1 for N in forces if abs(N) < 1.0)
print(
f" {kind:<6} ({len(forces):>3} elements) : "
f"N_max = {peak_t:+9.1f} N, N_min = {peak_c:+9.1f} N, "
f"slack ≈ {slack}"
)
# Top-5 tensed and top-5 compressed members for a quick engineering feel.
sorted_by_N = sorted(axial.items(), key=lambda kv: kv[1])
print()
print("Top 5 most-compressed members:")
for el, N in sorted_by_N[:5]:
n1, n2 = el.nodes
print(
f" {_classify(el):<6} elem {el.key:>3} : "
f"N = {N:+9.1f} N "
f"({float(n1.x) / 1000:.1f},{float(n1.y) / 1000:.1f} → "
f"{float(n2.x) / 1000:.1f},{float(n2.y) / 1000:.1f}) m"
)
print("Top 5 most-tensioned members:")
for el, N in sorted_by_N[-5:][::-1]:
n1, n2 = el.nodes
print(
f" {_classify(el):<6} elem {el.key:>3} : "
f"N = {N:+9.1f} N "
f"({float(n1.x) / 1000:.1f},{float(n1.y) / 1000:.1f} → "
f"{float(n2.x) / 1000:.1f},{float(n2.y) / 1000:.1f}) m"
)
print("=" * 70)
# Matplotlib plot: each element drawn in blue (compression),
# red (tension), or light gray (slack), line width scaled by |N|.
png_path = out / "axial_forces.png"
try:
plot_axial_forces(
elements,
axial,
corner_nodes=[grid[0][0], grid[NX][0], grid[0][NY], grid[NX][NY]],
loaded_nodes=loaded_nodes,
save_to=png_path,
show=True,
)
except Exception as exc: # pragma: no cover — matplotlib optional
print(f" plot skipped ({type(exc).__name__}: {exc})")
if __name__ == "__main__":
main()

© 2026 Francesco Ranaudo · Text and pictures CC BY 4.0 · Code Elastic License 2.0 · how to reuse them