|
hp-FEM
Adaptive hp-FEM suite for nano-optics
|
This file is the operating manual for Claude Code (and humans) working in this repository. Read it fully before touching code. When in doubt, follow this file, then the ADRs in docs/adr/, then docs/roadmap.md.
hp-FEM is an open-source finite-element suite for nano-optics / computational electromagnetics: time-harmonic Maxwell solvers with adaptive hp-refinement, high-order Nédélec (edge) elements, rigorous a-posteriori error estimation and perfectly matched layers (PML). The scientific target is the feature set of commercial tools such as JCMsuite, applied to:
Core library: C++20. User API: Python (pybind11). Build: CMake ≥ 3.25 + Ninja. See docs/adr/0001-language-and-stack.md for the rationale.
std::complex<double>. Real-valued shortcuts are an optimization that must be opt-in and tested, never the default.Rule: a header in include/hpfem/<module>/ has its implementation in src/<module>/ and its tests in tests/unit/<module>/. Keep modules dependency- ordered: core ← mesh ← fespace ← assembly ← {materials, pml} ← solvers ← adaptivity ← physics ← io ← python. Never introduce a cyclic include.
CMake options: HPFEM_BUILD_TESTS, HPFEM_BUILD_EXAMPLES, HPFEM_BUILD_PYTHON, HPFEM_BUILD_BENCHMARKS, HPFEM_BUILD_DOCS, HPFEM_ENABLE_MPI (off), HPFEM_ENABLE_MUMPS (preset mumps), HPFEM_ENABLE_OPENMP (on by default).
Third-party libraries are pulled via FetchContent in cmake/Dependencies.cmake (Eigen, Catch2, fmt, spdlog, nlohmann_json, pybind11). Heavy optional deps (MUMPS, PETSc/SLEPc, Gmsh SDK) are found with find_package and guarded by options.
The maintainer develops natively on Windows. Toolchain: MSYS2 GCC (UCRT64), CMake and Ninja (installed via winget), Git for Windows. Not MSVC.
C:\msys64\ucrt64\bin is on PATH (g++ --version must report the MSYS2 GCC). Do not build from a Visual Studio Developer / Cross Tools Command Prompt — CMake may then pick cl.exe.build/<preset> and reconfigure with CC=gcc CXX=g++ set in the environment../scripts/setup-dev.sh is Ubuntu-only. On Windows, install extra tools from the MSYS2 UCRT64 shell, e.g. pacman -S mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-gdb mingw-w64-ucrt-x86_64-clang-tools-extra.Build and test exactly as above; the presets already use Ninja:
Without presets (equivalent quick build):
asan test preset runs the unit tests only (label unit): the convergence tests take hours under sanitizers at -O0 and exercise no code the unit tests do not; they run in the release configurations.asan preset does not work with MinGW GCC (no AddressSanitizer on Windows/MinGW). Sanitizer runs happen in CI (Ubuntu) or in the devcontainer/WSL.fast preset uses -march=native; binaries are not portable to other CPUs.HPFEM_ENABLE_MUMPS, preset mumps): install pacman -S mingw-w64-ucrt-x86_64-mumps in the UCRT64 shell; the test targets get C:\msys64\ucrt64\bin (the DLLs) prepended to PATH automatically, programs started by hand need it on PATH. On Ubuntu: libmumps-seq-dev libmumps-headers-dev.HPFEM_STATIC_RUNTIME, default ON): Git for Windows ships an older libstdc++-6.dll in C:\Program Files\Git\mingw64\bin, which Git Bash (and tools started from it) puts before C:\msys64\ucrt64\bin on PATH. A dynamically linked test exe then fails with exit code 0xc0000139 / "Der Prozedureinsprungpunkt … wurde nicht gefunden" although the build succeeded. With the static runtime the binaries import only Windows system DLLs. If you switch the option off, run tests from PowerShell or the MSYS2 UCRT64 shell, or prepend /c/msys64/ucrt64/bin to PATH in Git Bash.std::filesystem for paths, and keep line endings as configured in .editorconfig.brew install cmake ninja libomp; Apple Clang from the Xcode command line tools.cmake --preset release -DOpenMP_ROOT=$(brew --prefix libomp) (without it the assembly runs serially). Then build and test as above.hpfem::cyl_bessel_j etc. from core/special_functions.hpp, never std::cyl_bessel_j directly, and include <numbers> where std::numbers is used (libc++ does not include it transitively).-j 4.hpfem::, submodules hpfem::mesh, hpfem::fespace, …snake_case for functions/variables/files, PascalCase for types, kConstant for compile-time constants, member_ trailing underscore for private members. Template parameters PascalCase. Dimension template parameter is Dim.Real = double, Complex = std::complex<double>, Index = std::int64_t, LocalIndex = std::int32_t — all in include/hpfem/core/types.hpp. Use them. Dense linear algebra: Eigen. Sparse: Eigen::SparseMatrix<Complex, RowMajor> wrapped behind hpfem::SparseMatrix so backends can be swapped.std::unique_ptr for polymorphic ownership; std::shared_ptr only when shared ownership is semantically required (meshes shared by several spaces). Never raw new/delete.hpfem::Error (or subclasses) with a message that names the offending entity. Use HPFEM_ASSERT(cond, msg) for invariants (active in Debug and Release-with-asserts). Never assert() directly.spdlog via hpfem::log(); levels: trace (per-element), debug (per-refinement-step), info (per-solve), warn, error.#pragma once, include-what-you-use, no using namespace in headers. Doxygen /// comments on every public symbol: what it does, units, preconditions, complexity if non-obvious, and a @f$ ... @f$ formula where the math matters..clang-format (LLVM-based, 100 cols). CI fails on unformatted code.[[nodiscard]].std::endl, no printf debugging left behind.exp(-iωt)**. A lossy medium therefore has Im(ε) > 0. A PML stretch is x̃ = x + (i/ω) ∫σ(s) ds. State this convention in every file where a sign would otherwise be ambiguous.nm, µm, eV, THz and converts at the boundary. Vacuum constants live in core/constants.hpp: c0, eps0, mu0, Z0.curl(μ⁻¹ curl E) − ω² ε E = iω J. The magnetic field is post-processed. (Exception: a dual H-formulation may be added later for error-bound purposes.)ε(ω) is a complex tensor (3×3 diagonal or full) per material; anisotropy and dispersion models (Drude, Lorentz, tabulated n,k) live in materials/.E ∈ H(curl) such that for all v ∈ H(curl) (μ⁻¹ curl E, curl v) − ω²(ε E, v) + ⟨BC terms⟩ = (iω J, v).(0,0),(1,0),(0,1) and unit tetrahedron (0,0,0),(1,0,0),(0,1,0),(0,0,1); local edge/face numbering is **fixed in mesh/simplex_topology.hpp (SimplexTopology<Dim>, re-used by fespace/reference_element.hpp) and documented in docs/theory/nedelec.md** — never redefine it elsewhere. Global entity numbering and orientation flags: docs/theory/mesh.md.E(x+a) = E(x)·exp(ik·a) via constrained DoFs), transparent (PML), and impedance/Robin as first-order absorbing fallback.η_K² = h_K² ‖R_K‖² + h_K ‖J_F‖² with the curl-jump and normal-flux-jump face residuals; marking by Dörfler (bulk) criterion; hp-decision via smoothness indicator (Legendre-coefficient decay) — see docs/theory/hp-adaptivity.md.main should stay buildable. Direct commits and pushes to main are allowed (single-maintainer project). Before pushing to main, build and run the tests locally (cmake --build --preset release && ctest --preset release). For larger or riskier work, use feat/<topic>, fix/<topic>, docs/<topic> branches with a PR so CI runs before merging.feat(fespace): add order-2 Nédélec basis on tetrahedra, test(mesh): verify edge orientation consistency, docs(adr): ….main is protected: the CI jobs are required checks (not strict, so a PR need not be rebased before the merge; admins may still push directly). PRs are merged server-side by GitHub auto-merge (enable it on the PR, merge commit); the workflow rerun-cancelled.yml re-runs jobs that the runner queue cancelled, so a PR merges on its own once its checks are green, without a local process polling for it.tests/unit/docs/docs/roadmap.md checkbox ticked, CHANGELOG.md entry under Unreleaseddocs/adr/docs/adr/NNNN-title.md, template in docs/adr/README.md). Read existing ADRs before proposing a change; supersede, don't silently diverge.| Layer | Location | Runs in CI | Examples |
|---|---|---|---|
| unit | tests/unit/ | always | reference-element shape functions, DoF numbering, quadrature exactness, mesh topology |
| convergence | tests/convergence/ | always (≤ 10 min total) | h- and p-convergence rates vs. analytic solutions |
| regression | tests/regression/ | always | golden JSON results of example pipelines (tolerance-based) |
| benchmarks | benchmarks/ | manual | assembly throughput, solver scaling |
Analytic benchmarks that must exist and stay green (add as milestones land):
p+1 in L2.π²(m²+n²+l²), zero spurious modes (count eigenvalues near 0 → must equal 0 after gauge).#DoF^(1/3) (2D) must be visible in the convergence plot.Convergence tests print a table (DoF, error, rate) and assert on the rate with a tolerance, never on absolute magic numbers.
docs/ is an MkDocs-Material site (mkdocs.yml at root); math via MathJax.docs/theory/ is the single source of truth for formulas and conventions. Code comments reference these pages instead of re-deriving.Doxyfile), published under docs/api/ by CI.examples/ has a README with: physics, expected result, runtime.docs/roadmap.md current — it is the project's task list..env files. Never print the GitHub token.build/, *.msh > 1 MB, *.vtu, site/). Large test meshes go through tests/data/ with a generation script, not binaries.cmake/Dependencies.cmake, the README dependency table and an ADR note if the dependency is load-bearing.main with a failing local build or failing tests.git pull, read docs/roadmap.md, pick the lowest unchecked item of the current milestone (or the item you were asked to do).docs/theory/*.md and the headers of the modules you touch../scripts/format.sh && cmake --build --preset release && ctest --preset release.Milestones M0 (scaffold), M1 (mesh infrastructure) and M2 (scalar FEM) are complete: build system, CI, docs; mesh::Mesh<Dim> with oriented entities, connectivity, tags, Gmsh input, generators, affine and quadratic geometry, red refinement, VTK export; reference element, Gauss–Jacobi quadrature, hierarchical H1 basis with DofMap, sparse assembly, Dirichlet elimination, SparseLU solver and the Poisson convergence test. M3 (Nédélec elements and Maxwell eigenproblems) is complete as well: hierarchical Nédélec basis with NedelecDofMap, curl–curl forms with complex tensors, PEC/PMC, discrete gradients and the gauged shift-invert eigensolver (Spectra), the PEC cavity convergence test, point location with field evaluation at arbitrary points, and VTK export of fields (cell averages and subdivision). M4 (time-harmonic scattering and waveguides) is complete: physics::Scattering (total / scattered field, plane-wave and dipole sources, materials by tag), PML as stretched material tensors, Bloch-periodic constraints, curved elements (second-order Gmsh input, disc / ball generators), post-processing (fluxes, cross-sections, far field, diffraction orders), physics::PropagatingMode, convergence tests #3–#6 and the four examples. M5 (adaptivity) is complete: residual and dual-weighted (goal-oriented) estimators, Dörfler marking, local h-refinement with hanging nodes (mesh::AdaptiveMesh, assembly::hanging_constraints), p-refinement, hp decision by error prediction (and coefficient decay), solution transfer, convergence test #7 (L-shape and plasmonic wedge, exponential in $N^{1/3}$) and the plasmonic_dimer example. M6 (solvers and performance) is complete apart from the optional MPI item: MUMPS backend behind solvers::LinearSolver (ADR-0007), static condensation, OpenMP parallel assembly and estimation, parameter sweeps (physics::ScatteringOperator, solvers::ReducedBasis) and the benchmark record in benchmarks/results/. M7 (Python API and usability) is complete: pybind11 bindings of the whole pipeline (python/bindings/, <Name>2D / <Name>3D classes, NumPy / SciPy at the boundary), hpfem.units, the hpfem.materials library (refractiveindex.info data with sources), hpfem.project files with the hpfem command line, hpfem.interop (meshio, pyvista, matplotlib) and the example notebooks; docs/python.md is the user guide. M8 (application examples) is complete: Python drivers in examples/ for the metasurface unit cell, the VCSEL cavity (with the new complex eigensolver solvers::complex_eigenpairs_near and physics::Resonance for quasi-normal modes), the quantum-dot Purcell factor (physics::gaussian_current), the 3D EUV mask and the ring resonator, each with a README and a regression test in python/tests/test_examples.py. M9 (multiphysics) is complete: physics::Thermal (heat conduction from the absorbed optical power on the same mesh), physics::ThermoOptical (temperature-dependent permittivity feedback loop with per-cell MaterialMap overrides), hpfem.pv (carrier generation profiles for device solvers) and the solar_cell_texture example; docs/theory/multiphysics.md. Done from the backlog as well: the dual H-formulation with guaranteed (Prager–Synge) error bounds (adaptivity::dual_solution, hypercircle_estimate), the Floquet–Bloch band-structure solver (physics::BandStructure), the time-domain solver (physics::TimeDomain, Newmark-β) and the cuDSS GPU direct solver (ADR-0008; GPU assembly deferred). M10 (validation against the literature) is complete: rib waveguide (Vassallo 1997), metallic lamellar grating (Granet & Guizal 1996), Mie sphere (Bohren & Huffman, with physics::mie_sphere and mesh::box_with_ball) and the slit–groove problem in silver (Besbes et al. 2007 / Burger et al. 2013) on the layered background of the scattered-field formulation (ADR-0009, physics::LayerStack); the gold-dimer benchmark (Hoffmann et al. 2009) is computed under a documented permittivity assumption because the source does not state its ε (examples/gold_dimer, docs/validation.md G). Results, deviations and the honest assessment of each are in docs/validation.md, the long local runs (ctest label validation-long) in benchmarks/results/. M11 (axisymmetric 2.5D solver, ADR-0010), M13 (conical incidence and the E_z polarisation, physics::ConicalScattering) and M14 (accuracy infrastructure for oblique incidence and gratings) are complete. M15 (features requested by the GUI work) is complete: hp-adaptivity for the conical solver with residual and goal-oriented estimators and the non-matching Bloch coupling (F1, F16), hpfem.grating.solve / validate with the unit-cell mesher, diagnostics, dispersive materials, flux balance and the scalar E_z path (F2, F6, F7, F13), the job runner python -m hpfem.run with progress, cancellation, timing and estimate_memory (F5, F9), the conical post-processing, resonances and bands (F10, F11, F14), field sampling, exact absorption, H field and sweep acceleration (F3, F4, F8, F12, gpu agent) and the wheels workflow with hpfem-gui (F15). M12 is complete except the full ring in 3D: material and shape sensitivities by the adjoint solve (ADR-0011), the 3D directional coupler with modal ports validated against coupled-mode theory on the cuDSS backend (docs/validation.md F), and the 3D add-drop ring as a driver (examples/ring_resonator_3d, half model with WaveguidePort::pmc_tags). M16 (optimisation, calibration, UQ, hpfem.opt) is complete, with the validation studies of S8 in docs/validation.md H–L (the study view S9b is in GUI-hpFEM). M17 (dipole emitters in periodic structures, ADR-0013) is complete: phased array, reciprocity, the array scanning grating.dipole_emission with the guided and surface-plasmon poles (validated against the layered Sommerfeld integral, the plasmonic film in a server run) and the job-runner task. M18 (layered background for the axisymmetric solver, ADR-0014) is complete. M19 (optically anisotropic materials, ADR-0015) is complete except one validation: ε tensors in materials::Material, the volume, conical and axisymmetric solvers, physics::AnisotropicStack (Berreman 4×4), mode-resolved orders in crystal half-spaces with the modal transparent boundary, grating.jones (Jones / Mueller), dipole emitters above crystals and the GUI material editor; the guided-mode poles in the array scan of crystal structures (S7e-2b) are implemented but await the long validation run (benchmarks/m19_crystal_guided_scan.py, server). M20 (linear elasticity with eigenstrain, ADR-0016, issue #213) is complete (the optional real-valued solver path S5c moved to the backlog): physics::Elasticity<Dim> on the vector H1 space (plane strain, 3D, bodies of revolution), shrinkage / thermal / grid eigenstrains, free bodies, output and the mesh velocity for the optics (shape_derivative), the residual estimator in the energy norm with hp-adaptivity (Elasticity::estimate, tests/convergence/elasticity_hp_corner.cpp) and the example examples/printed_block_shrinkage; theory in docs/theory/elasticity.md. Open: the items above, the full ring resonator in 3D (backlog, beyond the GPU memory at useful accuracy) and the optional MPI item. See docs/roadmap.md.
Several Claude Code sessions may work on this repository at the same time on the maintainer's machine. They coordinate as follows.
Separate working trees. Every agent works in its own git worktree; never two sessions in the same directory, and never touch another agent's worktree or branch. The main worktree (hp-FEM/) belongs to the development agent (dev); additional agents live in sibling directories (hp-FEM-<name>/) on their own branch and get their changes into main only through a PR.
Message board. The shared board is ../hp-fem-agents/BOARD.md, relative to the root of every worktree (all worktrees are siblings, so it is the same file for all). It is not part of the repository. Create the directory and file if they are missing.
-<from>/<to>are agent names (dev,housekeeping, …) orall. -TYPEis one ofSTART,CLAIM,RELEASE,INFO,ASK,ANSWER,DONE`.When to read the board (the last ~30 lines are enough): at session start, before each new task step, before every commit, push, PR merge or rebase, and before editing a shared file. Answer every ASK addressed to you with an ANSWER before continuing.
Shared files. CLAUDE.md, docs/roadmap.md, CHANGELOG.md, README.md, mkdocs.yml, pyproject.toml, the top-level CMakeLists.txt, CMakePresets.json and .github/ are edited by one agent at a time: post CLAIM <file> first, check that no open claim by someone else exists, and post RELEASE <file> once the change is in main. If a file is claimed by another agent, wait or ask (ASK) — do not edit it.
Moving main. After pushing to or merging into main, post INFO main is now <sha>: <one-line summary>. Agents with a branch rebase onto it before their next push.
Questions for the maintainer go to the maintainer in your own session, not on the board. Destructive or irreversible repository operations (deleting branches or tags, force-pushes, changing repository settings) need the maintainer's explicit OK.