Datasets:
Tasks:
Other
Formats:
json
Size:
10K - 100K
Tags:
agentfem
soft-robotics
programmable-matter
structural-mechanics
inverse-design
scientific-machine-learning
License:
Download cases/fig9/case.py from HaomingLuo/AgentFEM-Programmable-Soft-Rods: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/datasets/HaomingLuo/AgentFEM-Programmable-Soft-Rods/resolve/main/cases/fig9/case.py
- Command line
-
hf download hf://datasets/HaomingLuo/AgentFEM-Programmable-Soft-Rods/cases/fig9/case.py
-
curl -L -o case.py https://huggingface.co/datasets/HaomingLuo/AgentFEM-Programmable-Soft-Rods/resolve/main/cases/fig9/case.py
13.1 kB
| """Native AgentFEM FE reproduction of Ye et al. (2026), Figure 9. | |
| The paper's homogenized orientational potential is added to a finite-thickness | |
| Saint-Venant--Kirchhoff solid. AgentFEM owns the mesh, P2 displacement field, | |
| material, boundary conditions, Newton solve, DG0 projections, ParaView series, | |
| result manifest and run provenance. The paper equations are used only as an | |
| independent reference and as the Newton initial guess. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| import sys | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import h5py | |
| import copy | |
| import xml.etree.ElementTree as ET | |
| import ufl | |
| from dolfinx import fem | |
| from agentfem import ( | |
| constitutive, | |
| fields, | |
| io, | |
| mesh, | |
| models, | |
| problems, | |
| project, | |
| results, | |
| solvers, | |
| studies, | |
| ) | |
| from agentfem.constitutive import geometric_elasticity, hyperelasticity | |
| from paper_reference import ( | |
| CHI, | |
| DELTA, | |
| H, | |
| LOADS, | |
| critical_load_continuum, | |
| critical_load_discrete, | |
| solve_continuum, | |
| solve_discrete, | |
| ) | |
| def build_native_model(*, nx=100, ny=4): | |
| thickness = float(np.sqrt(12.0 * CHI)) | |
| young = 1.0 / thickness | |
| domain = mesh.rectangle( | |
| (0.0, -0.5 * thickness), | |
| (1.0, 0.5 * thickness), | |
| (nx, ny), | |
| cell_type="quadrilateral", | |
| ) | |
| model = models.create( | |
| study=studies.static_solid( | |
| dimension=2, | |
| assumption="plane_stress", | |
| nonlinear=True, | |
| ), | |
| mesh=domain, | |
| name="homogenized_microforce_rod", | |
| ) | |
| displacement = model.field(fields.displacement(domain, degree=2)) | |
| displacement.value.name = "U" | |
| material = model.material( | |
| constitutive.saint_venant_kirchhoff( | |
| young=young, | |
| poisson=0.0, | |
| plane_stress=True, | |
| name="EA=1_EI=chi", | |
| ) | |
| ) | |
| left = mesh.boundary(domain, lambda x: np.isclose(x[0], 0.0), name="clamp") | |
| right = mesh.boundary(domain, lambda x: np.isclose(x[0], 1.0), name="loaded_end") | |
| model.clamp(displacement, on=left) | |
| u = displacement.value | |
| F = ufl.Identity(2) + ufl.grad(u) | |
| axial_vector = ufl.dot(F, ufl.as_vector((1.0, 0.0))) | |
| axial_stretch = ufl.sqrt(ufl.dot(axial_vector, axial_vector)) | |
| cosine = axial_vector[0] / axial_stretch | |
| load_p = fem.Constant(domain, 0.0) | |
| elastic_density = geometric_elasticity.energy(F, material) | |
| microforce_density = -4.0 * H * DELTA / thickness * (1.0 - cosine) | |
| effective_force = load_p + 2.0 * H | |
| potential = ( | |
| (elastic_density + microforce_density) * ufl.dx | |
| - (effective_force / thickness) * u[0] * right.measure | |
| ) | |
| residual = ufl.derivative(potential, u, displacement.test) | |
| jacobian = ufl.derivative(residual, u, displacement.trial) | |
| nonlinear = problems.nonlinear( | |
| residual, | |
| u, | |
| jacobian=jacobian, | |
| constraints=model.constraints, | |
| solver_options=solvers.NewtonSolverOptions( | |
| absolute_tolerance=1.0e-9, | |
| relative_tolerance=1.0e-9, | |
| maximum_iterations=80, | |
| line_search="basic", | |
| ), | |
| name="ye_2026_model_i_native_fe", | |
| ) | |
| sigma = hyperelasticity.cauchy_stress(u, material) | |
| mises_expression = ufl.sqrt( | |
| sigma[0, 0] ** 2 | |
| - sigma[0, 0] * sigma[1, 1] | |
| + sigma[1, 1] ** 2 | |
| + 3.0 * sigma[0, 1] ** 2 | |
| ) | |
| mises = results.prepare_projection( | |
| mises_expression, | |
| domain=domain, | |
| family="DG", | |
| degree=0, | |
| name="MISES", | |
| ) | |
| orientation_energy = results.prepare_projection( | |
| microforce_density, | |
| domain=domain, | |
| family="DG", | |
| degree=0, | |
| name="MICROFORCE_POTENTIAL", | |
| ) | |
| return { | |
| "domain": domain, | |
| "model": model, | |
| "displacement": displacement, | |
| "material": material, | |
| "problem": nonlinear, | |
| "load_p": load_p, | |
| "mises": mises, | |
| "orientation_energy": orientation_energy, | |
| "thickness": thickness, | |
| "young": young, | |
| "nx": nx, | |
| "ny": ny, | |
| } | |
| def seed_from_reference(displacement, p): | |
| sample, theta, center_x, center_y = solve_continuum(float(p)) | |
| def initial(x): | |
| s = np.clip(x[0], 0.0, 1.0) | |
| xc = np.interp(s, sample, center_x) | |
| yc = np.interp(s, sample, center_y) | |
| angle = np.interp(s, sample, theta) | |
| transverse = x[1] | |
| return np.vstack( | |
| ( | |
| xc - s - transverse * np.sin(angle), | |
| yc + transverse * np.cos(angle) - transverse, | |
| ) | |
| ) | |
| displacement.value.interpolate(initial) | |
| return sample, center_x, center_y | |
| def sample_centerline(displacement, count=301): | |
| s = np.linspace(0.0, 1.0, count) | |
| values = np.asarray( | |
| [results.probe(displacement, at=(float(x), 0.0)) for x in s], | |
| dtype=float, | |
| ) | |
| return s, s + values[:, 0], values[:, 1] | |
| def comparison_plot(path: Path, cases): | |
| figure, axes = plt.subplots(1, 3, figsize=(13.4, 4.7), constrained_layout=True) | |
| for axis, case in zip(axes, cases): | |
| axis.plot( | |
| case["reference_x"], | |
| case["reference_y"], | |
| color="#e31a1c", | |
| lw=3.2, | |
| label="Paper Model (i)", | |
| ) | |
| axis.plot( | |
| case["fe_x"], | |
| case["fe_y"], | |
| color="#00a6a6", | |
| lw=2.0, | |
| ls="--", | |
| label="AgentFEM P2 solid", | |
| ) | |
| axis.plot( | |
| case["discrete_x"], | |
| case["discrete_y"], | |
| "o-", | |
| color="#111827", | |
| markerfacecolor="#facc15", | |
| markeredgecolor="#1d4ed8", | |
| lw=1.1, | |
| ms=3.0, | |
| label="Paper discrete n=15", | |
| ) | |
| axis.set_aspect("equal", adjustable="box") | |
| axis.grid(alpha=0.18) | |
| axis.set_xlabel(r"$x/L$") | |
| axis.set_ylabel(r"$y/L$") | |
| axis.set_title( | |
| rf"$p={case['p']:.6f}$" + "\n" + rf"AgentFEM vs Model (i): {100*case['fe_nrmse']:.3f}%", | |
| fontsize=11, | |
| ) | |
| handles, labels = axes[0].get_legend_handles_labels() | |
| figure.legend(handles, labels, loc="lower center", ncol=3, frameon=False) | |
| figure.suptitle( | |
| "Native AgentFEM finite-element reproduction of Ye et al. (2026), Figure 9\n" | |
| + rf"P2 StVK solid; $\chi=10^{{-4}},\;\delta=0.1,\;h=0.01$", | |
| fontsize=14, | |
| ) | |
| figure.savefig(path, dpi=220, bbox_inches="tight", facecolor="white") | |
| plt.close(figure) | |
| def main(): | |
| run = project.current_run() | |
| native = build_native_model(nx=100, ny=4) | |
| cases = [] | |
| pvd = run.artifact("paraview/native_agentfem_fig9.pvd") | |
| xdmf = run.artifact("xdmf/native_agentfem_fig9.xdmf") | |
| exact = run.artifact("scientific/p2_coefficients.h5") | |
| exact.parent.mkdir(parents=True, exist_ok=True) | |
| with io.ParaViewTimeSeries(pvd, native["domain"]) as writer, io.XDMFTimeSeries(xdmf, native["domain"]) as xwriter, h5py.File(exact, "w") as h5: | |
| h5.attrs["note"] = "Independent load cases, not physical time. Exact P2 coefficients; XDMF U is interpolated to P1." | |
| h5.create_dataset("dof_coordinates", data=native["displacement"].value.function_space.tabulate_dof_coordinates()) | |
| h5.create_dataset("cell_dofs", data=native["displacement"].value.function_space.dofmap.list) | |
| h5.attrs["element"] = "Q2 vector, block size 2, serial coefficients" | |
| for frame, p in enumerate(LOADS): | |
| sample, reference_x, reference_y = seed_from_reference( | |
| native["displacement"], float(p) | |
| ) | |
| native["load_p"].value = float(p) | |
| native["problem"].solve() | |
| group = h5.create_group(f"case_{frame}") | |
| group.attrs["p"] = float(p) | |
| group.create_dataset("U_P2", data=native["displacement"].value.x.array) | |
| mises = native["mises"].solve() | |
| orientation = native["orientation_energy"].solve() | |
| xwriter.write_fields(float(frame), io.interpolate_for_xdmf(native["displacement"], name="U"), mises, orientation) | |
| writer.write_fields( | |
| float(frame), | |
| native["displacement"], | |
| mises, | |
| orientation, | |
| ) | |
| s, fe_x, fe_y = sample_centerline(native["displacement"]) | |
| assert fe_y[-1] < 0.0, "FE must solve the downward branch, not flip it in plotting" | |
| group.create_dataset("centerline", data=np.column_stack([s, fe_x, fe_y])) | |
| target_x = np.interp(s, sample, reference_x) | |
| target_y = np.interp(s, sample, reference_y) | |
| fe_nrmse = float( | |
| np.sqrt(np.mean((fe_x - target_x) ** 2 + (fe_y - target_y) ** 2)) | |
| ) | |
| _, discrete_x, discrete_y = solve_discrete(float(p)) | |
| cases.append( | |
| { | |
| "p": float(p), | |
| "reference_x": reference_x, | |
| "reference_y": reference_y, | |
| "fe_x": fe_x, | |
| "fe_y": fe_y, | |
| "discrete_x": discrete_x, | |
| "discrete_y": discrete_y, | |
| "fe_nrmse": fe_nrmse, | |
| "fe_tip_error": float( | |
| np.hypot(fe_x[-1] - reference_x[-1], fe_y[-1] - reference_y[-1]) | |
| ), | |
| "newton_iterations": int(native["problem"].last_solve_info.iterations), | |
| "residual_norm": float(native["problem"].last_solve_info.function_norm), | |
| } | |
| ) | |
| # DOLFINx emits one temporal collection per field. Merge attributes onto | |
| # one geometry per case so readers do not display undeformed duplicates. | |
| original = ET.parse(xdmf).getroot().find("Domain") | |
| base = original.find("Grid") | |
| merged = ET.Element("Xdmf", Version="3.0") | |
| domain_xml = ET.SubElement(merged, "Domain") | |
| series = ET.SubElement(domain_xml, "Grid", Name="Independent_cases", GridType="Collection", CollectionType="Temporal") | |
| for frame in range(len(LOADS)): | |
| grid = ET.SubElement(series, "Grid", Name=f"case_{frame}", GridType="Uniform") | |
| grid.append(copy.deepcopy(base.find("Topology"))) | |
| grid.append(copy.deepcopy(base.find("Geometry"))) | |
| ET.SubElement(grid, "Time", Value=str(frame)) | |
| for collection in original.findall("Grid[@CollectionType='Temporal']"): | |
| grid.append(copy.deepcopy(collection.findall("Grid")[frame].find("Attribute"))) | |
| ET.indent(merged) | |
| ET.ElementTree(merged).write(xdmf, encoding="utf-8", xml_declaration=True) | |
| table = np.asarray( | |
| [ | |
| [ | |
| item["p"], | |
| item["fe_nrmse"], | |
| item["fe_tip_error"], | |
| item["newton_iterations"], | |
| item["residual_norm"], | |
| ] | |
| for item in cases | |
| ] | |
| ) | |
| metrics_path = run.artifact("native_fe_metrics.csv") | |
| np.savetxt( | |
| metrics_path, | |
| table, | |
| delimiter=",", | |
| header="p,agentfem_centerline_nrmse_over_L,tip_error_over_L,newton_iterations,residual_norm", | |
| comments="", | |
| ) | |
| figure_path = run.artifact("figures/native_agentfem_vs_paper.png") | |
| comparison_plot(figure_path, cases) | |
| result = results.SimulationResult( | |
| "ye_2026_fig9_native_fe", | |
| metadata={ | |
| "paper": { | |
| "title": "Three Homogenization Models for a Nonlinear Heterogeneous Rod with Microscale Dead Loading", | |
| "doi": "10.1016/j.jmps.2026.106870", | |
| "target": "Figure 9 / homogenized Model (i)", | |
| }, | |
| "formulation": { | |
| "mesh": f"{native['nx']} x {native['ny']} quadrilateral", | |
| "field": "P2 displacement", | |
| "material": "plane-stress Saint-Venant--Kirchhoff", | |
| "microforce_term": "Eq. (42) orientation potential", | |
| "solver": "AgentFEM Newton", | |
| "EA": 1.0, | |
| "EI": CHI, | |
| "thickness": native["thickness"], | |
| "young": native["young"], | |
| }, | |
| }, | |
| ) | |
| result.add_history( | |
| "centerline_nrmse", | |
| LOADS, | |
| np.asarray([item["fe_nrmse"] for item in cases]), | |
| abscissa_name="dimensionless_load_p", | |
| abscissa_unit=None, | |
| description="RMS centerline distance normalized by L against paper Model (i).", | |
| ) | |
| result.add_quantity("continuum_critical_load", critical_load_continuum()) | |
| result.add_quantity("discrete_n15_critical_load", critical_load_discrete()) | |
| result.add_field( | |
| "native_agentfem_fields", | |
| artifact=pvd, | |
| description="ParaView PVD series containing U, MISES and MICROFORCE_POTENTIAL.", | |
| ) | |
| result.add_artifact("comparison_figure", figure_path) | |
| result.add_artifact("metrics", metrics_path) | |
| result.add_artifact("exact_p2_coefficients", exact) | |
| result.add_artifact("xdmf_p1_visualization", xdmf) | |
| run.publish(result) | |
| return result | |
| if __name__ == "__main__": | |
| main() | |