Commit Graph

1218 Commits

Author SHA1 Message Date
Jukka Aho e2917cdba8 docs: Add ADR-005 on integration point indices architecture
Document decision to store integration point indices instead of data in Element struct.
Key rationale: Elements should store relationships (indices), not data, for memory
efficiency and consistency with node connectivity pattern. Aligns with nodal assembly
approach and GPU-friendly architecture.
2025-11-12 00:49:17 +02:00
Jukka Aho ba0afce933 docs: Add ADR-004 for zero-allocation integration points API
Architectural Decision Record documenting design of integration points
API for high-performance finite element assembly.

Decision: Compile-time function returning tuple of (weight, Vec{D})
matching eval_basis! zero-cost abstraction pattern.

Problem context:
- OLD API: Runtime dispatch with mutable struct containing Dict
- Performance penalty: ~50× slower due to type instability
- Allocations: New struct created every query
- Impact: Millions of calls during assembly

Solution properties:
- Compile-time generation (fully inlined)
- Vec{D} from Tensors.jl for FEM math
- Zero allocation (tuples, stack-only)
- Type-stable (all types known at compile time)
- GPU compatible (no heap allocations)

API signature:
get_gauss_points!(::Type{Topology}, ::Type{Gauss{order}})
  → NTuple{N, Tuple{Float64, Vec{D}}}

Alternatives rejected:
- Plain tuples (less convenient for FEM math)
- Store in element (overhead, less flexible)
- Global constants (not composable)
- Runtime dispatch (type-unstable, slow)

Status: Accepted, implemented in src/integration/ (193 lines)
2025-11-12 00:44:29 +02:00
Jukka Aho 25af535745 demo: Add Tet10 CPU test and validation
CPU implementation test for 10-node tetrahedral elements validating
shape functions, derivatives, and assembly against analytical solutions.

Validation tests:
1. Shape function partition of unity (Σ N_i = 1)
2. Shape function derivatives correctness
3. Jacobian computation accuracy
4. Element stiffness matrix symmetry
5. Assembly convergence with mesh refinement
6. Comparison against Tet4 (linear elements)

Tet10 specifics tested:
- 10 shape functions (quadratic)
- 4-point Gauss quadrature
- Curved element geometry
- Mid-edge node positioning

Test problems:
- Patch test (constant strain)
- Pure bending (quadratic strain)
- Manufactured solution (known displacement field)

Expected results:
- Tet10 converges faster than Tet4 (fewer elements needed)
- Tet10 captures bending better (quadratic)
- Tet10 passes patch test exactly

Purpose: Establish correctness before GPU port
Reference for gpu_assembly_tet10.jl validation
2025-11-12 00:29:36 +02:00
Jukka Aho 69e3b131b5 demo: Add nodal assembly GPU implementation
GPU port of nodal assembly strategy with CUDA kernels demonstrating
atomic-free assembly on GPU using node-parallel approach.

GPU kernel design:
- One thread per node (not per element)
- Each thread gathers from touching elements
- No atomic operations (node ownership)
- Coalesced memory access via node ordering

Kernel structure:
- Thread ID maps to node ID
- Loop over elements touching this node
- Loop over element nodes for block contributions
- Compute 3×3 stiffness blocks with Tensors.jl
- Accumulate locally, write once to global

Data layout:
- node_to_elements: CSR-like structure on GPU
- Element data: Array of Structs (immutable elements)
- Node displacement: Flat vector (3*n_nodes)
- Result: Flat vector (3*n_nodes)

Performance characteristics:
- Memory bandwidth bound (not compute bound)
- Benefits from coalescing (sequential node access)
- Scalable to multi-GPU (domain decomposition)
- No synchronization within kernel

Comparison to element assembly:
- Element: N_elem threads, atomic scatter
- Nodal: N_nodes threads, no atomics

Reference: CPU version in nodal_assembly_cpu.jl
2025-11-12 00:29:21 +02:00
Jukka Aho 4040a802e5 demo: Add nodal assembly CPU implementation
CPU implementation of nodal assembly strategy (loop over nodes, not
elements) demonstrating modern assembly approach for FEM.

Nodal assembly concept:
- Traditional: Loop over elements, scatter to nodes (atomics needed on GPU)
- Modern: Loop over nodes, gather from elements (no atomics, better GPU)

Algorithm:

Advantages:
- No atomic operations (each node owned by one thread)
- Natural 3×3 block structure (displacement DOFs)
- Contact-ready (contact is naturally nodal)
- GPU-friendly (coalesced memory access)

Implementation:
- Node-to-elements connectivity graph
- Block-based operations with Tensors.jl
- Zero-allocation assembly loop
- Matrix-free operator for iterative solvers

Reference: docs/src/book/multigpu_nodal_assembly.md
2025-11-12 00:29:03 +02:00
Jukka Aho 0bc41c7cf1 demo: Add Newton-Krylov-Anderson CPU reference implementation
Complete CPU reference implementation of Newton-Krylov solver with
Anderson acceleration for nonlinear elasticity with plasticity.

Solver components:
- Newton outer loop (nonlinear iterations)
- GMRES inner loop (linear solve, matrix-free)
- Anderson acceleration (convergence improvement)
- Adaptive GMRES tolerance (Eisenstat-Walker formula)

Matrix-free strategy:
- No tangent matrix assembly
- Jacobian-vector product via finite differences: J·v ≈ [r(u+ε·v)-r(u)]/ε
- Residual assembly: r(u) = f_int(u) - f_ext
- Each GMRES iteration = 2 residual evaluations

Plasticity handling:
- Radial return mapping at each Gauss point
- Material state tracking (ε_p, α) during iterations
- State update only on Newton convergence
- Von Mises yield criterion with perfect plasticity

Reference for GPU implementation:
- Validates numerical correctness
- Establishes performance baseline
- Documents algorithm flow for GPU port
- Shows data dependencies and kernel opportunities

Problem: 3D elasticity with J2 plasticity, Tet4 mesh
2025-11-12 00:28:45 +02:00
Jukka Aho 3daed70615 demo: Add GPU assembly for Tet10 higher-order elements
GPU implementation for 10-node tetrahedral elements demonstrating
higher-order finite elements with quadratic shape functions.

Tet10 specifics:
- 10 nodes per element (vertices + edge midpoints)
- 4-point Gauss quadrature (order 2)
- Quadratic shape functions (N_i second-order polynomials)
- Shape function derivatives via analytical formulas

Challenges vs Tet4:
- More integration points (4 vs 1)
- More DOFs per element (30 vs 12)
- More complex shape functions
- Larger local stiffness (10×10 vs 4×4 blocks)

GPU kernel modifications:
- Loop over 4 Gauss points instead of 1
- Evaluate quadratic shape functions at each IP
- Accumulate contributions from all IPs
- Scatter 30 DOFs per element (not 12)

Benefits of Tet10:
- Better stress/strain representation
- Fewer elements needed for accuracy
- Curved boundary representation
- Higher convergence rate

Same problem setup: 3D cantilever with steel properties
Test validates GPU higher-order element implementation (430 lines).
2025-11-12 00:28:24 +02:00
Jukka Aho 036331d82e demo: Add Tensors.jl-corrected GPU assembly POC
Corrected GPU assembly using proper Tensors.jl material modeling
instead of plain vectors with manual indexing.

Architectural improvements:
- SymmetricTensor{2,2} for 2D strain and stress
- Material API: compute_stress(material, ε)
- LinearElastic struct with Lamé parameters
- Hooke's law: σ = λ·tr(ε)·I + 2μ·ε (matches theory)
- Clean tensor operations (no manual indexing)

Versus original POC (gpu_assembly_poc.jl):
- OLD: ε = SA[εxx, εyy, γxy] (plain vector)
- NEW: ε = SymmetricTensor{2,2}((εxx, γxy/2, εyy))
- OLD: σ = C * ε (matrix multiply)
- NEW: σ = compute_stress(material, ε) (material API)
- OLD: Manual stress component indexing
- NEW: Tensor operations (Bᵀ·σ via dot product)

Benefits:
- Follows material_modeling.md architecture
- GPU compatible (Tensors.jl works on CUDA)
- Maintainable (material models pluggable)
- Mathematics matches equations

Same test case: 10×10 Quad4, steel, 242 DOFs (468 lines).
2025-11-12 00:28:07 +02:00
Jukka Aho 34027e887f demo: Add initial GPU assembly proof-of-concept
First working GPU assembly implementation (proof-of-concept stage)
demonstrating complete FEM solve staying on GPU for 2D elasticity.

Implementation:
- Element-parallel GPU kernel for Quad4 elements
- 2×2 Gauss quadrature on GPU
- Plain vector approach (before Tensors.jl integration)
- Matrix-free Jacobian-vector product
- Complete Newton-Krylov loop on GPU
- BC enforcement via masking

Test case: 10×10 Quad4 mesh (100 elements, 242 DOFs)
- Material: Steel (E=200 GPa, ν=0.3)
- BC: Fixed left edge, displacement on right edge

Architecture validation:
- GPU assembly matches CPU (error < 1e-15)
- Entire solve stays on GPU (no ping-pong)
- Only transfers: mesh (once) + u0/u_final (boundary)

Note: This is the initial version using plain vectors and manual
indexing. See gpu_assembly_poc_tensors.jl for corrected version
using proper Tensors.jl material API (606 lines).
2025-11-12 00:27:51 +02:00
Jukka Aho 6fd50689b6 demo: Add cantilever physics-based GPU assembly
GPU assembly using physics-aware abstractions (elasticity helper functions)
instead of raw kernel implementation, demonstrating higher-level API.

Architecture difference from cantilever_gmsh_gpu.jl:
- Raw GPU: Direct CUDA kernels with manual indexing
- Physics GPU: Helper functions (compute_strain, compute_stress, etc.)

Physics abstractions:
- compute_jacobian: J = Σ dN ⊗ X (automatic differentiation possible)
- compute_strain: ε = sym(Σ dN ⊗ u) using Tensors.jl
- compute_stress: σ = material(ε) with material API
- compute_residual: r = Σ Bᵀ·σ·w (internal forces)

Benefits:
- More readable (physics equations explicit)
- More maintainable (abstractions hide complexity)
- More extensible (swap materials easily)
- Still GPU-compatible (Tensors.jl works on CUDA)

Trade-offs:
- Slightly higher abstraction overhead
- Depends on Tensors.jl GPU support
- May need careful inlining for performance

Same problem: 10m × 1m × 1m cantilever, Tet4, steel properties
2025-11-12 00:27:26 +02:00
Jukka Aho 0856714ce1 demo: Add cantilever beam GPU assembly with Gmsh
Complete GPU-accelerated FEM solve for 3D cantilever beam using
nodal assembly strategy and matrix-free Newton-Krylov solver.

GPU implementation:
- Gmsh mesh generation (same as CPU version)
- Data transfer to GPU (nodes, connectivity, BC)
- GPU kernels for nodal assembly (element contributions)
- Matrix-free Jacobian-vector product on GPU
- GMRES solver on GPU (Krylov.jl with CuArrays)
- CPU fallback for Anderson acceleration

Problem characteristics:
- Geometry: 10m × 1m × 1m cantilever beam
- Elements: Tet4 from Gmsh
- Material: Steel (E=210 GPa, ν=0.3)
- BC: Fixed left end, tip force on right end

Architecture:
- Single GPU transfer: mesh + BC → GPU at start
- Entire Newton-Krylov loop stays on GPU
- Single result transfer: u_final ← GPU at end
- No ping-pong between CPU and GPU during solve

Demonstrates complete GPU FEM pipeline from meshing to solution
with realistic geometry and material properties.
2025-11-12 00:27:02 +02:00
Jukka Aho cf364576f1 demo: Add cantilever CPU assembly comparison
Compares traditional element assembly vs nodal assembly on CPU for
cantilever beam example, validating assembly equivalence and measuring
performance characteristics.

Comparison:
- Element assembly: Traditional FEM (loop over elements, atomic scatter)
- Nodal assembly: Modern approach (loop over nodes, block operations)

Validation:
- Residual equivalence (element vs nodal assembly)
- Stiffness operator equivalence (matvec comparison)
- Assembly time comparison
- Memory allocation tracking

Problem: Same cantilever beam as cantilever_beam_simple.jl
- Tet4 mesh from Gmsh
- Steel properties
- Fixed left, force on right

Demonstrates CPU assembly strategies before GPU implementation,
establishing baseline for GPU performance comparison.
2025-11-12 00:26:32 +02:00
Jukka Aho 2ae1b686ed demo: Add simple cantilever beam example with Gmsh
Demonstrates modern Physics API for 3D elasticity on realistic geometry
using Gmsh mesh generation and both direct/iterative solvers.

Features:
- Gmsh mesh generation (10m × 1m × 1m cantilever beam)
- Tet4 elements with controlled mesh size (lc=1.5)
- Physics API setup (Elasticity, continuum formulation)
- Steel material properties (E=210 GPa, ν=0.3)
- Boundary conditions: Fixed left end, force on right end

Problem setup:
- Geometry: Cantilever beam (aspect ratio 10:1:1)
- Discretization: Tet4 elements from Gmsh
- Loading: Tip force applied via Neumann BC
- Constraints: Fixed end via Dirichlet BC

Workflow demonstration:
1. Mesh generation with Gmsh API
2. Physics problem creation
3. Solver setup (direct or iterative)
4. Post-processing and visualization

Educational example showing complete FEM workflow from meshing
to solution with modern JuliaFEM API (183 lines).
2025-11-12 00:21:54 +02:00
Jukka Aho e7f0309f73 demo: Add simple assembly strategy comparison
Demonstrates modern Physics API for solving elasticity problems using
CPU backend with element assembly.

Features:
- Simple 2-element beam mesh (Hex8 elements, 12 nodes, 36 DOFs)
- Immutable Element API with field-based material properties
- Physics problem setup (Elasticity, continuum formulation)
- Material properties: Steel (E=210 GPa, ν=0.3)

Demonstrates workflow:
1. Create mesh (nodes dictionary + connectivity tuples)
2. Create Physics problem (Elasticity with continuum formulation)
3. Build elements with immutable API (fields tuple)
4. Add elements to physics

Educational example showing modern API usage for elasticity
problems with clean separation between geometry and physics (131 lines).
2025-11-12 00:21:37 +02:00
Jukka Aho 875073c1c2 docs: Add Tensors.jl integration correction for GPU POC
Documents architectural correction from manual Voigt indexing to proper
Tensors.jl material modeling in GPU assembly proof-of-concept.

Problem identified:
- Initial POC used plain vectors instead of SymmetricTensor
- Hardcoded constitutive matrix instead of material API
- Manual index arithmetic for stress components
- Didn't match established material_modeling.md architecture

Solution implemented:
- SymmetricTensor{2,2} for 2D strain and stress
- Material API: compute_stress(material, ε)
- LinearElastic struct with Lamé parameters
- Clean tensor operations matching theory
- GPU compatible (Tensors.jl works on CUDA)

Key architectural changes:
1. Material model struct (LinearElastic with E, ν)
2. Material API with Hooke's law (σ = λ·tr(ε)·I + 2μ·ε)
3. SymmetricTensor strain computation (εxx, εyy, γxy/2)
4. Stress-to-force conversion (Bᵀ·σ operator)

Reference: demos/gpu_assembly_poc_tensors.jl (264 lines)
2025-11-12 00:21:15 +02:00
Jukka Aho 600a2eeb0a docs: Add GPU assembly proof-of-concept summary
Complete working proof-of-concept for GPU-accelerated finite element
assembly demonstrating entire solve staying on GPU.

Implementation features:
- Element-parallel GPU kernel for 2D linear elasticity
- Quad4 elements with 2×2 Gauss quadrature
- Matrix-free Jacobian-vector product (finite difference on GPU)
- Complete Newton-Krylov loop on GPU (no CPU escapes)
- Boundary condition enforcement

Validation results:
- GPU assembly matches CPU (relative error < 1e-15)
- Entire solve pipeline stays on GPU
- Only transfers: mesh (once), u0 (input), u_final (output)

Test case: 10×10 Quad4 mesh (100 elements, 242 DOFs), steel properties
(E=200 GPa, ν=0.3), fixed left edge, displacement on right edge.

Architecture: u0 → GPU → [Newton loop: residual + Jv + GMRES + update] → u_final

Reference: demos/gpu_assembly_poc.jl (212 lines documentation)
2025-11-12 00:20:49 +02:00
Jukka Aho 19c93b82de docs: Add GPU kernel implementation plan for Newton-Krylov-Anderson
Implementation roadmap for GPU-accelerated nonlinear solver pipeline derived
from CPU reference implementation (newton_krylov_anderson_cpu.jl).

Breakdown of solver pipeline:
- Outer loop: Newton iterations (residual assembly + line search)
- Middle loop: GMRES iterations (matrix-free matvec + Arnoldi)
- Inner operation: Element residual assembly with plasticity

Key GPU kernels identified:
1. Element residual assembly (workhorse kernel, nodal scatter with atomics)
2. Vector operations (standard cuBLAS: axpy, dot, norm)

Four-phase implementation strategy:
1. Single kernel test (residual assembly CPU vs GPU)
2. Matrix-free matvec test (Jacobian-vector product validation)
3. GMRES on GPU (Krylov.jl with CuArrays)
4. Complete pipeline (GPU main loop, CPU Anderson acceleration)

Includes plastic state GPU representation (NTuple vs SymmetricTensor),
kernel launch configuration, and atomic scatter pattern (296 lines).
2025-11-12 00:20:24 +02:00
Jukka Aho 2e48a356a3 bench: Add GPU benchmarks test script
Shell script for quick validation of GPU benchmarks without running
full suites (which can take minutes on large problem sizes).

Features:
- Julia installation check (version validation)
- GPU availability detection (nvidia-smi query)
- CUDA.jl functionality verification
- Quick state management test (10K elements, not 1M)
- Quick matrix-free test (1K DOFs, not 1M)
- Both CPU and GPU paths tested
- Error handling with informative messages

Runs small problem sizes to verify:
- Code compiles and loads correctly
- CUDA kernels launch without errors
- Basic functionality works before long benchmarks
- Development workflow (test before full run)

Executable: chmod +x benchmarks/test_gpu_benchmarks.sh (159 lines)
2025-11-12 00:19:50 +02:00
Jukka Aho 33bf912b99 bench: Add perfect plasticity material performance analysis
Comprehensive benchmarking of J2 plasticity with radial return mapping:

Tests performed:
1. Single evaluation: elastic path (below yield) vs plastic path
2. Zero-allocation verification for both branches
3. Type stability validation
4. State management overhead (fresh vs history)
5. Hardening parameter sensitivity analysis
6. Assembly loop simulation (realistic FEM usage)
7. Comparison to LinearElastic and NeoHookean
8. Strain level scalability (elastic to plastic transition)

Validates:
- Plastic path overhead (radial return vs elastic)
- State handling performance (PlasticityState vs NoState)
- Zero allocations maintained even with mutable state
- Type stability for both converged and trial states

Includes von Mises stress computation, yield surface check, and
algorithmic tangent calculation (320 lines).
2025-11-12 00:19:30 +02:00
Jukka Aho 783c075277 bench: Add Neo-Hookean hyperelastic material analysis
Detailed performance analysis of automatic differentiation overhead in
hyperelastic stress computation for Neo-Hookean material model.

Key analyses:
1. Single stress evaluation timing (typical FEM assembly use case)
2. Allocation verification (zero-allocation requirement)
3. Component breakdown (strain energy vs stress vs tangent)
4. Scaling with problem size (assembly loop performance)

Compares NeoHookean (AD) against LinearElastic (manual derivatives) to
quantify AD overhead in production FEM assembly loops.

Results inform whether AD is suitable for hot paths vs manual derivatives
for performance-critical material models (260 lines).
2025-11-12 00:19:10 +02:00
Jukka Aho d4abf2fd13 bench: Add matrix-free Newton-Krylov GPU benchmark
Comprehensive benchmark comparing three nonlinear solver strategies:
1. Traditional Newton (full Jacobian assembly + direct solve)
2. Matrix-free Newton-Krylov (GMRES, no Jacobian matrix)
3. Matrix-free with Anderson acceleration (accelerated convergence)

Problem: 3D nonlinear elasticity with cubic nonlinearity
- r(u) = K·u + β·(K·u)³ - f
- Jacobian-vector product via finite differences: J·v ≈ [r(u+ε·v) - r(u)]/ε

Key findings validated:
- Matrix-free eliminates Jacobian assembly cost
- Anderson acceleration reduces iteration count
- GPU acceleration for large problems (memory bandwidth bound)
- GMRES with adaptive tolerance (Eisenstat-Walker formula)

Includes both CPU and GPU implementations with performance comparison
showing memory usage, iteration counts, and wall-clock times for systems
ranging from 1K to 1M DOFs (835 lines, full implementation).
2025-11-12 00:18:46 +02:00
Jukka Aho a88167b0cb bench: Add material models benchmark execution results
Complete execution output from material_models_benchmark.jl validation:

Performance results:
- Linear Elastic: 5.1× speedup (Tensors.jl vs Voigt/Dict)
- Neo-Hookean Manual: 2.0× speedup over old approach
- Perfect Plasticity: 21.0× speedup (zero allocations vs Dict)
- Average speedup: 9.4× (validates 5-50× claim range)

Key validation:
- All new implementations: ZERO allocations (confirmed)
- Manual derivatives: 21.1× faster than automatic differentiation
- Type stability: All @code_warntype checks pass (no red flags)
- AbstractMaterialState hierarchy: State handling identical for all materials

Demonstrates Newton iteration state handling for both stateless (LinearElastic,
NoState) and stateful (PerfectPlasticity, PlasticityState) materials.
2025-11-12 00:18:16 +02:00
Jukka Aho 6b2cde6689 bench: Add comprehensive material models performance comparison
Extensive benchmark comparing new Tensors.jl approach vs old Voigt/Dict approach:

Materials tested:
- Linear Elastic (Hookean) - stateless
- Neo-Hookean Hyperelasticity - stateless (AD + manual derivatives)
- Perfect Plasticity (von Mises) - stateful with radial return

Analysis performed:
1. Type stability (@code_warntype)
2. Memory allocations (@allocated)
3. Execution time (BenchmarkTools)
4. LLVM IR inspection (inlining, vectorization)
5. Native assembly analysis

Validates key claims:
- Zero allocations for new approach (stack-only computation)
- 5-50× speedup over Voigt/Dict
- Manual derivatives outperform automatic differentiation
- Proper state handling for Newton iterations

Includes AbstractMaterial/AbstractMaterialState type hierarchy demonstration
showing how assembly code stays identical for stateless and stateful materials.
2025-11-12 00:17:30 +02:00
Jukka Aho 995f01ca9e bench: Add comprehensive linear elastic material analysis
Performs detailed performance analysis of LinearElastic material model:
1. Execution time benchmarking (@btime)
2. Memory allocation tracking (@allocated)
3. Type stability verification (@code_warntype)
4. LLVM IR inspection (inlining, vectorization)
5. Native assembly analysis (SIMD instructions)

Validates implementation quality:
- Zero allocations (stack-only computation)
- Fully inlined (no function calls in LLVM IR)
- SIMD optimized (AVX/AVX2 vector instructions)
- FMA instructions (fused multiply-add for optimal performance)

Calculates throughput (~millions of stress evaluations per second per core)
and compares actual operations against theoretical minimum FLOPs for
Hooke's law: σ = λ·tr(ε)·I + 2μ·ε
2025-11-12 00:17:08 +02:00
Jukka Aho 829109132f bench: Add integration point access pattern comparison
Compares 5 strategies for accessing integration points during assembly:
- OLD: Runtime dispatch + mutable struct with Dict (type-unstable)
- Option A: Compile-time function returning tuples
- Option B: Store in element as NTuple (current approach)
- Option C: Compile-time with Vec{D} from Tensors.jl
- Option D: Pre-computed global constants
- Option E: Function returning pre-computed constant

Validates that compile-time generation (Options C-E) matches the golden
standard architecture from nodal assembly demos. Includes realistic FEM
assembly comparison showing performance difference between old runtime
dispatch and new compile-time approach.

Recommendation: Option C (compile-time with Vec) or D/E (pre-computed)
for zero allocation and full inlining, matching eval_basis! pattern.
2025-11-12 00:16:50 +02:00
Jukka Aho b37e8fc268 bench: Add GPU state management strategy comparison
Compares two state update strategies for GPU optimization:
- Strategy 1: Array of Structs (AoS) - immutable elements with embedded state
- Strategy 2: Structure of Arrays (SoA) - separate geometry and mutable state

Validates that SoA achieves 5-10× better memory bandwidth due to coalesced
access patterns. Benchmarks both CPU and GPU implementations with detailed
performance metrics including bandwidth utilization.

Key findings:
- SoA enables coalesced memory access (consecutive threads → consecutive memory)
- AoS suffers from pointer chasing and non-coalesced access
- SoA has zero allocations (in-place updates vs element reconstruction)
- Tests with 10k, 100k, 1M elements showing scalability
2025-11-12 00:13:30 +02:00
Jukka Aho 76ec3cfcdf bench: Add deformation gradient performance analysis
- Validates zero-allocation claim for compute_deformation_gradient()
- Allocation analysis with @allocated macro
- Performance benchmarking with BenchmarkTools
- LLVM IR analysis for optimization verification
- Tests finite strain formulation F = I + ∇u
- Hex8 element with 10% stretch in x-direction
- Jacobian computation J = ∑ X_i ⊗ dN_i/dξ
- Measures median time in nanoseconds/microseconds
- Confirms type stability and inlineability
- 240 lines analyzing deformation gradient computation performance
2025-11-12 00:10:49 +02:00
Jukka Aho 7bba4e7174 bench: Add Tet10 basis function access benchmark
- Comprehensive benchmark for 10-node quadratic tetrahedron (Tet10)
- Tests 3 strategies for accessing individual basis functions/derivatives
- Strategy 1: Tuple indexing with runtime index (N_all[i])
- Strategy 2: Val dispatch with compile-time index (::Val{I})
- Strategy 3: @generated function computing only requested function
- Tet10 basis functions: 4 vertex nodes + 6 edge midpoint nodes
- Derivatives: ∇N_i = (∂N_i/∂u, ∂N_i/∂v, ∂N_i/∂w) as Vec{3}
- Use cases: stiffness assembly (derivatives), mass assembly (functions), nodal assembly (single access)
- Node numbering: vertices 1-4, edges 5-10 (5: 1-2, 6: 2-3, 7: 3-1, 8: 1-4, 9: 2-4, 10: 3-4)
- Focus: zero allocation, type stability, inlineability for hot paths
- 504 lines benchmarking realistic 3D element access patterns
2025-11-12 00:10:31 +02:00
Jukka Aho 84708cce2e bench: Add basis function access pattern benchmark for Tet10
- Tests 5 strategies for accessing basis functions and derivatives
- Strategy 1: Tuple return + getindex (natural Julia)
- Strategy 2: @generated function (compile-time specialization)
- Strategy 3: Val dispatch (type-stable index)
- Strategy 4: BasisFunctions struct with getindex (most Julian)
- Strategy 5: Separate functions per basis (extreme specialization)
- Use case: Tet10 quadratic tetrahedron (10 nodes, workhorse for 3D FEM)
- Benchmarks both "access all" (element assembly) and "access single" (nodal assembly)
- Tests derivatives as Vec{3} tuples for gradient computation
- Focus: zero allocation, type stability, inlineability
- 412 lines evaluating access pattern performance for GPU-friendly design
2025-11-12 00:09:42 +02:00
Jukka Aho caf60e4356 docs: Add GPU benchmark suite documentation
- Comprehensive guide for GPU-friendly FEM architecture benchmarks
- State management strategy comparison: AoS vs SoA (coalesced memory access)
- Matrix-free Newton-Krylov benchmarks with Anderson acceleration
- Performance metrics: memory bandwidth (GB/s), execution time, iterations
- Expected results: Strategy 2 (SoA) 10× faster on GPU, 500-900 GB/s bandwidth
- Matrix-free + Anderson: 6-10× speedup, 2.5× fewer iterations
- Hardware requirements and tested platforms (RTX 4090, 3090, 3080)
- Troubleshooting guide: CUDA setup, OOM errors, slow CPU benchmarks
- Performance expectation tables for 1M elements and 100K DOFs
- Validation: correctness checks and convergence verification
- 244 lines documenting GPU optimization strategies and benchmarking methodology
2025-11-12 00:09:18 +02:00
Jukka Aho 7919a1fffa test: Add perfect plasticity material model validation
- Tests PerfectPlasticity with J2 von Mises yield criterion and linear hardening
- PlasticityState tracking: ε_p (plastic strain), α (backstress), κ (plastic work)
- Elastic loading: small strain below yield → no plastic strain
- Plastic loading: strain beyond yield → radial return mapping
- Von Mises yield surface: f = √(3/2·s:s) - σ_y ≤ 0
- Hardening behavior: H > 0 (kinematic hardening) vs H = 0 (perfect plasticity)
- Incremental loading: monotonic stress and plastic strain accumulation
- Bauschinger effect: cyclic loading with backstress evolution
- Pure shear: τ_yield = σ_y/√3 validation
- Consistency check: yield criterion satisfaction at all strain levels
- Tests both simplified interface and full state-passing API
- Zero allocation and type stability verification
- 293 lines validating elastoplastic material behavior with Tensors.jl
2025-11-12 00:08:30 +02:00
Jukka Aho 3b13a77981 test: Add nodal vs element assembly comparison validation
- Implements BOTH assembly methods for direct comparison on same problem
- Traditional element assembly: builds 12×12 K_e matrices, scatters to global K
- Nodal assembly: computes 3×3 K_ij blocks directly, accumulates per node
- Test problem: linear elasticity on simple Tet4 mesh
- TestLinearElastic material with Lamé parameters (λ, μ from E, ν)
- B-matrix computation: strain-displacement operator (6×3 per node, Voigt notation)
- Element stiffness: K_e = ∫ B^T C B dV with Gauss integration
- Nodal contribution: spider pattern with 3×3 blocks for coupled nodes
- Matrix-vector product comparison: K*v computed both ways
- Validates numerical equivalence: ‖K_element - K_nodal‖ < tol
- Performance characteristics: element (matrix scatter) vs nodal (direct blocks)
- Architectural differences demonstration: gather-scatter vs direct accumulation
- 542 lines validating nodal assembly correctness and comparing approaches
2025-11-12 00:08:06 +02:00
Jukka Aho 1f07f3f7aa test: Add comprehensive deformation gradient computation validation
- Tests compute_deformation_gradient() for both FiniteStrain and SmallStrain formulations
- Identity case: u=0 → F=I, det(F)=1
- Pure translation: constant u → ∇u=0 → F=I (rigid body motion)
- Pure stretch: uniaxial extension (10%, 20%) → diagonal F
- Simple shear: u_x = γ·y → off-diagonal F components
- Validates F = I + ∇u (finite strain) vs F = I (small strain approximation)
- Physical constraint: det(F) > 0 (orientation preservation)
- Incompressibility check: det(F) ≈ 1 for volume-preserving deformation
- Symmetry verification for Right Cauchy-Green tensor C = F^T·F
- Type stability and zero allocation checks
- Integration with new API: get_basis_derivatives(Hexahedron(), Lagrange{}, ξ)
- Tests Hex8 elements with various deformation patterns
- 393 lines validating fundamental kinematics with Tensors.jl
2025-11-12 00:07:40 +02:00
Jukka Aho 7b875dd117 test: Add nodal assembly data structures validation
- Tests NodeToElementsMap inverse connectivity (node → elements touching it)
- Validates "spider" pattern: set of nodes coupled to given node via shared elements
- Simple Tet4 mesh: 2 elements sharing face, tests node-element relationships
- Spider coupling patterns: corner nodes (1 element), shared nodes (2 elements)
- NodalStiffnessContribution storage: K_blocks (3×3 tensors), f_int, f_ext (Vec{3})
- Matrix-vector product: w_i = ∑_j K_ij ⊡ u_j (nodal assembly operation)
- Spider efficiency check: 2×2×2 hex mesh shows sparse coupling
  - Corner node: 8 couplings
  - Center node: 27 couplings (max for structured mesh)
  - Key insight: only compute non-zero blocks (not full 81×81 matrix)
- Diagnostic output showing spider structure and coupling patterns
- 208 lines validating nodal assembly infrastructure with Tensors.jl
2025-11-12 00:07:01 +02:00
Jukka Aho 5ec6dda0dd test: Add new API element construction validation
- Tests Element construction with explicit Topology + Basis separation
- Validates 2D elements: Triangle (P1=3 nodes, P2=6 nodes), Quadrilateral (Q1=4, Q2=9)
- Validates 3D elements: Tetrahedron (P1=4, P2=10), Hexahedron (Q1=8, Q2=27)
- Backward compatibility: Tet4, Tri3, Quad4, Hex8 aliases verified
- Topology properties independent of basis: dim(), reference_coordinates(), edges(), faces()
- Type-stable fields using NamedTuple (E, ν, thickness)
- Integration points as element property with integration_points(scheme, topology)
- Demonstrates separation of concerns: Geometry ≠ Interpolation ≠ Integration ≠ Fields
- Compile-time known sizes: NTuple connectivity, type parameters encode dimensions
- Zero allocation verification for field access and element queries
- 344 lines validating new immutable Element architecture with clear responsibilities
2025-11-12 00:06:34 +02:00
Jukka Aho 49bb196e68 test: Add new API basis function evaluation validation
- Demonstrates correct new API usage: Topology + Basis + IntegrationPoint separation
- Mock BasisValues struct with shape functions N and derivatives dN_dξ (SVector)
- Tests linear tetrahedron (P1, 4 nodes) evaluation at center and corner nodes
- Tests linear triangle (P1, 3 nodes) evaluation and partition of unity
- Validates constant derivatives for linear elements
- Integration with Gauss quadrature: evaluate_basis at all integration points
- Complete FEM workflow demonstration: Topology → Integration → Basis → Assembly
- Multiple element types from same topology (P1 vs P2 with same integration points)
- Type stability and zero allocation verification with StaticArrays
- 291 lines demonstrating separation of concerns: Topology ≠ Basis ≠ Integration
2025-11-12 00:05:56 +02:00
Jukka Aho 1b8da3465c test: Add comprehensive neo-Hookean hyperelastic material validation
- Tests NeoHookean construction with both Lamé parameters and engineering constants
- Strain energy computation: reference state (ψ=0), uniaxial extension, invalid deformations
- Stress computation: small deformation, large deformation (50% extension), pure shear
- Second Piola-Kirchhoff stress: S = 2·∂ψ/∂C computed via automatic differentiation
- Tangent modulus validation: 4th-order symmetric tensor, finite difference consistency
- Verifies stress-energy relationship: S = 2·gradient(strain_energy, C)
- Small strain limit: Neo-Hookean → linear elasticity as ε → 0
- Incompressibility check for nearly incompressible materials (ν → 0.5)
- Automatic differentiation accuracy verification
- Zero allocation and type stability checks
- 295 lines validating finite deformation hyperelasticity with Tensors.jl
2025-11-12 00:01:18 +02:00
Jukka Aho e9ead51f24 test: Add comprehensive linear elastic material validation
- Tests LinearElastic material construction with parameter validation
- Validates Lamé parameter computation (λ and μ from E and ν)
- Stress computation tests: uniaxial extension, pure shear, hydrostatic pressure, general strain
- Verifies Hooke's law: σ = λ·tr(ε)·I + 2μ·ε
- Tangent modulus validation: 𝔻 = λ·I⊗I + 2μ·𝕀ˢʸᵐ (4th-order tensor)
- Double contraction consistency: σ = 𝔻 ⊡ ε
- Symmetry and isotropy property verification
- Tests both full and simplified compute_stress() interfaces
- Zero allocation and type stability checks
- 279 lines validating fundamental elasticity operations with Tensors.jl
2025-11-12 00:00:59 +02:00
Jukka Aho 1952f9c6cb test: Add comprehensive Jacobian computation validation
- Tests compute_jacobian() for 2D triangles and 3D tetrahedra
- Validates identity, scaling, and rotation transformations
- Tests physical_derivatives() conversion from reference to physical coordinates
- Verifies constant strain condition (∑ dNᵢ/dx = 0)
- Element quality checks via determinant (positive = proper orientation)
- Detects degenerate elements (det ≈ 0)
- Type stability and zero allocation verification
- Manual calculation consistency checks for known Jacobians
- Tests both tuple and vector interfaces
- 261 lines covering fundamental isoparametric mapping operations
2025-11-12 00:00:41 +02:00
Jukka Aho b6b5ea4b1a test: Add zero-allocation integration points API validation
- Tests get_gauss_points!() for 5 topology types (Segment, Triangle, Tetrahedron, Quadrilateral, Hexahedron)
- Validates zero allocation property for all quadrature orders
- Verifies return type: NTuple of (Float64, Vec{D}) pairs
- Tests weight summation equals reference element area/volume
- Demonstrates usage in assembly loop with zero allocations
- Includes performance comparison benchmarking
- 151 lines of comprehensive integration points validation
2025-11-11 23:59:32 +02:00
Jukka Aho d47eed8ed3 test: Add finite strain plasticity material model validation
Unit tests for FiniteStrainPlasticity with multiplicative decomposition.

Test coverage:
- Material construction with validation (E, ν, σ_y, H parameters)
- State initialization (F_p, α_bar, κ)
- Small strain limit verification
- Identity and pure rotation deformation (frame indifference)
- Uniaxial extension (elastic and plastic regimes)
- Simple shear deformation
- Incremental loading with state persistence
- Plastic incompressibility constraint (det(F_p) ≈ 1)
- Kinematic hardening behavior (backstress evolution)
- State persistence across load steps
- Type stability verification
2025-11-11 23:54:22 +02:00
Jukka Aho c9f951ef16 test: Add traditional element assembly structures validation
Tests for element-by-element assembly approach with sparse matrix operations.

Test coverage:
- ElementAssemblyData construction and initialization
- DOF indexing for sequential and non-sequential nodes
- Element contribution structures (K_local, f_int, f_ext)
- Scatter operation to global arrays
- Overlapping element accumulation
- Residual computation (f_ext - f_int)
- Matrix-vector product
- Dirichlet BC application (penalty method)
- Symmetry preservation
- Reset functionality
- Assembly statistics printing
2025-11-11 23:53:02 +02:00
Jukka Aho 0ccc29976c test: Add single-element patch test for elasticity assembly
Validates core assembly implementation by solving single Tet10 element
under uniaxial tension and comparing to analytical solution.

Test coverage:
- Linear elastic material model validation
- Strain computation from gradients (uniaxial extension)
- Assembly helpers zero allocation verification
- Type stability verification
- Stiffness matrix properties (symmetry, positive definiteness)
- Internal forces accumulation

Validates complete assembly infrastructure works correctly.
2025-11-11 23:52:32 +02:00
Jukka Aho 280f42bbf8 test: Add standalone elasticity assembly helpers validation
Tests core assembly helper functions (strain computation, stiffness
accumulation) without requiring full Element/BasisInfo infrastructure.
Uses Tensors.jl types directly for validation.

Test coverage:
- Material model integration (LinearElastic)
- Strain computation from shape function gradients
- Stiffness matrix accumulation
- Zero allocation verification
- Type stability verification
- Stiffness matrix properties (symmetry, eigenvalues)
2025-11-11 23:52:05 +02:00
Jukka Aho 650e442a37 docs(examples): Fix formatting in gmsh_heat_equation QUICK_START
- Add blank line after 'This example shows:' for markdown lint compliance
- Minor formatting fix only, no content changes
2025-11-10 22:26:55 +02:00
Jukka Aho 269fa9a4ad feat(basis): Add dual-API basis function support (modern + legacy)
- New API: get_basis_functions() returns tuple of functions
- New API: get_basis_derivatives() returns tuple of gradient functions
- basis_api.jl: 210 lines implementing modern functional API
- Re-generated lagrange_generated.jl with 242 new lines
- abstract.jl: Add nnodes() method for Lagrange type
- Backward compatible: old eval_basis! API unchanged
- See ADR-003 for design rationale
2025-11-10 22:26:23 +02:00
Jukka Aho 30ca3de56a feat(elements): Add immutable update() function for elements
- Implement update() that returns new element (immutable pattern)
- Supports keyword arguments for ergonomic field updates
- Preserves backward compatibility with update!() (legacy)
- Dual-API approach: modern immutable + legacy mutable both supported
- 82 lines including documentation and examples
- See docs/book/fundamentals_element_creation.md for usage guide
2025-11-10 22:25:59 +02:00
Jukka Aho 7ffecf73e7 refactor(core): Update JuliaFEM.jl exports for new APIs
- Add new basis API exports: get_basis_functions, get_basis_derivatives
- Export both update() (immutable) and update!() (legacy)
- Re-enable assemble! and postprocess! exports
- Document new basis API with ADR-003 reference
- Include basis_api.jl for dual-API support (modern + legacy)
2025-11-10 22:25:41 +02:00
Jukka Aho 5823a8ec97 demo: Add interactive cantilever beam demo
- Complete working demo of GPU elasticity solver
- Includes mesh generation with Gmsh.jl
- Step-by-step workflow from mesh to solution
- Visualization code for results
- Material: Steel (E=200 GPa, ν=0.3)
- Load: 10 MPa pressure on free end
- Output: Displacement field, validation results
- 145 lines with detailed comments
2025-11-10 22:25:15 +02:00
Jukka Aho 2b1fa89684 test(gpu): Add GPU elasticity solver test with cantilever beam
- Complete test suite for ElasticityPhysics solver
- Cantilever beam mesh: 190 nodes, 434 Tet4 elements
- Gmsh-generated mesh file (cantilever_beam.msh)
- Material: Steel (E=200 GPa, ν=0.3)
- Boundary conditions: Fixed end, pressure load on free end
- Validates convergence and displacement field
- Test passes: 430 CG iterations, max displacement 4.1 cm
2025-11-10 22:24:52 +02:00