File size: 13,103 Bytes
07af0b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"""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()