{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# STEP import: a steel sleeve in axial tension\n",
    "\n",
    "Create the sleeve or set STEP_FILE to an input STEP file. Runtime 0.2.1a8, CPython 3.13 and the meshing, compute and visualization extras are required.\n",
    "\n",
    "The benchmark sleeve is 100 mm long, with 12 mm inner and 18 mm outer radius. Its upper face carries 40 MPa axial tension. The lower face is fixed and the cylindrical surfaces are traction-free.\n"
   ],
   "id": "step-1"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from importlib.metadata import version\n",
    "from pathlib import Path\n",
    "from time import perf_counter\n",
    "import csv\n",
    "import json\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from onesim.cad import CadGeometryBuilder\n",
    "from onesim.cad.d3 import AnnularCylinder, ImportedSolid\n",
    "from onesim.cad.exchange import survey_step\n",
    "from onesim.materials.library import standard_material\n",
    "from onesim.meshing import TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacement, LinearElasticity, Traction, TractionFree,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "\n",
    "assert version(\"onesimulation\") == \"0.2.1a8\"\n",
    "STEP_FILE = None\n",
    "PROFILE = \"FAST\"\n",
    "PROFILES = {\"FAST\": {\"target_size\": 0.006}, \"REFINED\": {\"target_size\": 0.003}}\n",
    "config = PROFILES[PROFILE]\n",
    "output_dir = Path(\"onesimulation_results\")\n",
    "output_dir.mkdir(exist_ok=True)\n",
    "\n",
    "INNER_RADIUS, OUTER_RADIUS, LENGTH = 0.012, 0.018, 0.100\n",
    "TENSILE_STRESS = 40.0e6\n",
    "MATERIAL = standard_material(\"stainless_steel_304\")\n",
    "\n",
    "if STEP_FILE is None:\n",
    "\n",
    "    design = AnnularCylinder(inner_radius=INNER_RADIUS,\n",
    "                              outer_radius=OUTER_RADIUS, length=LENGTH)\n",
    "    built_geometry = CadGeometryBuilder().build(design)\n",
    "    step_path = output_dir / \"sleeve.step\"\n",
    "    built_geometry.kernel.export_step(built_geometry.reference, step_path)\n",
    "    expected_volume = design.measure\n",
    "else:\n",
    "    step_path = Path(STEP_FILE)\n",
    "    expected_volume = None\n",
    "assert step_path.is_file() and step_path.stat().st_size > 0, step_path\n",
    "print(f\"STEP file: {step_path} ({step_path.stat().st_size / 1024:.1f} KiB)\")\n"
   ],
   "id": "step-2"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inspect the imported faces\n",
    "\n",
    "Read the STEP survey before assigning boundary conditions. STEP exchange does not carry the names used by the simulation model. The four face groups below describe this sleeve and should be checked for every replacement file.\n"
   ],
   "id": "step-3"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "survey = survey_step(step_path)\n",
    "print(f\"Faces: {survey.face_count}; Volume: {survey.volume:.6e} m^3; \"\n",
    "      f\"Unit: {survey.unit}\")\n",
    "print(f\"Bounding box: \"\n",
    "      + \", \".join(f\"{value:+.4f}\" for value in survey.bounds))\n",
    "print()\n",
    "print(f\"{'Index':>5}  {'Name':<10} {'Area / m^2':>14}  Normal\")\n",
    "for face in survey:\n",
    "    normal = \", \".join(f\"{value:+.3f}\" for value in face.normal)\n",
    "    print(f\"{face.index:>5}  {face.member:<10} {face.area:>14.6e}  ({normal})\")\n",
    "\n",
    "if expected_volume is not None:\n",
    "\n",
    "    relative_volume_error = abs(survey.volume / expected_volume - 1.0)\n",
    "    assert relative_volume_error < 1e-9, relative_volume_error\n",
    "    print(f\"\\nRelative volume difference from the design: {relative_volume_error:.3e}\")\n"
   ],
   "id": "step-4"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bind the faces, mesh the volume and solve\n",
    "\n",
    "The setup uses stainless steel 304 and small-strain linear elasticity. The fast profile uses a nominal 6 mm mesh size and the refined profile uses 3 mm. The displacement field is computed with quadratic finite elements.\n"
   ],
   "id": "step-5"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "FACE_COUNT = 4\n",
    "FACE_GROUPS = (\n",
    "    (\"inner_wall\", (0,)),\n",
    "    (\"fixed_end\", (1,)),\n",
    "    (\"outer_wall\", (2,)),\n",
    "    (\"loaded_end\", (3,)),\n",
    ")\n",
    "solid = ImportedSolid(path=str(step_path), unit=\"m\",\n",
    "                        face_count=FACE_COUNT, face_groups=FACE_GROUPS)\n",
    "material = MATERIAL.create()\n",
    "model = LinearElasticity(domain=solid.volume, material=material)\n",
    "problem = Problem(\n",
    "    name=\"Imported STEP sleeve under uniform tension\",\n",
    "    geometry=solid, physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacement(boundary=solid.boundaries.fixed_end,\n",
    "                          physics=model, value=(0.0, 0.0, 0.0)),\n",
    "        Traction(boundary=solid.boundaries.loaded_end, physics=model,\n",
    "                 value=(0.0, 0.0, TENSILE_STRESS)),\n",
    "        TractionFree(boundary=solid.boundaries.inner_wall\n",
    "                     | solid.boundaries.outer_wall, physics=model),\n",
    "    ),\n",
    ")\n",
    "\n",
    "start_time = perf_counter()\n",
    "mesh = TetrahedralMesher(target_size=config[\"target_size\"]).generate(solid)\n",
    "meshing_seconds = perf_counter() - start_time\n",
    "start_time = perf_counter()\n",
    "result = Simulation(\n",
    "    problem=problem, mesh=mesh,\n",
    "    numerics=Numerics(spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "                      linear_solver=SparseDirect()),\n",
    ").solve_stationary()\n",
    "solve_seconds = perf_counter() - start_time\n",
    "displacement = result.field(model.displacement)\n",
    "print(f\"Tetrahedra: {mesh.cell_count}; Mesh nodes: {len(mesh.coordinates)}; \"\n",
    "      f\"FEM nodes: {len(displacement.values)}\")\n",
    "print(f\"Meshing: {meshing_seconds:.2f} s; Solving: {solve_seconds:.2f} s\")\n"
   ],
   "id": "step-6"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Verify the loads and displacement\n",
    "\n",
    "Check that the named faces partition the boundary and integrate the applied traction. The ideal axial force is the load times annulus area. Sample axial displacement along the sleeve and compare it with u(z) = sigma z / E. The fixed end restricts transverse contraction, so the bar solution is an approximate reference.\n"
   ],
   "id": "step-7"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "facets_by_group = {\n",
    "    name: len(mesh.facets(getattr(solid.boundaries, name)))\n",
    "    for name, _ in FACE_GROUPS\n",
    "}\n",
    "total_boundary_facets = len(mesh.facets(solid.boundaries.all))\n",
    "assert sum(facets_by_group.values()) == total_boundary_facets\n",
    "print(\"Boundary facets per named face:\", facets_by_group)\n",
    "\n",
    "mean_radius = 0.5 * (INNER_RADIUS + OUTER_RADIUS)\n",
    "angles = np.linspace(0.0, 2.0 * np.pi, 13)[:-1]\n",
    "loaded_end_points = np.column_stack((\n",
    "    mean_radius * np.cos(angles), mean_radius * np.sin(angles),\n",
    "    np.full_like(angles, LENGTH),\n",
    "))\n",
    "loaded_end_displacements = np.asarray(displacement.evaluate(loaded_end_points))\n",
    "fixed_end_points = np.column_stack((\n",
    "    mean_radius * np.cos(angles), mean_radius * np.sin(angles),\n",
    "    np.zeros_like(angles),\n",
    "))\n",
    "max_fixed_displacement = float(np.max(np.abs(displacement.evaluate(fixed_end_points))))\n",
    "\n",
    "z = np.linspace(0.0, LENGTH, 61)\n",
    "axial_points = np.column_stack((np.full_like(z, mean_radius), np.zeros_like(z), z))\n",
    "axial_displacements = np.asarray(displacement.evaluate(axial_points))\n",
    "youngs_modulus = float(MATERIAL.properties[\"youngs_modulus\"])\n",
    "bar_reference = TENSILE_STRESS * z / youngs_modulus\n",
    "computed_elongation = float(loaded_end_displacements[:, 2].mean())\n",
    "reference_elongation = TENSILE_STRESS * LENGTH / youngs_modulus\n",
    "relative_elongation_error = abs(computed_elongation / reference_elongation - 1.0)\n",
    "\n",
    "operator = result.operators[model.model_id]\n",
    "_, _, nodal_loads = operator.conditions(0.0)\n",
    "integrated_load = np.asarray(nodal_loads).reshape(-1, 3).sum(axis=0)\n",
    "cross_section = np.pi * (OUTER_RADIUS**2 - INNER_RADIUS**2)\n",
    "expected_force = TENSILE_STRESS * cross_section\n",
    "\n",
    "relative_transverse_load = float(np.linalg.norm(integrated_load[:2]) / expected_force)\n",
    "relative_axial_load_error = float(abs(integrated_load[2] / expected_force - 1.0))\n",
    "\n",
    "mises = np.asarray(result.field(model.von_mises_stress).evaluate(\n",
    "    np.array([[mean_radius, 0.0, LENGTH / 2]])))\n",
    "relative_mises_error = float(abs(mises[0] / TENSILE_STRESS - 1.0))\n",
    "\n",
    "assert np.isfinite(axial_displacements).all() and np.isfinite(mises).all()\n",
    "assert max_fixed_displacement < 1e-12\n",
    "assert relative_transverse_load < 1e-12\n",
    "assert relative_axial_load_error < 0.01\n",
    "assert float(np.ptp(loaded_end_displacements[:, 2])) / abs(computed_elongation) < 0.01\n",
    "assert relative_elongation_error < 0.03\n",
    "assert relative_mises_error < 0.02\n",
    "\n",
    "print(f\"Elongation: {computed_elongation * 1e6:.3f} um; \"\n",
    "      f\"Bar formula: {reference_elongation * 1e6:.3f} um \"\n",
    "      f\"(difference {100 * relative_elongation_error:.2f} %)\")\n",
    "print(f\"Integrated tensile force: {integrated_load[2]:.6f} N; \"\n",
    "      f\"exact annulus: {expected_force:.6f} N \"\n",
    "      f\"(faceting difference {100 * relative_axial_load_error:.3f} %)\")\n",
    "print(f\"Midheight von Mises stress: {mises[0] / 1e6:.3f} MPa \"\n",
    "      f\"(difference {100 * relative_mises_error:.2f} %)\")\n",
    "\n",
    "csv_path = output_dir / \"step_sleeve.csv\"\n",
    "with csv_path.open(\"w\", encoding=\"utf-8\", newline=\"\") as csv_file:\n",
    "    writer = csv.writer(csv_file)\n",
    "    writer.writerow([\"z_m\", \"ux_m\", \"uy_m\", \"uz_m\", \"bar_reference_uz_m\"])\n",
    "    writer.writerows(np.column_stack((z, axial_displacements, bar_reference)))\n"
   ],
   "id": "step-8"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Export the results\n",
    "\n",
    "Write sampled displacements to CSV, the comparison chart to PNG and SVG, and the volumetric fields to VTK and XDMF for ParaView. Output files are written under onesimulation_results/.\n"
   ],
   "id": "step-9"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import onesim.visualization as visualization\n",
    "from onesim.results.storage import write_for_paraview\n",
    "\n",
    "cream, ink, green, copper = \"#F7F2E7\", \"#223D35\", \"#336B57\", \"#B66E43\"\n",
    "plt.rcParams.update({\"font.family\": \"DejaVu Sans\", \"font.size\": 11,\n",
    "                     \"text.color\": ink, \"axes.labelcolor\": ink,\n",
    "                     \"xtick.color\": ink, \"ytick.color\": ink,\n",
    "                     \"svg.fonttype\": \"none\"})\n",
    "fig, ax = plt.subplots(figsize=(8, 4.5), facecolor=cream)\n",
    "ax.set_facecolor(cream)\n",
    "ax.plot(z * 1000, axial_displacements[:, 2] * 1e6, color=green, linewidth=2.4,\n",
    "        label=\"OneSimulation, quadratic FEM on the imported sleeve\")\n",
    "ax.plot(z * 1000, bar_reference * 1e6, color=copper, linewidth=1.6,\n",
    "        linestyle=\"--\", label=r\"Bar formula $u_z=\\sigma z/E$\")\n",
    "ax.set_xlabel(\"Axial position z / mm\")\n",
    "ax.set_ylabel(r\"Elongation $u_z$ / µm\")\n",
    "ax.set_title(\"STEP sleeve under 40 MPa tensile stress\", color=ink)\n",
    "ax.legend(frameon=False)\n",
    "ax.grid(True, color=ink, alpha=0.12)\n",
    "fig.tight_layout()\n",
    "png_path = output_dir / \"step_sleeve.png\"\n",
    "svg_path = output_dir / \"step_sleeve.svg\"\n",
    "fig.savefig(png_path, dpi=200)\n",
    "fig.savefig(svg_path)\n",
    "\n",
    "PARAVIEW_FIELDS = (model.displacement, model.von_mises_stress, model.stress)\n",
    "paraview_files = [\n",
    "    write_for_paraview(result, mesh, PARAVIEW_FIELDS,\n",
    "                       output_dir / f\"step_sleeve.{suffix}\")\n",
    "    for suffix in (\"vtk\", \"xdmf\")\n",
    "]\n",
    "for path in paraview_files:\n",
    "    assert path.is_file() and path.stat().st_size > 1000, path\n",
    "    print(f\"ParaView file: {path} ({path.stat().st_size / 1024:.1f} KiB)\")\n",
    "\n",
    "figure = visualization.result(result.result_set, model.von_mises_stress.field_id,\n",
    "                              title=\"von Mises stress (Pa)\")\n",
    "assert figure.data, \"The result plot has no data traces\"\n",
    "figure\n"
   ],
   "id": "step-10"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Record the check and its limits\n",
    "\n",
    "The reference record contains the mesh size, integrated load and elongation comparison. This is a small-strain, linearly elastic load case. To adapt it, check the face groups, material, units and reference tolerances for the new geometry.\n"
   ],
   "id": "step-11"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "verification = {\n",
    "    \"passed\": True,\n",
    "    \"profile\": PROFILE,\n",
    "    \"runtime_version\": version(\"onesimulation\"),\n",
    "    \"example\": \"linear elastic tension on a solid imported from STEP\",\n",
    "    \"step_file\": str(step_path),\n",
    "    \"step_file_bytes\": int(step_path.stat().st_size),\n",
    "    \"imported_face_count\": int(survey.face_count),\n",
    "    \"declared_face_count\": FACE_COUNT,\n",
    "    \"imported_volume_m3\": float(survey.volume),\n",
    "    \"imported_bounds_m\": [float(value) for value in survey.bounds],\n",
    "    \"face_group_boundary_facets\": facets_by_group,\n",
    "    \"boundary_facets_total\": int(total_boundary_facets),\n",
    "    \"mesh_cells\": int(mesh.cell_count),\n",
    "    \"mesh_nodes\": int(len(mesh.coordinates)),\n",
    "    \"fem_nodes\": int(len(displacement.values)),\n",
    "    \"material\": MATERIAL.name,\n",
    "    \"material_quality\": MATERIAL.quality,\n",
    "    \"youngs_modulus_pa\": youngs_modulus,\n",
    "    \"applied_tension_pa\": TENSILE_STRESS,\n",
    "    \"cross_section_m2\": float(cross_section),\n",
    "    \"computed_elongation_m\": computed_elongation,\n",
    "    \"bar_formula_elongation_m\": reference_elongation,\n",
    "    \"elongation_relative_difference\": relative_elongation_error,\n",
    "    \"integrated_force_n\": integrated_load.tolist(),\n",
    "    \"target_force_n\": float(expected_force),\n",
    "    \"axial_load_relative_difference\": relative_axial_load_error,\n",
    "    \"transverse_load_relative_error\": relative_transverse_load,\n",
    "    \"midheight_von_mises_pa\": float(mises[0]),\n",
    "    \"midheight_von_mises_relative_difference\": relative_mises_error,\n",
    "    \"mesh_seconds\": float(meshing_seconds),\n",
    "    \"solve_seconds\": float(solve_seconds),\n",
    "    \"output_files\": [str(csv_path), str(png_path), str(svg_path),\n",
    "                     *(str(path) for path in paraview_files)],\n",
    "    \"limitations\": [\n",
    "        \"STEP read with the bundled CAD kernel; other exchange formats are not qualified\",\n",
    "        \"Boundaries are named by kernel face index; recheck the face table after a CAD change\",\n",
    "        \"Nominal handbook material values at 20 degC; no certified material data\",\n",
    "        \"Small-strain stationary isotropic linear elasticity; no contact, plasticity or thermal load\",\n",
    "        \"Bar formula is an approximate reference; the clamped end suppresses lateral contraction\",\n",
    "        \"One mesh is not a convergence study\",\n",
    "        \"The loaded end face is triangulated, so the integrated force is slightly below the exact annulus\",\n",
    "        \"ParaView export samples the quadratic solution at the written mesh vertices\",\n",
    "        \"No experimental or COMSOL validation\",\n",
    "    ],\n",
    "}\n",
    "assert all(Path(path).stat().st_size > 0 for path in verification[\"output_files\"])\n",
    "report_path = output_dir / \"step_sleeve_verification.json\"\n",
    "report_path.write_text(json.dumps(verification, indent=2, ensure_ascii=False),\n",
    "                     encoding=\"utf-8\")\n",
    "print(json.dumps(verification, indent=2, ensure_ascii=False))\n"
   ],
   "id": "step-12"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.13"
  },
  "onesimulation": {
   "runtime_version": "0.2.1a8",
   "example_kind": "application"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
