"""Validated AgentFEM pilot for structural dynamics and virtual sensing. The pilot deliberately starts from a slender, clamped plane-stress cantilever: its first bending frequency has an independent Euler--Bernoulli reference. A modal solve supplies the frequency scale and Rayleigh damping anchors, while implicit Newmark trajectories retain full displacement, velocity and acceleration fields plus five sparse displacement sensors. """ from __future__ import annotations import argparse import json import math from pathlib import Path from time import perf_counter import h5py import numpy as np from dolfinx import fem from mpi4py import MPI from petsc4py import PETSc from agentfem import ( amplitudes, constitutive, dynamics as dynamics_api, fields, mesh, models, operators, results, studies, ) from agentfem.solvers import prepare_linear_problem ROOT = Path(__file__).resolve().parents[1] DEFAULT_CONFIG = ROOT / "configs" / "t4_structural_dynamics_pilot.json" def load_config(path: Path = DEFAULT_CONFIG) -> dict: return json.loads(path.read_text(encoding="utf-8")) def analytical_first_frequency(config: dict) -> float: geometry = config["geometry"] material = config["material"] beta_1 = 1.875104068711961 length = float(geometry["length_m"]) height = float(geometry["height_m"]) return float( beta_1**2 / (2.0 * math.pi) * math.sqrt( float(material["young_pa"]) * height**2 / (12.0 * float(material["density_kg_m3"]) * length**4) ) ) def _base_model(config: dict, *, analysis: str, cells: tuple[int, int] | None = None): geometry = config["geometry"] material = config["material"] selected_cells = tuple(cells or geometry["cells"]) if analysis == "modal": study = studies.modal_solid(dimension=2, assumption=geometry["assumption"]) elif analysis == "transient": study = studies.dynamic_solid( dimension=2, assumption=geometry["assumption"], method=config["dynamics"]["method"], ) else: raise ValueError(f"Unknown analysis {analysis!r}.") domain = mesh.rectangle( (0.0, 0.0), (float(geometry["length_m"]), float(geometry["height_m"])), selected_cells, comm=MPI.COMM_SELF, cell_type=geometry["cell_type"], ) model = models.create(study=study, mesh=domain, name=f"t4_cantilever_{analysis}") displacement = model.field( fields.displacement(domain, degree=int(geometry["displacement_degree"])) ) model.material( constitutive.isotropic_elastic( young=float(material["young_pa"]), poisson=float(material["poisson"]), density=float(material["density_kg_m3"]), name=material["name"], ) ) left = mesh.face(domain, axis="x", value=0.0, name="fixed_end", tag=1) right = mesh.face( domain, axis="x", value=float(geometry["length_m"]), name="loaded_end", tag=2, ) model.clamp(displacement, on=left) return model, displacement, right def solve_modes(config: dict, *, cells: tuple[int, int] | None = None, modes: int = 4): model, displacement, _ = _base_model(config, analysis="modal", cells=cells) result = model.step(target=displacement, modes=modes).solve_result() return result def rayleigh_coefficients(frequencies_hz: np.ndarray, damping_ratio: float) -> tuple[float, float]: omega_1, omega_2 = 2.0 * math.pi * np.asarray(frequencies_hz[:2], dtype=float) system = np.array([[1.0 / omega_1, omega_1], [1.0 / omega_2, omega_2]]) alpha, beta = np.linalg.solve(system, np.full(2, 2.0 * float(damping_ratio))) return float(alpha), float(beta) def component_preserving_zero_bcs(model) -> list: """Create zero kinematic BCs without expanding component subspaces. AgentFEM 0.3.7 reconstructs acceleration constraints on the parent vector space, which expands each component BC to all vector components. Keep this campaign-side compatibility shim until the core implementation preserves ``bc.function_space`` itself. """ result = [] for item in model.constraints: source_bcs = item.bcs if hasattr(item, "bcs") else [item.bc] for bc in source_bcs: zero = fem.Constant(model.mesh, PETSc.ScalarType(0.0)) indices = bc.dof_indices() dofs = indices[0] if isinstance(indices, tuple) else indices result.append(fem.dirichletbc(zero, dofs, bc.function_space)) return result def excitation_amplitude(spec: dict, *, first_frequency_hz: float, duration: float, dt: float): kind = spec["kind"] name = spec["name"] if kind == "sine": return amplitudes.sine( amplitude=1.0, frequency=float(spec["frequency_factor"]) * first_frequency_hz, name=name, ) times = np.arange(0.0, duration + 0.5 * dt, dt) if kind == "half_sine_pulse": pulse_duration = 0.5 / first_frequency_hz values = np.where( times <= pulse_duration, np.sin(math.pi * times / pulse_duration), 0.0, ) elif kind == "chirp": f0 = float(spec["start_frequency_factor"]) * first_frequency_hz f1 = float(spec["end_frequency_factor"]) * first_frequency_hz rate = (f1 - f0) / duration phase = 2.0 * math.pi * (f0 * times + 0.5 * rate * times**2) envelope = np.sin(math.pi * np.clip(times / duration, 0.0, 1.0)) ** 2 values = envelope * np.sin(phase) else: raise ValueError(f"Unknown excitation kind {kind!r}.") return amplitudes.tabular(times, values, name=name, left=0.0, right=0.0) def run_trajectory( config: dict, spec: dict, *, frequencies_hz: np.ndarray, output_dir: Path, dt: float | None = None, save_fields: bool = True, ) -> dict: dynamics = config["dynamics"] geometry = config["geometry"] selected_dt = float(dynamics["dt_s"] if dt is None else dt) duration = float(dynamics["duration_s"]) steps = int(round(duration / selected_dt)) model, displacement, right = _base_model(config, analysis="transient") amplitude = excitation_amplitude( spec, first_frequency_hz=float(frequencies_hz[0]), duration=duration, dt=selected_dt, ) traction = float(dynamics["traction_amplitude_pa"]) driven_load = model.traction( (0.0, -traction), on=right, amplitude=amplitude ) stiffness = model.stiffness(displacement) mass = model.mass(displacement) force = model.external_force(displacement) # The spatial load shape is fixed and only its scalar amplitude changes. # Assemble that shape once; reassembling the full FE vector in every # accepted-step history callback is both unnecessary and very expensive. driven_load.scale.value = PETSc.ScalarType(1.0) unit_force_vector = operators.assemble_vector(force) driven_load.scale.value = PETSc.ScalarType(amplitude(0.0)) alpha, beta = rayleigh_coefficients( frequencies_hz, float(dynamics["target_damping_ratio"]), ) damping = operators.rayleigh_damping( mass, stiffness, mass_coefficient=alpha, stiffness_coefficient=beta, ) compiled_damping = damping.assemble_matrix() sensor_history = tuple( results.probe_history( f"sensor_{index:02d}_uy", at=tuple(point), component=1, unit="m", ) for index, point in enumerate(config["sensors"]) ) power_history = ( results.history( "external_power_w_per_m", lambda accepted_step, time: float( np.real( accepted_step.state.v.value.x.petsc_vec.dot( unit_force_vector ) ) * amplitude(time) ), unit="W/m", ), results.history( "damping_power_w_per_m", lambda accepted_step, time: operators.bilinear_form( compiled_damping, accepted_step.state.v, accepted_step.state.v, ), unit="W/m", ), ) history = sensor_history + power_history output_dir.mkdir(parents=True, exist_ok=True) output = output_dir / f"{spec['name']}.xdmf" if save_fields else None step = model.step( target=displacement, M=mass, C=damping, K=stiffness, F=force, dt=selected_dt, steps=steps, save_every=int(dynamics["save_every"]), print_every=max(1, steps // 5), progress=False, name=f"newmark_{spec['name']}", ) # Linear Newmark has a constant effective operator for this fixed-step, # time-invariant model. Reuse AgentFEM's public prepared-linear lifecycle; # only the right-hand side changes with predictors and load amplitude. original_problem = step.problem corrected_bcs = component_preserving_zero_bcs(model) step.problem = prepare_linear_problem( original_problem.bilinear_form, original_problem.linear_form, original_problem.solution, bcs=corrected_bcs, options=original_problem.solver_options, ) # Preserve the inspection attribute expected by the transient summary. step.problem.solver_options = original_problem.solver_options started = perf_counter() result = step.solve_result(output=output, history=history) wall = perf_counter() - started time = np.asarray(result.histories[sensor_history[0].name].abscissa, dtype=float) sensors = np.column_stack( [ np.asarray(result.histories[item.name].values, dtype=float) for item in sensor_history ] ) force_scale = np.asarray([amplitude(item) for item in time], dtype=float) strain_energy = np.asarray(result.histories["strain_energy"].values) kinetic_energy = np.asarray(result.histories["kinetic_energy"].values) external_power = np.asarray(result.histories["external_power_w_per_m"].values) damping_power = np.asarray(result.histories["damping_power_w_per_m"].values) increments = np.diff(time) external_work = np.concatenate( ([0.0], np.cumsum(0.5 * increments * (external_power[:-1] + external_power[1:]))) ) damping_dissipation = np.concatenate( ([0.0], np.cumsum(0.5 * increments * (damping_power[:-1] + damping_power[1:]))) ) mechanical_energy = strain_energy + kinetic_energy energy_balance_residual = ( mechanical_energy - mechanical_energy[0] + damping_dissipation - external_work ) # Use one trajectory-level reference scale. A pointwise denominator is # nearly zero during the first load increments and can turn a negligible # absolute residual into a misleadingly large percentage. energy_reference_scale = max( float(np.max(np.abs(mechanical_energy - mechanical_energy[0]))), float(np.max(np.abs(damping_dissipation))), float(np.max(np.abs(external_work))), float(np.finfo(float).eps), ) return { "name": spec["name"], "spec": spec, "dt_s": selected_dt, "steps": steps, "time_s": time, "force_scale": force_scale, "sensor_displacement_m": sensors, "strain_energy_j_per_m": strain_energy, "kinetic_energy_j_per_m": kinetic_energy, "external_power_w_per_m": external_power, "damping_power_w_per_m": damping_power, "external_work_j_per_m": external_work, "damping_dissipation_j_per_m": damping_dissipation, "energy_balance_residual_j_per_m": energy_balance_residual, "energy_balance_reference_j_per_m": energy_reference_scale, "energy_balance_relative_residual": ( energy_balance_residual / energy_reference_scale ), "rayleigh_mass_coefficient_per_s": alpha, "rayleigh_stiffness_coefficient_s": beta, "wall_time_s": wall, "field_hdf5": ( None if not save_fields else str(Path(result.artifacts["fields_hdf5"]).resolve()) ), "field_xdmf": ( None if not save_fields else str(Path(result.artifacts["fields_xdmf"]).resolve()) ), "dof_count": int(step.state.u.value.x.array.size), "kinematic_bc_scalar_dof_count": int( sum(bc.dof_indices()[1] for bc in corrected_bcs) ), "final_displacement_norm": float(np.linalg.norm(step.state.u.value.x.array)), "final_velocity_norm": float(np.linalg.norm(step.state.v.value.x.array)), "final_acceleration_norm": float(np.linalg.norm(step.state.a.value.x.array)), "geometry": geometry, } def read_field_history(path: str | Path) -> dict[str, np.ndarray]: """Read AgentFEM's scientific HDF5 field history into dense arrays.""" with h5py.File(path, "r") as h5: frame_names = sorted(h5["Frames"]) return { "time_s": np.asarray( [h5[f"Frames/{name}"].attrs["coordinate"] for name in frame_names], dtype=float, ), "reference_geometry_m": np.asarray(h5["Mesh/ReferenceGeometry"]), "topology": np.asarray(h5["Mesh/Topology"]), "displacement_m": np.stack( [np.asarray(h5[f"Frames/{name}/Point/U"]) for name in frame_names] ), "velocity_m_per_s": np.stack( [ np.asarray(h5[f"Frames/{name}/Point/Velocity"]) for name in frame_names ] ), "acceleration_m_per_s2": np.stack( [ np.asarray(h5[f"Frames/{name}/Point/Acceleration"]) for name in frame_names ] ), } def write_pilot_hdf5(path: Path, config: dict, modal: dict, trajectories: list[dict]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with h5py.File(path, "w") as h5: h5.attrs["schema"] = "agentfem.physics-data.structural-dynamics-pilot" h5.attrs["schema_version"] = "0.1.0" h5.attrs["trajectory_count"] = len(trajectories) h5.attrs["config_json"] = json.dumps(config, sort_keys=True) modal_group = h5.create_group("modal") for key, value in modal.items(): modal_group.create_dataset(key, data=np.asarray(value)) root = h5.create_group("trajectories") common_written = False for trajectory in trajectories: group = root.create_group(trajectory["name"]) group.attrs["spec_json"] = json.dumps(trajectory["spec"], sort_keys=True) for key in ( "dt_s", "steps", "rayleigh_mass_coefficient_per_s", "rayleigh_stiffness_coefficient_s", "wall_time_s", "dof_count", "final_displacement_norm", "final_velocity_norm", "final_acceleration_norm", "energy_balance_reference_j_per_m", ): group.attrs[key] = trajectory[key] for key in ( "time_s", "force_scale", "sensor_displacement_m", "strain_energy_j_per_m", "kinetic_energy_j_per_m", "external_power_w_per_m", "damping_power_w_per_m", "external_work_j_per_m", "damping_dissipation_j_per_m", "energy_balance_residual_j_per_m", "energy_balance_relative_residual", ): group.create_dataset(key, data=trajectory[key], compression="gzip") for key in ("field_hdf5", "field_xdmf"): if trajectory[key] is not None: group.attrs[key] = trajectory[key] if trajectory["field_hdf5"] is not None: fields_data = read_field_history(trajectory["field_hdf5"]) if not common_written: common = h5.create_group("common") common.create_dataset( "reference_geometry_m", data=fields_data["reference_geometry_m"], ) common.create_dataset("topology", data=fields_data["topology"]) common.create_dataset( "sensor_coordinates_m", data=np.asarray(config["sensors"], dtype=float), ) common_written = True field_group = group.create_group("fields") for key in ( "time_s", "displacement_m", "velocity_m_per_s", "acceleration_m_per_s2", ): field_group.create_dataset( key, data=fields_data[key], compression="gzip", shuffle=True, ) def make_preview( path: Path, config: dict, modal_array: np.ndarray, trajectories: list[dict], ) -> None: import matplotlib.pyplot as plt figure, axes = plt.subplots(2, 2, figsize=(12.5, 8.0), constrained_layout=True) cells = np.asarray(config["verification"]["modal_meshes"], dtype=float)[:, 0] axes[0, 0].plot(cells, modal_array[:, 0], "o-", label="AgentFEM Q2") axes[0, 0].axhline( analytical_first_frequency(config), color="black", linestyle="--", label="Euler--Bernoulli", ) axes[0, 0].set( xlabel="longitudinal cells", ylabel="first frequency (Hz)", title="Modal verification", ) axes[0, 0].legend(frameon=False) for trajectory in trajectories: axes[0, 1].plot( trajectory["time_s"], trajectory["force_scale"], label=trajectory["name"].replace("_", " "), ) axes[0, 1].set( xlabel="time (s)", ylabel="normalized load", title="Four excitation histories", ) axes[0, 1].legend(frameon=False, fontsize=8) for trajectory in trajectories: axes[1, 0].plot( trajectory["time_s"], 1.0e3 * trajectory["sensor_displacement_m"][:, -1], label=trajectory["name"].replace("_", " "), ) axes[1, 0].set( xlabel="time (s)", ylabel="tip displacement (mm)", title="Virtual tip sensor", ) selected = trajectories[0] field = read_field_history(selected["field_hdf5"]) magnitudes = np.linalg.norm(field["displacement_m"][:, :, :2], axis=2) frame = int(np.argmax(np.max(magnitudes, axis=1))) coordinates = field["reference_geometry_m"] color = field["displacement_m"][frame, :, 1] scatter = axes[1, 1].scatter( coordinates[:, 0], coordinates[:, 1], c=color, s=26, cmap="coolwarm", ) axes[1, 1].set_aspect("equal") axes[1, 1].set( title=f"Full-field vertical displacement, t={field['time_s'][frame]:.4f} s", xlabel="x (m)", ylabel="y (m)", ) figure.colorbar(scatter, ax=axes[1, 1], label="vertical displacement (m)") figure.suptitle( "AgentFEM T4 structural dynamics and virtual sensing pilot", fontsize=15, ) figure.savefig(path, dpi=180) plt.close(figure) def run_pilot(config_path: Path, *, smoke: bool = False) -> dict: config = load_config(config_path) output_dir = ROOT / "data" / "t4_structural_dynamics_pilot" fields_dir = output_dir / "fields" modal_meshes = [tuple(item) for item in config["verification"]["modal_meshes"]] modal_frequencies = [] for cells in modal_meshes: result = solve_modes(config, cells=cells, modes=4) modal_frequencies.append(np.asarray(result.quantity("frequencies"), dtype=float)) selected_frequencies = modal_frequencies[1] specs = config["excitations"][:1] if smoke else config["excitations"] trajectories = [ run_trajectory( config, spec, frequencies_hz=selected_frequencies, output_dir=fields_dir, ) for spec in specs ] time_refinement_relative_l2 = None dominant_frequency_hz = None damping_estimate = None if not smoke: coarse = trajectories[0] fine_dt = float(config["verification"]["time_refinement_dt_s"][-1]) fine = run_trajectory( config, config["excitations"][0], frequencies_hz=selected_frequencies, output_dir=fields_dir, dt=fine_dt, save_fields=False, ) fine_on_coarse = np.column_stack( [ np.interp( coarse["time_s"], fine["time_s"], fine["sensor_displacement_m"][:, index], ) for index in range(fine["sensor_displacement_m"].shape[1]) ] ) time_refinement_relative_l2 = float( np.linalg.norm(coarse["sensor_displacement_m"] - fine_on_coarse) / max(np.linalg.norm(fine_on_coarse), np.finfo(float).eps) ) tip = coarse["sensor_displacement_m"][:, -1] spectrum = dynamics_api.spectrum(coarse["time_s"], tip, window="hann") dominant_frequency_hz = float(spectrum.dominant_frequency) pulse_duration = 0.5 / float(selected_frequencies[0]) free_tip = tip[coarse["time_s"] >= pulse_duration] if free_tip.size >= 8: try: damping_estimate = float( dynamics_api.damping_from_free_decay(free_tip).damping_ratio ) except ValueError: damping_estimate = None analytical = analytical_first_frequency(config) modal_array = np.vstack(modal_frequencies) quality = { "analytical_first_frequency_hz": analytical, "modal_cells": modal_meshes, "modal_frequencies_hz": modal_array.tolist(), "finest_first_frequency_relative_error": float( abs(modal_array[-1, 0] - analytical) / analytical ), "last_modal_mesh_relative_change": float( abs(modal_array[-1, 0] - modal_array[-2, 0]) / modal_array[-1, 0] ), "trajectory_count": len(trajectories), "all_finite": bool( all( np.all(np.isfinite(item["sensor_displacement_m"])) and np.all(np.isfinite(item["force_scale"])) and np.all(np.isfinite(item["energy_balance_relative_residual"])) for item in trajectories ) ), "maximum_energy_balance_relative_residual": float( max( np.max(np.abs(item["energy_balance_relative_residual"])) for item in trajectories ) ), "trajectory_energy_balance_relative_residual": { item["name"]: float( np.max(np.abs(item["energy_balance_relative_residual"])) ) for item in trajectories }, "time_refinement_tip_history_relative_l2": time_refinement_relative_l2, "pulse_tip_dominant_frequency_hz": dominant_frequency_hz, "pulse_free_decay_damping_ratio_estimate": damping_estimate, "target_damping_ratio": float(config["dynamics"]["target_damping_ratio"]), } gates = { "analytical_frequency": quality["finest_first_frequency_relative_error"] <= float( config["verification"][ "maximum_first_frequency_analytical_relative_error" ] ), "modal_mesh": quality["last_modal_mesh_relative_change"] <= float(config["verification"]["maximum_modal_mesh_relative_change"]), "time_refinement": smoke or quality["time_refinement_tip_history_relative_l2"] <= float( config["verification"]["maximum_tip_history_relative_l2_change"] ), "finite": quality["all_finite"], "energy_balance": quality["maximum_energy_balance_relative_residual"] <= float( config["verification"]["maximum_energy_balance_relative_residual"] ), } quality["gates"] = gates quality["passed"] = bool(all(gates.values())) output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "quality.json").write_text( json.dumps(quality, indent=2, ensure_ascii=False), encoding="utf-8" ) modal = { "cells": np.asarray(modal_meshes, dtype=int), "frequencies_hz": modal_array, "analytical_first_frequency_hz": np.asarray([analytical]), } write_pilot_hdf5(output_dir / "pilot.h5", config, modal, trajectories) if not smoke: make_preview(output_dir / "preview.png", config, modal_array, trajectories) return quality def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--smoke", action="store_true") args = parser.parse_args() quality = run_pilot(args.config, smoke=args.smoke) if MPI.COMM_WORLD.rank == 0: print(json.dumps(quality, indent=2, ensure_ascii=False)) if __name__ == "__main__": main()