diff --git a/Analysis/TPZAnalysis.h b/Analysis/TPZAnalysis.h index 84ff49cd3..fed842e5b 100644 --- a/Analysis/TPZAnalysis.h +++ b/Analysis/TPZAnalysis.h @@ -115,7 +115,13 @@ class TPZAnalysis : public TPZSavable { TPZAnalysis(TPZCompMesh *mesh, const RenumType& renumtype = RenumType::EDefault, std::ostream &out = std::cout); /** @brief Create an TPZAnalysis object from one mesh auto pointer object */ TPZAnalysis(TPZAutoPointer mesh, const RenumType& renumtype = RenumType::EDefault, std::ostream &out = std::cout); - + + /** @brief Copying is disabled: TPZAnalysis owns fSolver and deletes it in + * its destructor. Copying would make two objects delete the same pointer, + * causing a crash. */ + TPZAnalysis(const TPZAnalysis &) = delete; + TPZAnalysis &operator=(const TPZAnalysis &) = delete; + void CreateRenumberObject(const RenumType& renumtype); /** @} */ diff --git a/Material/Elasticity/TPZMixedElasticityND.cpp b/Material/Elasticity/TPZMixedElasticityND.cpp index bebee2b9c..888c49018 100644 --- a/Material/Elasticity/TPZMixedElasticityND.cpp +++ b/Material/Elasticity/TPZMixedElasticityND.cpp @@ -1144,7 +1144,7 @@ void TPZMixedElasticityND::Solution(const TPZVec> &data, STATE TPZMixedElasticityND::Inner(TPZFMatrix &S, TPZFMatrix &T) { //inner product of two tensors -#ifdef DEBUG +#ifdef PZDEBUG if (S.Rows() != S.Cols() || T.Cols() != T.Rows() || S.Rows() != T.Rows()) { DebugStop(); } @@ -1165,7 +1165,7 @@ STATE TPZMixedElasticityND::Inner(TPZFMatrix &S, TPZFMatrix &T) { template TVar TPZMixedElasticityND::InnerVec(const TPZVec &S, const TPZVec &T) { //inner product of two vectors -#ifdef DEBUG +#ifdef PZDEBUG if (S.size() != T.size()) { DebugStop(); } @@ -1179,7 +1179,7 @@ TVar TPZMixedElasticityND::InnerVec(const TPZVec &S, const TPZVec &T //////////////////////////////////////////////////////////////////// STATE TPZMixedElasticityND::Tr(TPZFMatrix &GradU) { -#ifdef DEBUG +#ifdef PZDEBUG if (GradU.Rows() != GradU.Cols()) { DebugStop(); } diff --git a/Mesh/TPZCompElHDivDuplConnects.cpp b/Mesh/TPZCompElHDivDuplConnects.cpp index e94aa2357..79342008b 100644 --- a/Mesh/TPZCompElHDivDuplConnects.cpp +++ b/Mesh/TPZCompElHDivDuplConnects.cpp @@ -59,7 +59,7 @@ template int TPZCompElHDivDuplConnects::NConnectShapeF(int connect, int order)const { -#ifdef DEBUG +#ifdef PZDEBUG if (connect < 0 || connect > TSHAPE::NFacets*2) { DebugStop(); } diff --git a/Mesh/TPZCompElHDivDuplConnectsBound.cpp b/Mesh/TPZCompElHDivDuplConnectsBound.cpp index b60d76316..b87b5cdb7 100644 --- a/Mesh/TPZCompElHDivDuplConnectsBound.cpp +++ b/Mesh/TPZCompElHDivDuplConnectsBound.cpp @@ -43,7 +43,7 @@ int TPZCompElHDivDuplConnectsBound::NSideConnects(int side) const{ template int TPZCompElHDivDuplConnectsBound::NConnectShapeF(int connect, int connectorder)const { -#ifdef DEBUG +#ifdef PZDEBUG if (connect < 0 || connect > TSHAPE::NFacets) { DebugStop(); } diff --git a/Mesh/pzelchdiv.cpp b/Mesh/pzelchdiv.cpp index 04b72b511..01960d2bc 100644 --- a/Mesh/pzelchdiv.cpp +++ b/Mesh/pzelchdiv.cpp @@ -249,7 +249,7 @@ void TPZCompElHDiv::SetConnectIndex(int i, int64_t connectindex){ template int TPZCompElHDiv::NConnectShapeF(int connect, int order)const { -#ifdef DEBUG +#ifdef PZDEBUG if (connect < 0 || connect > TSHAPE::NFacets) { DebugStop(); } diff --git a/Mesh/pzelchdivbound2.cpp b/Mesh/pzelchdivbound2.cpp index c6882519f..3a6ab4804 100644 --- a/Mesh/pzelchdivbound2.cpp +++ b/Mesh/pzelchdivbound2.cpp @@ -303,7 +303,7 @@ void TPZCompElHDivBound2::SetConnectIndex(int i, int64_t connectindex) template int TPZCompElHDivBound2::NConnectShapeF(int connect, int connectorder) const { -#ifdef DEBUG +#ifdef PZDEBUG if (connect < 0 || connect > TSHAPE::NFacets) { DebugStop(); } diff --git a/Mesh/pzgmesh.cpp b/Mesh/pzgmesh.cpp index a08505314..09dd4f500 100644 --- a/Mesh/pzgmesh.cpp +++ b/Mesh/pzgmesh.cpp @@ -99,6 +99,9 @@ TPZGeoMesh::~TPZGeoMesh() #ifdef PZDEBUG2 std::cout << "Deleting TPZGeoMesh " << (void *) this << std::endl; #endif + if (fReference && fReference->Reference() == this) { + fReference->SetReference(nullptr); + } CleanUp(); } diff --git a/Post/pzpostprocanalysis.cpp b/Post/pzpostprocanalysis.cpp index a8fcdc6ff..35e7460f0 100644 --- a/Post/pzpostprocanalysis.cpp +++ b/Post/pzpostprocanalysis.cpp @@ -80,18 +80,6 @@ TPZLinearAnalysis(), fpMainMesh(pRef) } -TPZPostProcAnalysis::TPZPostProcAnalysis(const TPZPostProcAnalysis ©) : TPZRegisterClassId(&TPZPostProcAnalysis::ClassId), -TPZLinearAnalysis(copy), fpMainMesh(0) -{ - -} - -TPZPostProcAnalysis &TPZPostProcAnalysis::operator=(const TPZPostProcAnalysis ©) -{ - SetCompMesh(0); - return *this; -} - TPZPostProcAnalysis::~TPZPostProcAnalysis() { if (fCompMesh) { diff --git a/Post/pzpostprocanalysis.h b/Post/pzpostprocanalysis.h index 6e1f62333..88f49e06d 100644 --- a/Post/pzpostprocanalysis.h +++ b/Post/pzpostprocanalysis.h @@ -26,9 +26,12 @@ TPZPostProcAnalysis(TPZCompMesh * pRef); TPZPostProcAnalysis(); - TPZPostProcAnalysis(const TPZPostProcAnalysis ©); - - TPZPostProcAnalysis &operator=(const TPZPostProcAnalysis ©); + /** @brief Copying is disabled: the base class (TPZAnalysis) owns fSolver + * and deletes it in its destructor, so copying would make two objects + * delete the same pointer. */ + TPZPostProcAnalysis(const TPZPostProcAnalysis ©) = delete; + + TPZPostProcAnalysis &operator=(const TPZPostProcAnalysis ©) = delete; virtual ~TPZPostProcAnalysis(); diff --git a/Pre/TPZH1ApproxCreator.cpp b/Pre/TPZH1ApproxCreator.cpp index 6ce075a4d..a77f1d244 100644 --- a/Pre/TPZH1ApproxCreator.cpp +++ b/Pre/TPZH1ApproxCreator.cpp @@ -101,9 +101,10 @@ void TPZH1ApproxCreator::CreateAtomicMeshes(TPZVec &meshvec) { meshvec.resize(fNumMeshes); int countMesh = 0; - if(HybridType() != HybridizationType::ENone) + if(HybridType() != HybridizationType::ENone) { meshvec[countMesh++] = CreateBoundaryHDivSpace(); - meshvec[countMesh++] = CreateL2Space(); + } + meshvec[countMesh++] = CreateL2Space(); if (fIsRBSpaces){ int lagMult1 = EDistFlux, lagMult2 = EAvSol; @@ -639,7 +640,7 @@ TPZCompMesh *TPZH1ApproxCreator::CreateBoundaryHDivSpace() int nstate = 1; if(fProbType == ProblemType::EElastic) nstate = fGeoMesh->Dimension(); //Inserting HDiv material - if (fHybridType!= HybridizationType::EStandard || fHybridType!= HybridizationType::EStandardSquared) { + if (fHybridType== HybridizationType::EStandard || fHybridType== HybridizationType::EStandardSquared) { int matid = fHybridizationData.fLagrangeMatId; auto nullmat = new TPZNullMaterial(matid); nullmat->SetDimension(fGeoMesh->Dimension()-1); diff --git a/Pre/pzcreateapproxspace.h b/Pre/pzcreateapproxspace.h index d35bef3f6..b2a0939ae 100644 --- a/Pre/pzcreateapproxspace.h +++ b/Pre/pzcreateapproxspace.h @@ -60,24 +60,9 @@ class TPZCreateApproximationSpace : public TPZSavable { SetAllCreateFunctionsContinuous(); } - TPZCreateApproximationSpace(const TPZCreateApproximationSpace ©) : fCreateHybridMesh(copy.fCreateHybridMesh), fCreateLagrangeMultiplier(copy.fCreateLagrangeMultiplier) - ,fCreateWithMemory(copy.fCreateWithMemory) - { - for (int i=0; i<8; i++) { - fp[i] = copy.fp[i]; - } - } - - TPZCreateApproximationSpace &operator=(const TPZCreateApproximationSpace ©) - { - for (int i=0; i<8; i++) { - fp[i] = copy.fp[i]; - } - fCreateHybridMesh = copy.fCreateHybridMesh; - fCreateLagrangeMultiplier = copy.fCreateLagrangeMultiplier; - fCreateWithMemory = copy.fCreateWithMemory; - return *this; - } + TPZCreateApproximationSpace(const TPZCreateApproximationSpace ©) = default; + + TPZCreateApproximationSpace &operator=(const TPZCreateApproximationSpace ©) = default; int ClassId() const override; void Read(TPZStream &buf, void *context) override; @@ -97,15 +82,15 @@ class TPZCreateApproximationSpace : public TPZSavable { // Get set methods for space families const HDivFamily &HDivFam() const {return fhdivfam;} const HDivFamily &HDivFam() {return fhdivfam;} - const void SetHDivFamily(HDivFamily fam){fhdivfam = fam;} + void SetHDivFamily(HDivFamily fam){fhdivfam = fam;} const H1Family &H1Fam() const {return fh1fam;} const H1Family &H1Fam() {return fh1fam;} - const void SetH1Family(H1Family fam){fh1fam = fam;} + void SetH1Family(H1Family fam){fh1fam = fam;} const HCurlFamily &HCurlFam() const {return fhcurlfam;} const HCurlFamily &HCurlFam() {return fhcurlfam;} - const void SetHCurlFamily(HCurlFamily fam){fhcurlfam = fam;} + void SetHCurlFamily(HCurlFamily fam){fhcurlfam = fam;} /** @brief Create discontinuous approximation spaces */ void SetAllCreateFunctionsDiscontinuous(); diff --git a/README.md b/README.md index 23391bbcb..8de9fa3b6 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,10 @@ can be added to a startup file of your shell. In both examples, `pz_install_dir` A Doxygen documentation can be found [here](http://www.labmec.org.br/pz/arquivos-html/html/index.html). +Additionally, the [`ai-analysis`](ai-analysis) folder contains an AI-generated +codebase analysis (architecture overview, algorithm notes, and a findings/roadmap +report). + ## How to cite NeoPZ Devloo, P.R. B., 1997. PZ: An object oriented environment diff --git a/Shape/TPZShapeHDiv.cpp b/Shape/TPZShapeHDiv.cpp index 8e3bb8d52..de3b964c4 100644 --- a/Shape/TPZShapeHDiv.cpp +++ b/Shape/TPZShapeHDiv.cpp @@ -477,7 +477,7 @@ int TPZShapeHDiv::NShapeF(const TPZShapeData &shapedata) template int TPZShapeHDiv::ComputeNConnectShapeF(int connect, int order) { -#ifdef DEBUG +#ifdef PZDEBUG if (connect < 0 || connect > TSHAPE::NFacets) { DebugStop(); } diff --git a/Shape/TPZShapeHDivConstant.cpp b/Shape/TPZShapeHDivConstant.cpp index 31a345b07..96ea3efe7 100644 --- a/Shape/TPZShapeHDivConstant.cpp +++ b/Shape/TPZShapeHDivConstant.cpp @@ -301,7 +301,7 @@ void TPZShapeHDivConstant::Shape(const TPZVec> &pt, TPZShapeDa count++; // Kernel HDiv functions - for (int k = 0; k < data.fHCurl.fNumConnectShape[nedges]; k++) + for (int k = 0; k < data.fHCurl.fNumConnectShape[nedges + i]; k++) { for (auto d = 0; d < dim; d++) { @@ -343,7 +343,7 @@ template int TPZShapeHDivConstant::ComputeNConnectShapeF(int connect, int order) { -#ifdef DEBUG +#ifdef PZDEBUG if (connect < 0 || connect > TSHAPE::NFacets) { DebugStop(); diff --git a/Shape/TPZShapeHDivConstantBound.cpp b/Shape/TPZShapeHDivConstantBound.cpp index 23b279785..39fe7af22 100644 --- a/Shape/TPZShapeHDivConstantBound.cpp +++ b/Shape/TPZShapeHDivConstantBound.cpp @@ -105,7 +105,7 @@ void TPZShapeHDivConstantBound::Shape(const TPZVec &pt, TPZShapeDa template int TPZShapeHDivConstantBound::ComputeNConnectShapeF(int connect, int order) { -#ifdef DEBUG +#ifdef PZDEBUG if (connect < 0 || connect > TSHAPE::NFacets) { DebugStop(); } diff --git a/Shape/TPZShapeHDivOptimized.cpp b/Shape/TPZShapeHDivOptimized.cpp index 4a6696c85..11188134f 100644 --- a/Shape/TPZShapeHDivOptimized.cpp +++ b/Shape/TPZShapeHDivOptimized.cpp @@ -419,7 +419,7 @@ int TPZShapeHDivOptimized::NShapeF(const TPZShapeData &shapedata) template int TPZShapeHDivOptimized::ComputeNConnectShapeF(int connect, int order) { -#ifdef DEBUG +#ifdef PZDEBUG if (connect < 0 || connect > TSHAPE::NFacets) { DebugStop(); diff --git a/Topology/TPZTopologyUtils.h b/Topology/TPZTopologyUtils.h index 39c6b7168..4ca05d7d8 100644 --- a/Topology/TPZTopologyUtils.h +++ b/Topology/TPZTopologyUtils.h @@ -20,7 +20,7 @@ namespace pztopology{ // };// if, in the future, there are more topology settings to be adjusted, this model of singleton can be used. typedef std::numeric_limits< REAL > dbl; - static REAL gTolerance = pow(10,(-1 * (dbl::max_digits10- 5))); + inline REAL gTolerance = pow(10,(-1 * (dbl::max_digits10- 5))); REAL GetTolerance(); diff --git a/ai-analysis/ALGORITHM_NOTES.md b/ai-analysis/ALGORITHM_NOTES.md new file mode 100644 index 000000000..3eb333b0e --- /dev/null +++ b/ai-analysis/ALGORITHM_NOTES.md @@ -0,0 +1,82 @@ +# NeoPZ Algorithm Notes + +**Phase 4 deliverable; §10–§12 added in Session 2 (2026-07-06).** Deep review of the major techniques on the analyzed paths, at `develop @ 6ffd38b12` (runtime evidence labeled `[run @ 852a5116c(+)]`). Method: four line-cited code traces (H1 hybrid creator at develop, HDiv creator + semi-hybridization, H(div) shape/Piola pipeline, app-side Schur solver) with load-bearing lines re-verified first-hand, plus an instrumented run of the mandated slice; Session 2 added static traces of the non-HDiv families, the restraint/composition machinery, and the geometry layer. Full detail in `wiki/` (links inline). + +--- + +## 1. H(div) basis construction & the Piola question — **resolved, conventional (variant factorization)** + +**Goal**: H(div)-conforming vector bases on all topologies, hierarchical, hp-capable. +**Implementation**: `Shape/TPZShapeHDiv*` compose each vector shape = scalar H1 shape × constant master-element direction (`TPZShapeHDiv.cpp:345-355`), directions from Topology (`ComputeHDivDirections`; the triangle routine is itself commented "contravariant piola mapping", `tpztriangle.cpp:1064-1068`). Shape layer outputs **master** quantities only. The element layer applies the **contravariant Piola map pointwise**: `fDeformedDirections = (1/|detJ|)·J·φ̂`, `divphi *= 1/|detJ|` (`Mesh/pzelchdiv.cpp:1032-1033`, verified). Orientation = `fSideOrient` (from `TPZGeoEl::NormalOrientation`) folded into master directions + facet-DOF permutation gather (`HDivPermutation`) for neighbor compatibility. Curved elements: pointwise Jacobians + an optional FAD branch (`:979-1031`) giving exact physical derivatives; algebraic divergence scaling is exact for general smooth maps (Piola identity) — no hidden affine assumption found. +**Verdict**: conventional contravariant Piola in a NeoPZ-specific factorization (|detJ| + explicit side-orient signs instead of signed detJ). Matches the published construction ([[devloo-group-shape-construction]]). +**Residual risks**: (a) |detJ|⊕fSideOrient sign composition across all refinement/orientation configs — expert derivation or targeted test recommended; (b) confirmed REAL-vs-FAD inconsistency in `TPZShapeHDivConstant` facet kernel counts ([[finding-hdivconstant-fad-index]]) — latent for curved × HDivConstant × variable face order; (c) intentionality of unused `divphiFad`. +**Validation present**: De Rham rank/kernel tests (SVD), permutation-invariance tests, constant div/curl reproduction, side-shape continuity — strong at basis level; no test combines H(div) × curved geometry × convergence rate (Phase 7 gap). + +## 2. HDivConstant / kernel families — **intentional variants, published** + +`TPZShapeHDivConstant` derives from `TPZShapeHCurlNoGrads`: per facet a single RT0-like function carries the (constant) divergence; all remaining functions are divergence-free (rotated H1 gradients in 2D, HCurl-NoGrads curls in 3D) (`TPZShapeHDivConstant.cpp:129-215`). Divergence image = piecewise constants — the property enabling exact total condensation with order-0 pressures. Family/enrichment-driven accuracy differences are the group's published research axis ([[devloo-hdiv-variants-accuracy]]). `EHDivOptimized` semantics remain undocumented in-tree (expert question). + +## 3. Hybridization taxonomy — **traced end-to-end; conventional core + published extensions** + +Frame: [[cockburn-2009-unified-hybridization]]. NeoPZ realization ([[hybridization]] for full line-cites): +- **Geometry protocol**: wrap geoels on interior facets + interface pairs + Lagrange skeleton geoels, ids strided above max matid; interfaces registered in `HybridizationData::fInterfaces`; glue = `TPZMultiphysicsInterfaceElement` + `TPZLagrangeMultiplierCS` with problem-dependent sign tables (verified `TPZApproxCreator.cpp:780-830`). +- **EStandard (H1)**: broken H1 volume; wrap comp-els *share* volume connects; skeleton flux mesh (HDivStandard, dim−1). Single multiplier level. +- **EStandardSquared (H1; mandated slice)**: literal hybridization² — `AddHybridSquareGeoElements` adds a second interface+multiplier layer; condensation groups absorb first-level flux/Lagrange DOFs (`AssociateElements`, numloops=2), leaving **only the second-level skeleton global**. Structurally matches the primal double-hybrid method of [[avancini-2025-double-hybrid-elasticity]]. +- **ESemi (HDiv)**: requires EHDivConstant/EHDivOptimized; per interior facet the flux connect splits into even=constant (1 shape) + odd=higher-order (nshape−1) via `TPZCompElHDivDuplConnects`; only the even connect on the sideOrient=−1 side is rebound to the wrap ⇒ *constant normal flux* becomes multiplier-mediated, higher-order trace stays strongly continuous; order-0 multiplier mesh. Structurally the semi-hybridization of [[carvalho-2024-semi-hybrid-stokes]] (which trace is weakened differs — intentional variant). +- **Elasticity extras**: mixed-elasticity in HDiv adds a rotation space (weak symmetry; scalar 2D / 3-vector 3D); in-code guard documents that condensed HDivConstant elasticity is singular without ESemi or rigid-body spaces (`TPZHDivApproxCreator.cpp:85-89`). +**Assumptions/invariants**: multiplier sign tables per problem (Elastic asymmetry — only right interface reset to +1 — flagged as expert question); Lagrange-level ordering drives what is condensable; `EAvSol` global-coupling mechanism under EStandardSquared unclear from code (works per tests) — expert question. +**Hygiene**: cluster of small verified defects in exactly this layer ([[finding-approx-creator-hygiene]]). + +## 4. Static condensation & rigid-body spaces — **coherent design, invariants identified** + +`TPZElementGroup` → `TPZCondensedCompElT` decorator (exposes only active connects; internal Schur via library `TPZMatRed`, which is rigid-body-mode aware — `pzmatred.h:23-79` verified). Connect "Lagrange levels" order condensability; `fIsRBSpaces` appends order-0 constant meshes (distributed flux + average solution; elastic: 3/6 states = rigid-body-mode counts) precisely to make interior blocks invertible for total condensation. Invariants: K00 invertibility (guarded in one known-singular case), correct recovery via `UGlobal`-style back-substitution, dependency (hanging-node) connects excluded from splits. + +## 5. The app-side Schur solver (`TPZMatRedSolver`/`TPZSparseMatRed`) — **sound structure; one consequential mislabel** + +Flow (verified by trace + run): equations split purely by Lagrange level (`lag={1}` → K00), independent of mode; K00 = symmetric sparse Pardiso/MUMPS, Cholesky-factorized; Schur complement K11−K10·K00⁻¹·K01 applied **matrix-free** in CG (`TPZSparseMatRed::MultAdd`), block-diagonal(ELU) preconditioner from K11; 500 iter cap, tol 1e-10; solution recovered and loaded back. Negative-definite K00 handled by global sign flips for the H1-hybrid modes. +**Run evidence** [run]: CG iterations = 19 at 50² and 400² (p=1) — mesh-independent; t1 = block assembly, t2 = K00 factorization + preconditioner build + CG. +**Findings**: mode mislabel with measurable effect on the benchmark ([[finding-matred-solver-mode-mislabel]]); memory-unit platform bug ([[finding-rusage-memory-units]]); `EMHMSparse`-era API removed at HEAD leaving one registered target uncompilable ([[finding-mhm-target-uncompilable]]). "Orthogonalizing restraints" (`ComputeOrthogonalizingRestraints`, app-side, feeding the High-Order/Linear flux split observed at runtime) not yet traced — expert/maintainer question. + +## 6. Assembly & solve orchestration — **verified at the orchestration level** + +`TPZLinearAnalysis::AssembleT`: defaulting rules (MKL sparse else skyline; LU), in-place matrix reuse when size matches, load-case-aware RHS (`TPZLinearAnalysis.cpp:35-100`, verified). Solve honors equation filters (`NReducedEquations`). Parallel-vs-serial assembly equality is unit-tested (`TestMultithreading` [agent]). Per-element `CalcStiff` → material `Contribute` pipeline detail (H1/mixed data vectors ordering) is documented per creator ordering; thread-safety of shared materials → Phase 5. + +## 7. At-pin defects on analyzed paths (library) + +1. **`TPZHybridElasticity2D::Contribute` omits body-force RHS at the pin** — confirmed, fixed 2 commits later upstream ([[finding-hybridelasticity2d-missing-rhs-at-pin]]). The mandated benchmark is insensitive (zero body force), which is exactly why no test caught it. +2. `TPZShapeHDivConstant` FAD facet-count inconsistency ([[finding-hdivconstant-fad-index]]). +3. `TPZCreateApproximationSpace` copy ops drop family flags ([[finding-approxspace-copy-drops-families]]). +4. Missing self-assignment guard pattern (`TPZMatRed::CopyFrom`; patched post-pin in `TPZSYsmpMatrix`) — same family. + +## 8. Numerical-stability & correctness watchlist (expert-validation queue) + +- |detJ| ⊕ fSideOrient composition on reflected/refined configurations ([[piola-transformations]]). +- Elastic interface-multiplier sign asymmetry (H1 path). +- `EAvSol` coupling mechanism under EStandardSquared. +- ESemi-for-Darcy vs the Stokes-oriented published semi-hybridization (which trace should be weak for Darcy). +- Preconditioner block-size validity (`bsize | nEqHigh`) if the elasticity mode is corrected. +- Quadrature-order sufficiency for `fExtraInternalPOrder`-enriched spaces on curved maps (untested combination). + +## 9. Non-HDiv element families (Session 2) — **traced structurally, conventional with documented variants** + +Full detail: [[element-families]], [[h1-space]], [[hcurl-space]], [[discontinuous-l2-dg]]. +- **H1**: one connect per side (incl. corners, clamped to order 1); `TPZShapeH1` corner×generating-function hierarchical composition; `EffectiveSideOrder` = max over sub-sides. `H1Family::EH1WidePrism` is a creation-time template choice for prisms only — the stored flag is never consulted at runtime (a latent surprise for anyone toggling it post-construction). +- **H(curl)**: covariant Piola in `TPZCompElHCurl::TransformShape` (`axesᵀ·J⁻ᵀ·phî`; curl via `J·curl̂/detJ` in 3D) — structural mirror of the H(div) contravariant trace in §1; orientation implicit via node-id transform ids (no `fSideOrient` analog); `EHCurlNoGrads` filters gradient fields (and is reused as the divergence-free carrier of `TPZShapeHDivConstant`, §2); dedicated vector `RestrainSideT` (refuses small-side order < large order); pyramid/point unavailable by DebugStop. +- **Discontinuous/L²**: `TPZCompElDisc` = single connect, modal basis about the element center, external-shape enrichment hook; the mixed-pair "L² mesh" is broken-H1 for p>0 (procedural disconnection at build) and true Disc at p=0 — worth knowing before comparing DOF counts across families. +- **Interfaces/DG**: compositional (space + `CreateInterfaceElements` + interface-mixin material); shared code path with hybridization's Lagrange glue. + +## 10. Restraints & composition machinery (Session 2) — **coherent; invariants DebugStop-enforced** + +Full detail: [[TPZConnect]], [[condensation-groups-submeshes]], [[multiphysics-composition]], [[geometry-refinement-maps]]. +- **Hanging nodes end-to-end**: geometric `Divide` → `CreateMidSideConnect` finds the coarse neighbor by ancestor walk → `RestrainSide` solves the side L2 projection (`M⁻¹·MSL`, LU) → `TPZConnect::AddDependency`; applied per element via a complex-correct congruence transform (`Dᴴ K D`, conjugate-transpose MultAdd) in topological dependency order. The only geometric input is `SideTransform3` — the transform-accumulation walk up the refinement tree. +- **Ordering constraints that must not be shuffled**: restraints before condensation (dependent∧condensed illegal); `ComputeNodElCon` after grouping, before condensation decisions; `SaddlePermute` (Lagrange-level global ordering) before `PermuteExternalConnects` before submesh matrix creation; multiphysics `AddConnects` re-offsets dependency masters. All enforced by PZDEBUG DebugStops, not types — consistent with the §5-era findings on unenforced conventions. +- **Composition ladder**: ElementGroup (sum + connect-union, hides members from the mesh) → CondensedCompElT (per-group `TPZMatRed::K11Reduced`/`UGlobal`, `SetKeepMatrix(false)` memory mode) → SubCompMesh (mesh-as-element; internal analysis with equation-filtered factorization over internals; rigid-body-mode count passed to TPZMatRed for floating substructures) — the mechanism stack beneath condensation, MHM, and every downstream Schur variant. +- **Geometry guarantees**: children of curved elements evaluate the *eldest ancestor's* exact map (`TPZGeoElMapped`); uniform pyramid refinement yields 6 pyramids + 4 tets (mixed-type meshes appear unbidden); refinement patterns fail loudly on neighbor incompatibility; saved refined meshes require the same `gRefDBase` to be repopulated before reading (persistence coupling). + +## 11. Downstream algorithmic patterns (Session 2, app-repo evidence) + +From the five-app survey ([[apps-overview]]): an Uzawa/augmented-Lagrangian outer iteration over a single reused Cholesky factorization with hand-assembled CSR coupling operators (Iterative-Saddle_Point); partition-of-unity enrichment via `ComputeShape` override + patch-eigenvalue orthogonalization of enrichment DOFs (GFEM); reconstruction-based error estimators (edge/nodal averaging into conforming spaces; PoU patch solves) driving closed h/hp loops (ErrorEstimation); cross-dimensional coupling by direct connect-dependency programming (wann); weak-symmetry tensor mixed methods to 7 fields + custom-refpattern macro-elements (MixedElasticity). Three independent MatRed reimplementations downstream corroborate §5's assessment that the block-reduction pattern deserves first-class library support. + +## 12. Performance notes carried to Phase 6 (Session 1) + +Mesh-independent CG counts (excellent); K00 factorization dominates t2 at scale (3.4 s of 4.7 s at 400², p=1 [run]); assembly scales ~linearly across the sweep; renumbering disabled in benchmarks (`RenumType::ENone`) — interaction with the Lagrange-level-contiguous reordering inside `TPZSparseMatRed::ReorderEquations` explains why (the solver does its own ordering); memory column unreliable on macOS. diff --git a/ai-analysis/CODEBASE_ATLAS.md b/ai-analysis/CODEBASE_ATLAS.md new file mode 100644 index 000000000..4bcd8c2f8 --- /dev/null +++ b/ai-analysis/CODEBASE_ATLAS.md @@ -0,0 +1,156 @@ +# NeoPZ Codebase Atlas + +**Analyzed commit:** `develop` @ `6ffd38b12` (2026-06-12) in `labmec/neopz` (local clone `NeoPZ_divfree`). +**Working-tree caveat:** checkout is `SemiHybridElasticity` @ `4de234fae` = develop + 3 commits touching exactly 5 files +(`Material/Elasticity/TPZHybridElasticity2D.cpp`, `Matrix/TPZSYSMPMatrix.h`, `Matrix/pzmatrix.h`, `Pre/TPZH1ApproxCreator.{h,cpp}`); +claims about those files are cross-checked against `git show develop:`. +**Repo default branch** is `main`; `develop` is the integration branch and the review canon (user instruction). +**Evidence markers:** `[repo]` verified first-hand at the pin; `[agent]` located by a read-only explorer and cited but not yet independently re-verified; `[run]` runtime observation of installed builds. Details and page-level citations live in `ai-analysis/wiki/`. + +--- + +## 1. What this repository is + +NeoPZ is a single-library C++17 finite element environment (`project(PZ)`, one `add_library(pz)` target — CMakeLists.txt:8,52 [repo]) +developed by LabMEC/Unicamp since the 1990s (Devloo, CMAME 1997). It provides, per README.md:14-21 [repo]: discontinuous, H1-, H(div)- and +H(curl)-conforming approximation spaces, multiphysics, hp-adaptivity, hanging nodes, runtime-defined refinement patterns, exact curved +geometry, and forward automatic differentiation. It is a library only — applications live in downstream repos +(here: `../divfreebubbles`, see §7). + +## 2. Module map + +Single library; top-level directories are source groups appended to `pz` in dependency-ish order (CMakeLists.txt:320-343 [repo]). +File counts measured on the working tree [agent, spot-checked]. + +| Module | .h/.cpp | Responsibility (one line) | Key types | +|---|---|---|---| +| `Util/` | 36/24 | Foundation containers & helpers: vectors, stacks, chunk vectors, ref-counted pointer, logging | `TPZVec`, `TPZManVector`, `TPZStack`, `TPZChunkVector`, [[TPZAutoPointer]], `pzlog` | +| `Common/` | 53/7 | Numeric type config (REAL/STATE), error macros, element-type enum, thread pool | `pzreal.h`, `DebugStop`, `MElementType`, `TPZThreadPool` | +| `Save/` | 13/11 | Object persistence with ClassId registry + versioned chunk translators | `TPZSavable`, `TPZStream`, `TPZPersistenceManager` → [[persistence]] | +| `Integral/` | 11/9 | Quadrature rules per topology (long double precision internally) | `TPZIntPoints`, `tpzgaussrule` → [[quadrature]] | +| `Solvers/` | 27/16 | Linear & eigen solver wrappers incl. Pardiso/MUMPS bindings | `TPZMatrixSolver`, `TPZStepSolver`, `TPZPardisoSolver` → [[matrix-and-solvers]] | +| `Matrix/` | 32/29 | Matrix storage zoo: dense, banded, skyline, Yale sparse (sym/nonsym) | `TPZFMatrix`, `TPZSkylMatrix`, `TPZFYsmpMatrix` → [[matrix-and-solvers]] | +| `Topology/` | 11/10 | Master-element combinatorics: sides, permutations, transforms | `pztopology::TPZTriangle` … → [[topology-module]] | +| `Geom/` | 15/11 | Reference→physical geometric maps per topology + blend maps | `pzgeom::TPZGeoQuad`, `pznoderep`, `tpzgeoblend` → [[geometric-mappings]] | +| `SpecialMaps/` | 20/19 | Exact curved maps (arcs, spheres, tori, cylinder, NACA, quadratic els) | `TPZArc3D`, `TPZCylinderMap`, `TPZQuadSphere` | +| `Shape/` | 26/22 | Shape functions as **static, non-virtual** per-topology classes; H1/HDiv/HCurl families | `pzshape::TPZShapeQuad`, `TPZShapeHDiv*`, `TPZShapeHCurl*`, `TPZShapeData` → [[shape-functions]] | +| `Refine/` | 12/11 (+71 `.rpt`) | h-refinement via runtime refinement patterns (data-driven) | `TPZRefPattern`, `TPZRefPatternDataBase` → [[refinement-hanging-nodes]] | +| `External/` | 10/17 | Vendored renumbering/partitioning: Sloan, (R)CM, METIS wrapper, Boost graph | `TPZRenumbering`, `TPZCutHillMcKee`, `TPZSloanRenumbering` | +| `Material/` | 199/178 | Weak forms & constitutive models; variadic mixin base + per-physics dirs + big legacy layer | [[material-system]]: `TPZMaterial`, `TPZMatBase`, `TPZBndCond`; `needrefactor/` (19+108 files) | +| `Mesh/` | 65/61 | Geometric & computational meshes; element hierarchies for all space families | [[TPZGeoMesh]], [[TPZCompMesh]], `TPZCompEl`, `TPZInterpolatedElement`, [[TPZCompElHDiv]], `TPZCompElHCurl`, `TPZMultiphysicsCompMesh`, `TPZSubCompMesh`, `TPZCondensedCompEl` | +| `Analysis/` | 13/13 | Drives the solve sequence: renumber → assemble → solve → post-process | [[TPZAnalysis]], `TPZLinearAnalysis`, `TPZEigenAnalysis` | +| `Post/` | 29/26 | Post-processing/output: legacy graph meshes (DX/MV/V3D/VTK) + modern VTK generator | [[post-processing-vtk]]: `TPZVTKGenerator`, `TPZGraphMesh`, `TPZVTKGeoMesh` | +| `Frontal/` | 8/9 | Frontal (out-of-core style) solver machinery | `TPZFront`, `TPZFrontMatrix` | +| `StrMatrix/` | 24/24 | "Structural matrices": assembly strategies binding mesh↔storage↔parallel scheme | [[structural-matrices]]: `TPZStructMatrix(T)`, `TPZSkylineStructMatrix`, `TPZSSpStructMatrix`, `TPZEquationFilter` | +| `Pre/` | 34/31 | Pre-processing: mesh readers/generators, analytic solutions, **approximation-space creators**, hybridization, MHM controllers | [[mesh-io-generators]], [[approx-space-creators]]: `TPZGmshReader`, `TPZGenGrid2D/3D`, `TPZAnalyticSolution`, `TPZCreateApproximationSpace`, `TPZApproxCreator` → `TPZHDivApproxCreator`/`TPZH1ApproxCreator`, `TPZHybridizeHDiv`, `TPZMHM*MeshControl` | +| `SubStruct/` | 13/12 | Substructuring / BDDC (Dohrmann) domain decomposition | `TPZDohrStructMatrix`, `tpzdohrsubstruct` | +| `Random/` | 5/1 | Random number generators (uniform/normal/constrained) | `TPZRandom` | +| `Optimization/` | 1/0 | Stub: stochastic search | `TPZStochasticSearch` | +| `Exception/` | 3/3 | Typed exceptions | `TPZConvergenceException` | +| `PerfUtil/`, `PerfTests/` | — | Perf measurement toolkit + standalone benchmarks (stale; "in need of a revision" per own README [agent]) | `run_stats_table`, `SubStruct/substruct.cpp` | +| `Publications/` | 3 pairs | Paper-companion code: `hdiv2dpaper201504`, `hdiv3dpaper201504`, `hdivCurvedJCompAppMath` [repo] | — | +| `UnitTest_PZ/` | 33 suites | Catch2 v3.3.2 test suites (§6) | — | + +Quirks worth knowing [repo]: 4 double-extension `.h.h` files carry template bodies (`Geom/pznoderep.h.h`, `Mesh/TPZGeoElement.h.h`, +`Mesh/pzgeoelrefless.h.h`, `Mesh/tpzgeoelrefpattern.h.h`); two naming eras coexist (`pz*.h` older, `TPZ*.h` newer); `Refine/RefPatterns/` +holds 71 `.rpt` refinement-pattern *data* files loaded at runtime. + +## 3. Dependency layering (first pass) + +CMake `add_subdirectory` order (CMakeLists.txt:320-343 [repo]) approximates the layering; all code links into one `pz` target, so +"dependencies" are include-level, not link-level: + +``` +foundation: Util → Common → Save +numerics: Integral, Solvers, Matrix +reference layer: Topology → Geom → SpecialMaps → Shape → Refine +discretization: External, Material → Mesh +orchestration: Analysis, Post, Frontal, StrMatrix, Pre, SubStruct +extras: Random, Optimization, Exception +``` + +Observed include-level couplings [repo]: `Mesh/pzcmesh.h` includes `pzcreateapproxspace.h` (Pre) — i.e. **Mesh ↔ Pre are mutually +entangled** (the computational mesh owns a `TPZCreateApproximationSpace` member); `Analysis/TPZAnalysis.h` includes StrMatrix + Solvers + +External (renumbering); `TPZGeoMesh` and `TPZCompMesh` hold mutual `fReference` pointers (pzgmesh.h:55, pzcmesh.h:49 [repo]). A true +include-graph pass is deferred to Phase 5. + +## 4. Build system + +[repo, verified] CMake ≥ 3.14 (`CMakeLists.txt:3`; README says 3.13+ — minor doc mismatch), C++17 enforced (`:13-14`), single shared lib +(static on Windows). Type system via `cmake/StandardPZSettings.cmake`: `REAL_TYPE` (geometry scalar) and `STATE_TYPE` (FE scalar) each +float/double/long double, plus `REAL_TYPE=pzfpcounter` (op-counting instrumented scalar); complex state = `CSTATE`. Generated +`Common/pz_config.h` embeds source dir, refpattern dir, git branch/revision/date. +24 `option()` flags [repo count]: only Threads is required; optional `USING_MKL` (forces LAPACK; Pardiso), `USING_MUMPS`, `USING_LAPACK` +(Accelerate on Apple), `USING_METIS`, `USING_TBB`, `USING_OMP`, `USING_LOG4CXX` (→`PZ_LOG`), `USING_BOOST`, `USING_EIGEN`, +`USING_UMFPACK`, `USING_BLAZE`, perf instrumentation (`LIKWID/PAPI/LIBNUMA`), and build toggles (`BUILD_UNITTESTING`, `BUILD_PERF_TESTS`, +`BUILD_PUBLICATIONS`, `BUILD_PROJECTS`, `BUILD_PLASTICITY_MATERIALS`, `BUILD_DOCS`/`BUILD_SPHINX_DOCS`) [agent, options spot-verified]. +Install exports a proper CMake package: `find_package(NeoPZ)` → `NeoPZ::pz` (install layout `/pz/{include,lib}` + +`/lib/cmake/neopz`) [agent; confirmed in practice by divfreebubbles' cache `NeoPZ_DIR=.../NeoPZ_install/lib/cmake/neopz` [repo]]. + +## 5. Entry points a user actually touches + +Typical downstream flow (confirmed in divfreebubbles targets [repo]): +1. **Geometry**: `TPZGeoMesh` from `TPZGmshReader` (in-tree .msh parser — gmsh is *not* linked), `TPZGenGrid2D/3D`, or + `TPZGeoMeshTools::CreateGeoMeshOnGrid`. +2. **Spaces**: either manual per-space `TPZCompMesh` construction + `TPZMultiphysicsCompMesh`, or the modern + `TPZHDivApproxCreator`/`TPZH1ApproxCreator` layer (Pre/) with `ProblemType{EDarcy,EElastic,EStokes}`, + `HybridizationType{ENone,EStandard,EStandardSquared,ESemi}`, optional rigid-body spaces + condensation + (Pre/TPZApproxCreator.h:15-16,42-68 [repo]). +3. **Physics**: a `TPZMatBase` material per material-id + `CreateBC` boundary conditions ([[material-system]]). +4. **Solve**: `TPZLinearAnalysis` + a `TPZStructMatrix` flavor + `TPZStepSolver` (direct ELDLt/ELU/Cholesky or CG/GMRES) — or external + Pardiso/MUMPS via sparse struct-matrices. +5. **Output**: `TPZVTKGenerator` (modern, NGSolve-derived — Post/TPZVTKGenerator.h:1-6 [repo]) or legacy `TPZGraphMesh` family; + errors via `TPZAnalysis::PostProcessError` against `SetExact`. + +## 6. Tests, CI, docs (condensed; full review in Phase 7) + +[agent, key items spot-verified] Catch2 v3.3.2 (FetchContent), 33 suites under `UnitTest_PZ/`, ~180+ TEST_CASEs. Notably *mathematical* +suites: `TestDeRham` (De Rham complex exactness via rank/kernel with SVD), `TestMesh/TestHDiv.cpp` (De Rham checks incl. under face/node +permutations, side-shape continuity, order checks), `TestTopology` (constant div/curl reproduction per topology), `TestHCurl`, +`TestHDivApproxSpaceCreator` (parametrized: HDiv family × Darcy/Elastic × mesh type × hybridization × condensation), +`TestSBFem` (convergence), `TestSolverComparison` (MUMPS vs Pardiso), `TestMultithreading` (parallel==serial assembly). +Known-failing tests marked `[!shouldfail]` (SVD, some skyline ops). CTest granularity = one test per suite executable +(`catch_discover_tests` disabled). CI = 5 GitHub Actions workflows; macOS job is the always-on test gate; Linux + MKL jobs run only when a +prebuilt `neopz-deps` image exists; no Windows CI, no coverage tooling. Docs = Doxygen + Sphinx/Breathe → labmec.github.io/neopz, +published from `main` only. No LICENSE/CONTRIBUTING files in tree [agent]. + +## 7. Downstream application landscape (Session 2, 2026-07-06) + +The library's user base is visible in `~/GitHub`: ~20 research repos embed their own NeoPZ copy (all near-develop, few local changes). The five most recently active were surveyed read-only (`wiki/apps/`, spot-verified): + +| App (active) | Domain | NeoPZ surface it stresses | +|---|---|---| +| Iterative-Saddle_Point (2026-03) | Uzawa/augmented-Lagrangian mixed Darcy & Stokes | Matrix/Pardiso layer as user API; manual Stokes hybridization + condensation | +| GFEM (2025-12) | fracture GFEM enrichment | `TPZCompElH1` subclassing (`ComputeShape` override); SBFem eigenmodes; custom StrMatrix/MatRed | +| ErrorEstimation (2025-11) | a-posteriori estimators + hp-adaptivity | mesh cloning/reconstruction, patch solves, closed adaptive loops, quarter-point/SBFem/NACA geometry | +| wann (2025-09) | 3D/2D/1D reservoir–wellbore Darcy → ANN data | connect surgery (`AddDependency`), cylinder+blend maps, directional refinement | +| MixedElasticity (2025-05) | Hellinger–Reissner tensor elasticity | 3–7-field multiphysics, weak/strong symmetry, MHM controllers + submeshes, frontal solver | + +Cross-cutting: manual space construction is first-class API everywhere; the connect layer is a public research surface; MatRed-style reduction reimplemented independently 3×; refinement patterns used for adaptivity, grading, *and* space construction; ~20 downstream material subclasses vs 1 element subclass; app→lib same-name-class migration is the growth mechanism (details: [[apps-overview]]). + +## 7b. Companion application repo: `../divfreebubbles` (branch `3DKernelHdiv`; the Session-1 vehicle) + +[repo/agent] Research app repo ("div-free bubbles" Laplace per README — stale; actual scope now spans mixed/hybrid Darcy and elasticity). +Own support lib `divfree/`: materials (`TPZMatDivFreeBubbles`, `TPZMixedDarcyH1`, …), creators (`TPZH1HybridApproxCreator` — derives from +NeoPZ's `TPZH1ApproxCreator`, one of the 5 delta files; `TPZMHMGeoMeshCreator`, `TPZMHMHDivApproxCreator`), custom H(div) elements with +duplicated connects (excluded from build), Schur-complement solvers (`TPZMatRedSolver` modes `EDefault/EDarcyHDiv/EDarcyH1Hybrid/EMHMSparse`, +`TPZSparseMatRed`). 8 built targets (`iter_elast`, `dupl_connects2`, `MHM_HDivConstant`, `dFreeBubbles1el`, `2frac`, `hpc4`, +`voronoi_mixed_elas`, `semiHybrid_elas`). `divfree_config.h` bakes absolute `MESHDIR`. Catch2 tests exist behind `BUILD_TESTS=OFF`. +Vertical slices selected for this assessment: see [[flow-iter-elast]] (mandated), [[flow-dupl-connects]], [[flow-mhm-hdivconstant]], +[[flow-dfreebubbles-1el]], [[flow-unit-test-hdiv-creator]] (pages created in Phase 2). + +## 8. Concepts queued for reference research (Phase 3) + +[[h1-space]], [[hdiv-space]], [[hcurl-space]], [[de-rham-complex]], [[mixed-methods]], [[hybridization]] (standard / squared / semi), +[[static-condensation]], [[mhm]], [[sbfem]], [[refinement-hanging-nodes]], [[geometric-mappings]], [[piola-transformations]], +[[quadrature]], [[assembly]], [[error-estimation-convergence]], [[vtk-output]]. + +## 9. Corrections & uncertainty ledger + +- C1 [fixed]: explorer report placed `pzcreateapproxspace.h` in `Mesh/`; actually `Pre/pzcreateapproxspace.h` [repo]. (`Mesh/pzcmesh.h:18` + includes it, which likely caused the confusion — and reveals the Mesh↔Pre coupling noted in §3.) +- C3 [fixed, Session 2]: Session-1 claims that `Material/needrefactor/` "still compiles into `pz`" were wrong — no `add_subdirectory(needrefactor)` exists and `libpz.dylib` contains none of its symbols [repo, verified by nm]. The Material row's 199h/178cpp counts include needrefactor *files on disk*, not compiled code. Residual risk = header/name shadowing + a few out-of-library targets including its headers. +- Open questions tracked in `wiki/log.md` (OQ1–OQ5): approx-space copy semantics, installed-build revision stamp, `[!shouldfail]` scope, + `voronoi_mixed_elas` null-`gAnalytic` suspicion, missing LICENSE. +- All `[agent]` claims above are treated as *located, pending re-verification*; they get promoted to `[repo]` (with line citations) as the + relevant phases touch them. diff --git a/ai-analysis/CPP_TECHNICAL_REVIEW.md b/ai-analysis/CPP_TECHNICAL_REVIEW.md new file mode 100644 index 000000000..41b789b8f --- /dev/null +++ b/ai-analysis/CPP_TECHNICAL_REVIEW.md @@ -0,0 +1,67 @@ +# NeoPZ C++ Technical Review + +**Phase 5 deliverable.** Objective C++/architecture review at `develop @ 6ffd38b12`. Sources: two targeted sweeps (ownership/lifetime/thread-safety; API/organization/build) with all high-severity claims re-verified first-hand, plus the Phase 1–4 traces. Every item: severity, evidence, why it matters, improvement + risk, and an **essential-vs-accidental** verdict. Finding pages under `wiki/findings/` carry full detail. + +Legend: severity H/M/L; [✓] = verified first-hand; [agent] = sweep-cited (line-checked spot sample). + +--- + +## 1. What is genuinely good (credit where due) + +- **The domain architecture is coherent and intentional**: gmesh/cmesh split, sides/topology layer, static shape classes, connect-based conformity, materials as weak-form objects — all traceable to the founding design ([[devloo-1997-pz-environment]]) and still load-bearing. Complexity here is **essential**. +- **The material mixin design** (`TPZMatBase`, verified) is a modern, disciplined solution to the "N physics × M capabilities" matrix; boilerplate for a new material is ~335 lines with clear pure-virtual surface [agent, walkthrough]. +- **Parallel assembly is real engineering**: OR = producer/consumer with single-writer scatter; OT = graph-coloring with atomic work index + condition-variable ordering and lock-free concurrent scatter (safe by coloring) [agent, lines cited]. Per-thread `TPZMaterialData` scratch is correctly isolated [✓ via pzinterpolationspace.cpp:480 pattern]. +- **`override` discipline (3757 uses), `[[nodiscard]]` (150), `std::function` callbacks** (the factory table and SetExact are already modern) [agent counts]. +- **Header-level Doxygen coverage on core public APIs is good (~70–90%)** [agent sampling]; docs pipeline (Doxygen+Sphinx→gh-pages) exists. +- **Persistence design** (ClassId + chunk translators) is elaborate and versioned — unusual for research codes. + +## 2. High-severity findings (all accidental complexity) + +| # | Finding | Evidence | Why it matters | +|---|---------|----------|----------------| +| H1 | **`DebugStop()` throws messageless `std::bad_exception` unconditionally — also in Release** (guard commented out) | [✓ Common/pzerror.cpp:15-28]; ~3029 call sites vs ~9 `catch` [agent] | The de-facto assertion mechanism gives production users a terminate with no diagnostic beyond a cerr line; guards can't be distinguished from fatal invariants; 51 `throw` vs 3029 DebugStop shows exceptions aren't the real strategy. → [[finding-debugstop-throws-release]] | +| H2 | **`pztopology::gTolerance` is a header-scope `static`** → one copy per TU; `SetTolerance()` mutates only TPZTopologyUtils.cpp's copy | [✓ Topology/TPZTopologyUtils.h:23]; readers in other TUs incl. header default args [agent] | Geometry point-location tolerance silently inconsistent across translation units; the commented-out singleton above it shows the intended fix was known. → [[finding-global-state-cluster]] | +| H3 | **GeoMesh→CompMesh dangling on the common path**: `~TPZCompMesh` clears the peer's back-pointer, `~TPZGeoMesh` does not; `SetReference(TPZGeoMesh*)` deliberately drops the owning autopointer | [✓ pzgmesh.cpp:97-103; pzcmesh.cpp:181-186; pzcmesh.h:772-773] | Destroy order becomes a correctness rule the compiler can't check; the co-ownership overload exists but is opt-in. → [[finding-mesh-lifetime-ownership]] | +| H4 | **Materials are shared mutable objects invoked concurrently through non-const `Contribute`** during OR/OT parallel assembly | [✓ TPZMatSingleSpace.h:112-114; agent: pzstrmatrixor.cpp:624, pzstrmatrixot.cpp:732, pzinterpolationspace.cpp:522] | Thread-safety rests on an unenforced "materials must be stateless in Contribute" convention; a single cached member = silent data race. Const-qualifying `Contribute/Solution` would make the existing invariant compiler-checked. → [[finding-thread-shared-materials]] | +| H5 | **Build-config macro gaps**: default `RelWithDebInfo` matches neither `$` (PZNODEBUG) nor `$` (PZDEBUG); 14 dead `#ifdef DEBUG` blocks (wrong macro); no `-Wall/-Wextra` anywhere; Xcode warnings explicitly silenced | [✓ CMakeLists.txt:84-90; ✓ TPZCompElHDivDuplConnects.cpp:62; ✓ grep counts] | The recommended default build silently disables both the debug checks *and* the release fast-paths; 14 real consistency checks never compile in any config; warnings that would catch the above are off. → [[finding-build-config-gaps]] | + +## 3. Medium severity + +- **M1 Layering is aspirational, not enforced** — single `pz` target; `add_subdirectory` order is decorative; 6 verified backward include edges (`Mesh→Pre` [✓ pzcmesh.h:18], `Geom→Mesh`, `Analysis→StrMatrix`, `Material(needrefactor,Plasticity)→Mesh`, `Refine→Mesh`, Solvers-before-Matrix order inversion) [agent]. Mesh⇄Pre is a genuine module-level cycle putting the two heaviest core headers in one recompilation SCC. *Essential?* No — the layer *concept* exists; enforcement is absent. Improvement: acyclic include lint in CI, forward-declare `TPZCreateApproximationSpace` in `pzcmesh.h`; cost low, risk low. +- **M2 Raw-owning members without copy control**: `TPZAnalysis::fSolver` raw owner + no deleted copy ⇒ double-delete on copy of any concrete analysis [agent, ctor/dtor lines]; contrast `fStructMatrix` already `TPZAutoPointer`. Improvement: delete copies or hold via autopointer; trivial, low risk. +- **M3 Ownership monoculture**: 963 `new TPZ*` sites; `TPZAutoPointer` (758, atomic refcount [✓ earlier]) vs `std::unique_ptr` **0**, `weak_ptr` 0 [agent counts]. Unique ownership is always raw `new`+manual `delete`; cycles (gmesh↔cmesh) can't be expressed safely. *Partly essential* (predates C++11; consistent house style), but new code keeps inheriting the hazard. +- **M4 `NConnectShapeF` per-family dispatch duplicated across 14 element .cpp files** with drift; formula centralized in Shape but the switch wrapper is copy-paste [agent]. Adding a family = copy 7 overrides + creator plumbing (~500 lines) rather than extend a hook. *Essential-ish* variability, *accidental* duplication. +- **M5 Global mutable state on active paths**: `gRefDBase` (refinement pattern DB, mutated by Initialize*/Insert/clear) blocks concurrent adaptivity and makes tests order-dependent; `gSinglePointMemory`; legacy per-material statics in `needrefactor/` (non-reentrant `gCurrentEq`) [agent]. → [[finding-global-state-cluster]] +- **M6 Installed `pz_config.h` bakes absolute build-machine paths** (`PZSOURCEDIR`, `PZ_REFPATTERN_DIR`) → non-relocatable installs; scalar-type macros are ABI-affecting globals [agent; consistent with observed install]. Improvement: runtime resolution/install-relative; medium effort. +- **M7 No symbol-visibility control on the shared lib** (everything exported; no PZ_API macro) [agent]. Larger ABI, slower links, zero encapsulation; standard `GenerateExportHeader` fix, medium effort (touching public headers). +- **M8 `Material/needrefactor/` legacy island — CORRECTED (Session 2, ledger C3)**: 19+108 files [✓ count], duplicate physics (two `TPZMixedDarcyFlow`s), old naming, the reentrancy statics. It does **not** compile into `pz` (no `add_subdirectory`; zero symbols in `libpz.dylib` [✓ nm]). Remaining risk is include-path shadowing of duplicate class names, plus out-of-library targets (SubStruct, PerfTests, Publications, TestCondensedElement) that include its headers. Severity drops M→L for the library proper; the retirement item in the roadmap becomes "delete/relocate headers + fix downstream includes" rather than a build-target carve-out. + +## 4. Low severity / hygiene + +- Four template-impl conventions coexisting (`.h.h` ×4 [✓], `_impl.h` ×5, inline-in-header, explicit-instantiation ×96 files) — standardize on `_impl.h`; L. +- Include-guard chaos (3 styles; generic `ANALYSISH` collision-prone guard) vs 7 `#pragma once`; L. +- Two naming eras `pz*`/`TPZ*` ~50/50 in Mesh/Matrix/Shape with filename↔class mismatch systemic in the old era (`pzcmesh.h`→`TPZCompMesh`); onboarding tax; L (rename churn risk high — recommend new-code-policy only). +- Self-assignment guards missing in `CopyFrom` family (`TPZMatRed` [✓]; patched post-pin in `TPZSYsmpMatrix`) ; L. +- `TPZCreateApproximationSpace` copy ops drop family flags ([[finding-approxspace-copy-drops-families]], verified) + `const void` setter signatures; L→M if a clone path is live. +- Approx-creator hygiene cluster (tautological guard, mis-scoped if, stubs, dead Backup/UnitaryLagrange machinery) — verified, [[finding-approx-creator-hygiene]]; L. +- Persistence coverage decay: elaborate machinery, one round-trip test (Phase 7 angle); L here. +- Docs miss the modern entry point: zero prose for `TPZ*ApproxCreator`; getting-started funnel leaves the tree (README → NeoPZExamples) [agent]; L→M for adoption. + +## 5. Essential vs accidental — the honest split + +**Essential (do not "simplify" without domain expertise):** sides/topology combinatorics; per-topology templates + explicit instantiation; hierarchical shape composition and its orientation protocol; multiphysics atomic-mesh + Lagrange-level condensation machinery; the variadic material mixins; swappable scalar types (`REAL/STATE`, FAD); refinement-pattern database concept. +**Accidental (fixable without touching the math):** everything in §2; the layering non-enforcement; ownership conventions; naming/guard/template-impl inconsistency; dead code (needrefactor, Backup paths, `#ifdef DEBUG`); build hygiene. Notably, the five H items are all in this category — the mathematical core is in better shape than the surrounding engineering. + +## 6. Extensibility verdict (evidence-based) + +Adding a **material**: well-designed path, moderate boilerplate (~335 lines), persistence registration only [agent walkthrough]. Adding a **solver**: small surface (3 overrides) [agent]. Adding an **element family**: the weak point — 7+ overrides plus copy-paste dispatch plus creator/factory plumbing across `Pre/pzcreateapproxspace` and creators (~500 lines, duplication-driven) [agent + Phase 4 traces]. The app repo (divfreebubbles) demonstrates the real extension workflow: derive creators, add materials, wrap solvers — workable, but same-name classes migrating app→lib (`TPZMHMHDivApproxCreator` in both) show the extension boundary is porous ([[divfree-support-lib]]). +**Session-2 corroboration across five more apps** ([[apps-overview]]): ~20 downstream material subclasses vs exactly one computational-element subclass (GFEM's `TPZCompElH1` override — which shows *modifying* a family via the `ComputeShape` seam is cheap even though *adding* one is not); two custom StrMatrix/matrix pairs and three independent MatRed reimplementations (the recurring gap); more same-name migrations observed (`TPZMixedElasticityND`, `TPZHybridElasticity2D`, `TPZSparseMatRed`) — the porous-boundary risk is systemic, not a divfreebubbles quirk. + +## 7. Priority recommendations (cost/risk-annotated) + +1. **H5 build-config triad** (RelWithDebInfo macro case, `DEBUG`→`PZDEBUG` rename, `-Wall -Wextra` in CI): hours of work, near-zero risk, immediately surfaces latent defects. Do first. +2. **H1 DebugStop**: introduce `TPZFatal(file,line,msg)`-style typed exception or abort-in-debug; mechanical replacement; low risk, high diagnostic payoff. +3. **H4 const-Contribute**: API-breaking but mechanical (derived overrides updated by compiler errors); pairs naturally with a thread-safety doc note. Medium churn, high invariant value. +4. **H2/H3/M2/M5**: small, local, high-value lifetime/global-state fixes. +5. **M1 layering lint + Mesh⇄Pre forward-decl**: cheap guardrail preventing further erosion. +6. Defer: renames (L), visibility macros (M7) until an ABI-break release window. diff --git a/ai-analysis/DOMAIN_PRIMER.md b/ai-analysis/DOMAIN_PRIMER.md new file mode 100644 index 000000000..7a82c9c3f --- /dev/null +++ b/ai-analysis/DOMAIN_PRIMER.md @@ -0,0 +1,83 @@ +# NeoPZ Domain Primer + +**Phase 3 deliverable; extended in Session 2 (2026-07-06).** Practical explanations of the FEM concepts the repository actually uses, each split into *reference evidence* (established theory, → `wiki/sources/`) and *repository evidence* (what NeoPZ demonstrably does at `develop @ 6ffd38b12`). Concept detail pages: `wiki/concepts/`. +Session-1 sections (§1–§9, §13) centered on the mixed/hybrid H(div) axis exercised by divfreebubbles. Sections §10–§12 (Session 2) restore the balance: the other element families as *code structures*, the eigen/complex/SBFem side of the library, and what five further downstream applications reveal about how the library is actually used (`wiki/apps/`). + +## 1. The space zoo and why NeoPZ is unusual + +Reference: conforming FEM needs function spaces matched to the operator — H1 (continuous traces) for primal problems, H(div) (continuous *normal* traces) for fluxes/stresses, H(curl) (continuous *tangential* traces) for EM, L² (no continuity) for pressures/multipliers ([[boffi-brezzi-fortin-2013]]). + +NeoPZ does **not** implement the textbook RT/BDM/Nédélec families. It implements the Devloo-group *hierarchical* construction: pick geometry-based vector fields per element, multiply by hierarchical H1 scalars → vector bases whose normal (H(div)) or tangential (H(curl)) interface components are continuous **by construction** ([[devloo-group-shape-construction]], JCAM 2013). Repo: `Shape/TPZShapeHDiv*.h`, `TPZShapeHCurl*.h` compose exactly this way (structure verified; deep trace Phase 4); per-connect orders make hp native ([[shape-functions]]). + +Flavors at the pin [repo `Shape/TPZEnumApproxFamily.h:5-11`]: `HDivFamily {EHDivStandard, EHDivConstant, EHDivKernel, EHDivOptimized}`, `H1Family {EH1Standard, EH1WidePrism}`, `HCurlFamily {EHCurlStandard, EHCurlNoGrads}`. Published context: multiple H(div) types with different internal enrichment and divergence accuracy are a *deliberate research axis* ([[devloo-hdiv-variants-accuracy]]) — reviewers should treat flavor-specific surprises as candidate intentional variants, not bugs, until traced. + +## 2. De Rham compatibility as the house correctness criterion + +Reference: the discrete sequence H1 →grad→ H(curl) →curl→ H(div) →div→ L² should be exact for stable mixed pairs (FEEC; [[boffi-brezzi-fortin-2013]] Ch.2.5). +Repo: NeoPZ *tests this directly* — `UnitTest_PZ/TestDeRham` builds Gram matrices of `op(φ)` and checks `rank(M_left) = ker(M_right)` plus range-inclusion via SVD, dims 2/3, k=1..3, incl. the `HDivConst` flavor [repo TestDeRham.cpp:49-120]. Mesh-level De Rham checks incl. face-permutation invariance live in `TestMesh/TestHDiv.cpp`. This is a strong, unusual, in-repo validation asset ([[de-rham-complex]]). What it does *not* establish: commuting-diagram/interpolation properties, curved-element exactness — Phase 7 records these as gaps, not failures. + +## 3. Mixed methods and multiphysics plumbing + +Reference: saddle-point problems need inf-sup-compatible pairs; payoffs are local conservation and direct flux/stress fields ([[boffi-brezzi-fortin-2013]] Ch.4-5). +Repo: one `TPZCompMesh` per field (flux, pressure, …) combined into `TPZMultiphysicsCompMesh`; combined-space materials (`TPZMatCombinedSpacesT`) evaluate the coupled weak form; `TPZHDivApproxCreator` builds Darcy/elasticity pairs by `ProblemType` ([[mixed-methods]], [[approx-space-creators]], [[material-system]]). The De Rham-compatible H(div)×L² pairing is the group's standard trick to keep divergence-consistency exact. + +## 4. Hybridization: the repo's central research axis + +Reference: hybridization breaks a continuity and re-imposes it with skeleton Lagrange multipliers; local problems condense to an SPD skeleton system ([[cockburn-2009-unified-hybridization]]). +Repo taxonomy [Pre/TPZApproxCreator.h:15]: `ENone | EStandard | EStandardSquared | ESemi`, orchestrated with wrap/interface/Lagrange material ids (`HybridizationData`). +- **EStandard** ≈ classic single-level hybridization. +- **EStandardSquared** ("double hybrid"): second hybridization level — traced in Phase 4 as a literal hybridization² of the **broken-H1 primal space** (second interface/multiplier layer; only the 2nd-level skeleton stays global). The published double-hybrid elasticity paper ([[avancini-2025-double-hybrid-elasticity]], CMAME 2025) uses H(div)–L² displacements/pressure — the in-code H1 path is a *structurally matching primal variant*, not a verbatim implementation of that paper (classification: intentional variant; exact correspondence = expert question). Exercised by the mandated slice [[flow-iter-elast]] (`TPZH1HybridApproxCreator`, elasticity). +- **ESemi** (semi-hybridization): only *part* of the interface coupling moves to multipliers — H(div) normal continuity stays strong, tangential (or a designated subset) goes weak; realized via duplicated connects ([[carvalho-2024-semi-hybrid-stokes]], IJNME 2024; `TPZCompElHDivDuplConnects*`). Exercised by [[flow-dupl-connects]]. +Mapping code↔paper is **hypothesis-level until Phase 4** (recorded on both source pages). + +## 5. Static condensation, rigid-body spaces, and Schur solvers + +Reference: eliminate interior DOFs per element/patch; needs invertible interior blocks; skeleton system stays SPD for symmetric problems. +Repo: `TPZCondensedCompEl`/`TPZElementGroup` wrap elements; connect "Lagrange levels" order what is condensable; `fIsRBSpaces` enriches with constants/rigid-body fields precisely so interior blocks *become* invertible (needed for total condensation with `EHDivConstant`) [[static-condensation]]. Downstream, the app repo drives reductions iteratively: `TPZMatRedSolver` (Schur complement on the multiplier/BC block, modes per problem family) over lib-side `TPZMatRed`-style containers ([[divfree-support-lib]], [[matrix-and-solvers]]). + +## 6. MHM — multiscale hybrid-mixed + +Reference: [[araya-2013-mhm]] (SINUM 2013): coarse-skeleton multipliers + independent fine local problems per coarse cell; locally conservative dual variable; per-subdomain constant/rigid-body kernels become the coarse unknowns. +Repo: two generations (older `TPZMHM*MeshControl`, newer `TPZMHM*ApproxCreator` — in *both* the library and the app repo, same class name!). Slice [[flow-mhm-hdivconstant]]: polygonal coarse cells from a quadtree file, triangulated around scaling centers, `EHDivConstant` + rigid-body spaces + `PutinSubstructures`/`CondenseElements` (`TPZSubCompMesh` = the local-problem container). Elasticity-on-polygons variant published by the group ([[devloo-mhm-elasticity-polygonal]]). + +## 7. Geometry: master elements, sides, curved maps, and the mapping question + +Reference: FE integrals pull back through the element map; *vector* bases additionally need Piola-type transforms — contravariant for H(div), covariant for H(curl) — especially on non-affine/curved elements ([[boffi-brezzi-fortin-2013]] Ch.2). +Repo: topology layer (`Topology/`, "sides" with permutation machinery) → geometry maps (`Geom/`, blend maps, `SpecialMaps/` exact curved geometries) → `axes`-based gradient frames (2D elements embeddable in 3D). **Where/how the Piola step happens is deliberately left open** ([[piola-transformations]]) — the group has published on H(div) for curved meshes ([[devloo-hdiv-variants-accuracy]]), so the convention is a documented variant to be traced, not presumed textbook. Phase 4 must locate the transform in `TPZCompElHDiv::ComputeRequiredData`/shape drivers before any correctness claim. + +## 8. Refinement, hanging nodes, hp + +Reference: nonuniform h-refinement produces hanging DOFs constrained to coarse neighbors; hp needs per-entity orders and side-order compatibility. +Repo: *runtime-defined refinement patterns* (71 `.rpt` data files + `TPZRefPattern` database) — a distinctive NeoPZ capability [README + Refine/]; constraints live in `TPZConnect` dependency matrices resolved at assembly ([[refinement-hanging-nodes]]); per-connect orders come free with hierarchical shapes ([[hp-adaptivity]]). Unit tests cover hanging nodes and constrained spaces; H(div)/H(curl)-under-refinement coverage is a Phase 7 question. + +## 9. Assembly, solvers, output + +Repo pipeline (verified across five slices, [[flow-iter-elast]] etc.): `TPZLinearAnalysis` → `TPZStructMatrix` flavor (storage × parallel scheme × equation filter) → per-element `CalcStiff` → material `Contribute` per quadrature point → connect-indexed scatter → `TPZStepSolver` direct (ELDLt/Cholesky/LU, in-house or MKL/Pardiso/MUMPS) or Krylov (CG/GMRES with block/Jacobi preconditioners) ([[assembly]], [[structural-matrices]], [[matrix-and-solvers]], [[TPZAnalysis]]). +Output: modern `TPZVTKGenerator` (legacy-format .vtk, element subdivision by `vtkRes`, NGSolve-derived) + legacy graph-mesh writers; error path `SetExact` → `PostProcessError` with material-defined norms ([[vtk-output]], [[error-estimation-convergence]]). + +## 10. The element families as code structures (Session 2) + +The mathematical space zoo of §1 maps onto four *structurally different* element designs ([[element-families]], line-cited): +- **H1** (`TPZCompElH1`): one connect per topological side *including corners*; conformity by connect sharing; corner connects order-1; hanging nodes via the generic scalar restraint. `H1Family` matters only for prisms, resolved at element creation (template choice), never branched at runtime. +- **H(curl)** (`TPZCompElHCurl`): no vertex connects; `HCurlFamily` is a live runtime switch (Standard vs NoGrads); **covariant** Piola in `TransformShape` (`axesᵀ·J⁻ᵀ`), curl mapped separately; orientation *implicit* via corner-node-id transform ids — contrast H(div)'s explicit `fSideOrient` signs. Pyramid/point unavailable (DebugStop). +- **Discontinuous** (`TPZCompElDisc`): a single connect for the whole element, modal basis about the element center, appendable external shape functions (the enrichment hook), no restraints — continuity, when wanted, is weak via interface elements. +- **L² in mixed meshes is two things**: broken-H1 (p>0; continuous factory + build-time reference resetting) or true `TPZCompElDisc` (p=0, and always for `EHDivConstant`). There is no `EDisconnected` flag; the disconnection is procedural ([[discontinuous-l2-dg]]). +- **DG is compositional**: discontinuous space + `CreateInterfaceElements` + a material implementing the interface mixins — the same interface machinery hybridization uses; no monolithic DG creator exists. + +The DOF layer beneath all of them ([[TPZConnect]]): dependencies are L2 projections of coarse traces (built by `RestrainSide` from geometric side transforms), applied per element with a complex-correct congruence transform; Lagrange *levels* order global numbering via `SaddlePermute`; condensed and dependent are mutually exclusive states. Composition layers ([[condensation-groups-submeshes]]): ElementGroup (sum) → CondensedCompEl (per-group Schur via TPZMatRed) → SubCompMesh (a mesh that *is* an element; rigid-body-mode-aware reduction) — the substructuring ladder MHM stands on. + +## 11. Eigenproblems, complex scalars, SBFem (Session 2) + +The library's second personality, invisible from the Darcy/elasticity axis: `Material/Electromagnetics/` is entirely **CSTATE** (complex) — waveguide modal analysis (`TPZWgma`, `TPZAnisoWgma`, `TPZPeriodicWgma`), scattering with integration-point-memory sources, and a PML *decorator template* `TPZMatPML` over any host material. These feed generalised (A/B) and quadratic (K/L/M) eigen mixins consumed by `TPZEigenAnalysis`/`TPZQuadEigenAnalysis` over a real solver stack: LAPACK dense, Krylov/Arnoldi with spectral transforms (shift, shift-and-invert), quadratic-EVP solver ([[matrix-and-solvers]]). **SBFem** ([[sbfem]]) assembles per-group E0/E1/E2 matrices into a 2n×2n block Hamiltonian and solves the non-symmetric eigenproblem directly with LAPACK `dgeev_` (bypassing the solver stack); it is the only in-tree suite with genuine convergence-*rate* tests, and downstream it doubles as a *generator of singular basis functions* for GFEM enrichment. + +## 12. How the library is used downstream (Session 2, five-app survey) + +Full survey: `wiki/apps/` ([[apps-overview]]). The one-paragraph version: NeoPZ downstream research spans saddle-point solver methodology (Uzawa loops over cloned/mutated Pardiso matrices), GFEM fracture enrichment (subclassed H1 elements + connect-keyed enrichment maps), reconstruction-based a-posteriori estimation with closed hp-adaptive loops, dimensionally heterogeneous (3D/2D/1D) coupled flow via hand-programmed connect dependencies, and tensor-valued mixed elasticity with weak/strong symmetry up to 7-field multiphysics plus MHM controllers. Patterns to internalize: manual space construction is first-class API (all five use it); the connect/dependency layer is a public research surface; MatRed-style block reduction recurs independently in three repos; refinement patterns triple as adaptivity, grading, and macro-element construction devices; material subclassing absorbs almost all extension needs. H(curl) and complex scalars appear in *none* of the five — that usage lives in the electromagnetics materials/tests and older downstream lines. + +## 13. Reviewer's caution list (from Phase 3; all items still apply) + +1. NeoPZ families ≠ textbook families — compare *properties* (traces, exactness, orders), never DOF layouts. +2. Hybridization taxonomy is a research frontier here (squared/semi) — papers exist but code may lead or lag them; classify mismatches per the 5-way scheme. +3. Flavor knobs (`HDivFamily`, `fExtraInternalPOrder`, RB spaces) intentionally change accuracy orders — "wrong-looking" convergence may be the documented behavior ([[devloo-hdiv-variants-accuracy]]). +4. The De Rham tests are rank-level; don't over-claim what they prove. +5. Benchmarks in the app repo validate performance only (error/VTK legs disabled) — correctness evidence lives in unit tests + dFreeBubbles1el ([[flow-dfreebubbles-1el]]). diff --git a/ai-analysis/EXECUTION_FLOWS.md b/ai-analysis/EXECUTION_FLOWS.md new file mode 100644 index 000000000..8fdf7eb0f --- /dev/null +++ b/ai-analysis/EXECUTION_FLOWS.md @@ -0,0 +1,46 @@ +# NeoPZ Execution Flows + +**Version 1 (Phase 2 — shallow discovery).** Deepened in Phase 4. Analyzed commit `develop @ 6ffd38b12`; app repo `../divfreebubbles @ 3DKernelHdiv`; runtime binaries link installed NeoPZ stamped `852a5116c` (`neopz_install/pz/include/Common/pz_config.h` [repo]). +Full per-slice pages: `wiki/flows/`. +**Session-2 scope note:** the five slices below are all divfreebubbles/unit-test flows (HDiv/hybridization-weighted). Statically traced flow *sketches* from five further downstream apps — adaptive estimator loops, GFEM enrichment builds, Uzawa outer iterations, 3D/2D/1D coupled builds, MHM-controller elasticity — now live in `wiki/apps/` (one page per app + [[apps-overview]]); they were not executed, so they carry app-repo evidence class, not [run]. + +## The canonical NeoPZ pipeline (as observed across all five slices) + +``` + geometry spaces physics system solve output +TPZGeoMesh ──────► TPZCompMesh / TPZMultiphysicsCompMesh ──────► TPZMaterial+BCs ──► TPZLinearAnalysis ──► StepSolver/ ──► VTK writers / +(GmshReader, (ApproxSpace factory or (per matid, + TPZStructMatrix Schur(MatRed)/ PostProcessError + GenGrid, Tools) TPZ*ApproxCreator [+hybridize, weak form) (storage+threads) Pardiso/MUMPS (SetExact) + +condense, +substructure]) +``` + +Two space-construction idioms coexist: +- **Manual** (older, `flow-dfreebubbles-1el`): per-field cmeshes with `TPZNullMaterial` placeholders + `ApproxSpace().SetAllCreateFunctions*` + `AutoBuild`, combined via `TPZMultiphysicsCompMesh`; even fully manual per-element `new TPZCompElKernelHDiv<...>` with neighbor-walking for wrap elements. +- **Creator-driven** (current, all other slices): `TPZHDivApproxCreator`/`TPZH1ApproxCreator` (+MHM/app-side derivatives) encapsulating multi-mesh construction, hybridization (`ENone/EStandard/EStandardSquared/ESemi`), rigid-body enrichment and condensation. + +## Slice summaries + +| Slice | Problem | Space idiom | Solve | Output legs | Page | +|---|---|---|---|---|---| +| iter_elast (mandated) | 2D hybrid-squared H1 elasticity, analytic homogeneous | app-side `TPZH1HybridApproxCreator` + orthogonalizing restraints + low-order-flux hybridization + group/condense | `TPZMatRedSolver(EDarcyH1Hybrid)` Schur vs direct MKL/MUMPS LDLt, 32 thr | timing+memory tables only (error/VTK commented) | [[flow-iter-elast]] | +| dupl_connects2 | 2D/3D mixed Darcy, `EHDivConstant` | lib `TPZHDivApproxCreator`, `ESemi`, condense=on | `TPZMatRedSolver(EDarcyHDiv)` vs direct | timing tables (error/VTK commented) | [[flow-dupl-connects]] | +| MHM_HDivConstant | Darcy on polygonal partition (quadtree import) | app-side MHM geo+approx creators, rigid-body on, substructures + condense | direct LDLt (ESemi/`EMHMSparse` branch = dead & **drifted**) | cmesh-as-VTK + txt dumps (always-on debug) | [[flow-mhm-hdivconstant]] | +| dFreeBubbles1el | Darcy on 1-element gmsh mesh | manual flux+pressure meshes, factory `SetAllCreateFunctionsHDiv` | direct LDLt | **error computation + multiphysics VTK active** | [[flow-dfreebubbles-1el]] | +| Unit tests | linear/constant representation grid; De Rham rank/kernel | lib creators incl. lib MHM creator; basis-level Gram matrices | direct / SVD (LAPACK) | Catch2 assertions (+VTK smoke) | [[flow-unit-test-hdiv-creator]] | + +## Cross-slice observations (feeding Phases 4–7) + +1. **The 5-file develop delta sits on the hot path of the mandated slice**: `TPZH1ApproxCreator` (base of the app creator) and `TPZHybridElasticity2D` (material). Runtime evidence must carry the `[run @ 852a5116c]` label (install stamp; possibly stale vs dylib rebuild — nuance logged). +2. **Solver-mode naming mismatch**: iter_elast passes `EDarcyH1Hybrid` for an elasticity problem though `EElasticityH1Hybrid` exists (`divfree/TPZMatRedSolver.h:15`) — either the reduction structure is problem-agnostic (naming debt) or a real mis-selection → Phase 4 must read `TPZMatRedSolver::Solve`. +3. **App-repo source drift**: `MHM_HDivConstant` references removed enumerator `EMHMSparse`; current tree likely doesn't rebuild that target (binary is Mar 27). OQ6. +4. **Benchmark-first hygiene**: error/VTK legs are commented out in the two benchmark drivers; analytic lambdas left inconsistent (3D solution in 2D runs; forcing not matching exact solution; dead assignments inside lambdas). These are app-side, not library, issues — but they mean **the benchmarks currently validate performance, not correctness** (correctness legs live in dFreeBubbles1el + unit tests). +5. **Renumbering disabled** (`RenumType::ENone`) in both benchmarks — deliberate for the Schur solver? Bandwidth effects on direct path? → Phase 6 question. +6. **Same-name classes in lib and app** (`TPZMHMHDivApproxCreator` in `Pre/` and in `divfree/`) — which one a target gets depends on include paths; migration-in-progress pattern → Phase 5 risk note. +7. **Outputs land in CWD** across drivers (results txt, mphysics2.txt, cmesh_multi.vtk, gmesh.vtk) — any run of these binaries must use a scratch CWD (engagement rule already in place). + +## What each output means (v1 + Phase 4 run evidence) + +- `results_*_memory_time.txt`: ` ` — confirmed by a fresh run [run @ 852a5116c(+), 2026-07-02]: for `iterative` rows t1 = SparseMatRed assembly (stdout "Time Assembling SparseMatRed 78 ms" ↔ t1=78), t2 ≈ K00 decomposition + CG; `mem` = `ru_maxrss/1024` — **KiB on macOS mislabeled as MB** (1024× overstatement; correct on Linux) → [[finding-rusage-memory-units]]. +- Run anatomy (iter_elast, p=1, 50²): 168,200 full eqs → 19,600 condensed → split "High Order Flux" 4,900 + "Linear Flux" 14,700; K00 factorized; **CG converges in 19 iterations at 50² and at 400²** (mesh-independent count, contraction ≈0.3/iter) — strong empirical robustness signal for the reduction; mechanism documented after the MatRedSolver trace. +- `postprocessHdiv.txt` (1el): `TPZAnalysis::PostProcessError`-style norms vs the (effectively linear) exact solution — indices/norms documented in Phase 4. +- `cmesh_multi.vtk` / `gmesh.vtk`: geometric visualization (mesh + matids/partition), not solution fields. diff --git a/ai-analysis/FINDINGS_AND_ROADMAP.md b/ai-analysis/FINDINGS_AND_ROADMAP.md new file mode 100644 index 000000000..1fc5e697a --- /dev/null +++ b/ai-analysis/FINDINGS_AND_ROADMAP.md @@ -0,0 +1,64 @@ +# NeoPZ Findings & Roadmap + +**Phase 6 deliverable (performance & scalability) + consolidated roadmap (finalized in Phase 9).** Evidence at `develop @ 6ffd38b12`; runtime data `[run @ 852a5116c(+)]` from the instrumented iter_elast sweeps (this engagement) — see `EXECUTION_FLOWS.md` and `wiki/findings/`. + +--- + +## A. Performance & scalability review + +### A1. Measured behavior (first-party evidence) + +2D hybrid-squared elasticity, p=1, quad meshes n×n [run, same machine, Release library build]: + +| n | eqs (condensed) | Schur t1/t2 (ms) | Direct assemble/solve (ms) | CG iters | +|---|---|---|---|---| +| 50 | 19,600 | 78 / 75 | 81 / 69 | 19 | +| 100 | 79,200 | 250 / 247 | 278 / 472 | — | +| 200 | 318,400 | 1,043 / 992 | 1,097 / 1,769 | — | +| 300 | 717,600 | 2,746 / 2,449 | 2,671 / 3,989 | — | +| 400 | 1,276,800 | 4,949 / 4,718 | 5,302 / 7,851 | 19 | + +Readings: (i) **CG iteration count is mesh-independent (19 at both extremes)** — the K00-reduction acts as a robust preconditioner for this family; (ii) iterative t2 scales ≈ linearly in DOFs while direct solve grows superlinearly (69→7,851 ms ≈ n^1.14 in DOFs) — crossover before 100²; (iii) assembly ≈ linear and nearly identical in both paths (it is the same assembly); (iv) inside t2 at 400², K00 Cholesky dominates (3.4 s of 4.7 s) → further gains live in the K00 factorization, not CG. +Caveats: single machine; p=1 only; memory column of the app's tables is platform-distorted ([[finding-rusage-memory-units]]); the elasticity sweep ran with the Darcy-shaped preconditioner ([[finding-matred-solver-mode-mislabel]]) — true elastic-block numbers may differ. + +### A2. Architecture-level performance properties + +- **Assembly parallelism is real and layered**: OR (single-writer consumer) vs OT (coloring, lock-free scatter) vs OMP/TBB variants ([[structural-matrices]]). Parallel==serial is unit-tested. Tradeoff: OR serializes scatter (bottleneck at high thread counts); OT pays coloring precompute + condvar ordering. No benchmark in-tree currently quantifies the crossover (PerfTests stale). +- **Hot-path virtual dispatch is consciously split**: shape functions are static non-virtual per-topology classes (documented as a performance decision); materials *are* virtual per integration point — inherent to the extensible-material design; element `CalcStiff` virtual per element. This is the conventional FEM tradeoff; no evidence it dominates (assembly ≈ linear and matches the direct path). +- **Memory layout**: chunked vectors (`TPZAdmChunkVector`) give pointer stability at the cost of contiguity; `TPZFMatrix` column-major dense; `TPZManVector`/`TPZFNMatrix` small-buffer optimizations pervasive in element code — good. Sparse = CSR (sym/nonsym) with Pardiso/MUMPS backends. +- **Solver stack**: in-house skyline/Cholesky/LDLt for small-mid problems; MKL Pardiso / MUMPS for sparse direct; CG/GMRES + Jacobi/block/element preconditioners; eigen via Arnoldi/Krylov + LAPACK. The app-side `TPZSparseMatRed` shows the intended scalable pattern (factor small K00 blocks, iterate on the skeleton complement). +- **Scalability ceiling: shared-memory only.** No MPI anywhere; SubStruct/BDDC (Dohrmann) exists but is dormant (perf tests self-described as needing revision; not in CI). METIS optional for ordering only. For the group's problem sizes (10⁶–10⁷ DOFs observed) shared-memory + MUMPS/Pardiso is adequate; beyond that there is no distributed path. +- **Renumbering**: Sloan/Cuthill-McKee/Metis available via `RenumType`; benchmarks run `ENone` deliberately because `TPZSparseMatRed::ReorderEquations` imposes its own Lagrange-level ordering — coherent, but means the *direct* baseline in those same runs is unrenumbered (its fill could improve; the comparison slightly favors the iterative path) — worth one control run [suggested]. + +### A3. Build/compile performance + +Single 35 MB dylib; 96 explicit-instantiation TUs; heaviest headers concentrated in Plasticity/needrefactor but core `pzcompel.h`/`pzcmesh.h` (800+ lines each) sit inside the Mesh⇄Pre include SCC → wide recompiles on core edits. No PCH, no unity builds, no ccache integration (CI uses ccache actions externally). Low-risk wins available; matters for iteration speed more than runtime. + +### A4. Performance-infrastructure gaps + +- `PerfTests/` stale (2021/2024 touches; own README: "in need of a revision"); not wired to CI; no regression tracking of assembly/solve times. The CDash config is legacy. +- No profiling hooks beyond `TPZSimpleTimer`/`TPZTimer`; LIKWID/PAPI options exist but ungated by any maintained target. +- The benchmark drivers that *do* exist (divfreebubbles) have the two measurement bugs found in Phase 4 (memory units, preconditioner mislabel) — i.e., current published-table pipelines carry avoidable noise. + +### A5. Suggested improvements (each with tradeoff) + +1. **Revive one thin perf CI job** (assemble+solve a fixed 2D/3D Darcy + elasticity case, OR vs OT vs serial, JSON output): catches regressions; cost = CI minutes; risk ≈ 0. Highest value/effort ratio. +2. **Fix the two benchmark-instrumentation bugs** (units, mode) before the next paper run; trivial. +3. **One control run with renumbering on** for the direct baseline; if fill improves materially, report both. +4. **K00 factorization**: at 400², 72% of t2 — try MUMPS BLR / Pardiso two-level or reuse symbolic factorization across the sweep (same sparsity each idiv? no — mesh changes; but across pOrders it repeats). Medium effort, needs measurement first. +5. **PCH/unity for Mesh+Material** and breaking the Mesh⇄Pre SCC: build-time win, low runtime risk. +6. **Do not** micro-optimize material virtual calls or replace chunk vectors on speculation — no evidence they dominate; measure first (premature-optimization risk flagged). + +--- + +## B. Consolidated findings register (running; final ranking in Phase 9) + +**Library (NeoPZ) — correctness/API:** [[finding-hybridelasticity2d-missing-rhs-at-pin]] (major, fixed upstream) · [[finding-hdivconstant-fad-index]] · [[finding-approxspace-copy-drops-families]] · [[finding-approx-creator-hygiene]] · [[finding-local-test-crashes-workingtree]] (working tree, not pin). +**Library — C++/architecture:** [[finding-debugstop-throws-release]] · [[finding-global-state-cluster]] · [[finding-mesh-lifetime-ownership]] · [[finding-thread-shared-materials]] · [[finding-build-config-gaps]]. +**Application (divfreebubbles):** [[finding-matred-solver-mode-mislabel]] · [[finding-rusage-memory-units]] · [[finding-mhm-target-uncompilable]] · [[finding-voronoi-null-ganalytic]]. + +## C. Roadmap (v1 — completed in Phase 9 §9 of the final report) + +- **Low-risk tidy**: build-config triad; DebugStop typed error; DEBUG→PZDEBUG; self-assignment guards; approx-creator hygiene cluster; benchmark instrumentation fixes; ~days total. +- **Medium structural**: const-Contribute; mesh-lifetime symmetrization + deleted copies; gTolerance inline-variable fix; layering lint + Mesh⇄Pre decycle; creators prose docs + in-tree tutorial; app-repo CI (build-all-targets); persistence round-trip test for meshes; ~weeks. +- **High-risk/deep**: element-family extension API (de-duplicate the 14-file dispatch); needrefactor retirement (Session-2 correction C3: already out of the `pz` build — remaining work is header deletion/relocation + fixing SubStruct/PerfTests/Publications/unit-test includes, so risk drops); visibility/ABI macros; unique_ptr migration for unique ownership; distributed-memory strategy decision (revive BDDC vs external solver coupling); MatRed-style block reduction as a first-class library citizen (Session 2: three independent downstream reimplementations); each needs expert review + regression nets. diff --git a/ai-analysis/NEOPZ_TECHNICAL_ASSESSMENT.md b/ai-analysis/NEOPZ_TECHNICAL_ASSESSMENT.md new file mode 100644 index 000000000..ec9f8f7a3 --- /dev/null +++ b/ai-analysis/NEOPZ_TECHNICAL_ASSESSMENT.md @@ -0,0 +1,92 @@ +# NeoPZ Technical Assessment + +**Analyzed commit:** `develop @ 6ffd38b12` (labmec/neopz; repo default branch is `main`, `develop` is the integration/review canon per instruction). Working-tree caveat: checkout = develop + 3 commits touching 5 files; those files were always cross-checked via `git show develop:`. Runtime evidence from prebuilt binaries is labeled `[run @ 852a5116c(+)]`. Companion app repo: `../divfreebubbles @ 3DKernelHdiv`. +**Method:** 9-phase evidence-driven review (Session 1, 2026-07-02); knowledge base in `ai-analysis/wiki/`; per-phase deliverables in `ai-analysis/*.md`. Confidence labels: **[HC]** high (verified first-hand at cited lines / measured), **[MC]** medium (agent-traced with spot verification, or single-source), **[LC]** low (inference/hypothesis). +**Session 2 (2026-07-06) — library-breadth rebalance:** Session 1 leaned on one application (divfreebubbles) and the H(div)/hybridization axis. Session 2 added line-cited deep dives of the previously under-covered subsystems (H1/HCurl/discontinuous element families, TPZConnect restraints, multiphysics composition, condensation/groups/submeshes, geometry/refinement-patterns/nonlinear maps, Material-layer breadth incl. complex-scalar electromagnetics and eigen solvers, SBFem) and a survey of the **five most recently active downstream applications** (`wiki/apps/`). Sections below are annotated where Session 2 changed or extended the picture; one Session-1 claim is corrected (§6, needrefactor). + +--- + +## 1. Executive Summary + +**What this is.** A ~30-year-old, actively developed C++17 finite element *research environment* (single `pz` library) from LabMEC/Unicamp, distinguished by: hierarchical H1/H(div)/H(curl)/L² families of its own published construction, first-class hybridization (including novel "squared" and "semi" variants under active research), runtime-defined refinement patterns with hanging-node constraints, multiphysics composition, and swappable scalar types (incl. complex, for the eigen/electromagnetics stack) with forward AD. Applications live downstream. [HC] + +**How it is actually used [Session 2, app-repo evidence].** Six downstream repos were examined (divfreebubbles + the five most recently active in `~/GitHub`): saddle-point iterative-solver research (Iterative-Saddle_Point), GFEM fracture enrichment (GFEM), a-posteriori estimation + hp-adaptivity (ErrorEstimation), 3D/2D/1D coupled reservoir-wellbore flow (wann), and tensor-valued mixed elasticity with MHM (MixedElasticity). Cross-cutting findings (`wiki/apps/apps-overview`): every space family except H(curl) is heavily used downstream (H1 is a primary research surface, not a baseline); manual space construction and the creator layer are *both* load-bearing API; the TPZConnect/dependency layer is programmed directly by applications; MatRed-style block reduction has been independently reimplemented three times downstream (a strong candidate for a first-class library citizen); refinement patterns serve adaptivity, geometric grading, *and* macro-element space construction; ~20 downstream material classes but only one computational-element subclass — the material mixin layer absorbs most extension needs; app→lib class migration (with same-name-class shadowing) is the observed growth mechanism. + +**What it does well.** (1) The mathematical core is real and validated where it matters most structurally: the H(div) pipeline implements the contravariant Piola transform correctly factored across Topology/Shape/element layers [HC, traced to `pzelchdiv.cpp:1032-1033`]; discrete De Rham exactness and permutation-invariant conformity are directly unit-tested — rare anywhere [HC]. (2) The creator layer gives modern, disciplined space construction across an enormous configuration grid, and it is grid-tested [HC]. (3) Parallel assembly (producer/consumer and graph-coloring strategies) is soundly engineered [MC]. (4) The Schur-complement research solver shows excellent numerics: mesh-independent CG iterations (19 at 50² and 400²) and a measured win over sparse direct from ~100² up [HC, measured]. (5) Extensibility for materials/solvers is good and demonstrated by the app repo [HC]. + +**Main risks.** (1) *Accuracy-level validation is thin*: no convergence-rate tests on the core paths; the at-pin `TPZHybridElasticity2D` missing body-force RHS (confirmed, fixed upstream 2 commits later) is the proof that the current net cannot catch a whole defect class [HC]. (2) *Compiler-unenforced conventions*: shared mutable materials under threaded assembly (non-const `Contribute`), mesh lifetime asymmetry, per-TU `gTolerance` making `SetTolerance` a silent no-op, `DebugStop` throwing messageless exceptions in release, and a default build type that disables both debug checks and release paths — all verified, all accidental [HC]. (3) *The active research frontier (hybridization/condensation) has the weakest scaffolding*: dead guards and stubs cluster there; 5 test suites crash in the local working-tree build (pin itself is CI-green) [HC]. (4) The app repo has no CI and demonstrably rots (uncompilable target, null-deref driver, benchmark unit bug) [HC]. + +**Biggest opportunities.** A manufactured-solution *rate* matrix (days of work, catches the worst class of silent errors); the build-config triad fix (hours); const-`Contribute` (mechanical, makes the parallel-assembly invariant compiler-checked); an app-repo CI job; reviving one thin performance-regression job. + +**Overall recommendation.** NeoPZ is a mathematically serious library whose *domain* architecture deserves preservation; investment should go to hardening the engineering shell around an already-strong core: validation depth (rates, curved×vector combinations), enforcement of existing conventions (const, lifetimes, build flags), and CI breadth (app repo, granularity, sanitizers). No wholesale refactor is warranted; the high-risk items are surgical. + +## 2. Repository Map + +(Compressed; full atlas: `CODEBASE_ATLAS.md`.) Single `pz` target; 24 top-level source groups in aspirational layer order [HC]: foundation (Util/Common/Save) → numerics (Integral/Matrix/Solvers) → reference layer (Topology/Geom/SpecialMaps/Shape/Refine) → discretization (Material 199h/178cpp incl. the 19+108-file `needrefactor/` legacy island; Mesh 65/61) → orchestration (Analysis/Post/Frontal/StrMatrix/Pre/SubStruct). Core abstractions: `TPZGeoMesh`/`TPZGeoEl`+sides, `TPZCompMesh`/`TPZConnect`/`TPZCompEl`, `TPZMatBase` materials, `TPZCreateApproximationSpace` factory + `TPZ*ApproxCreator` builders, `TPZStructMatrix` assembly strategies, `TPZMatrix` storage zoo + `TPZStepSolver`/Pardiso/MUMPS, `TPZVTKGenerator`. Layering is not build-enforced (one target; 6 verified backward include edges; Mesh⇄Pre cycle) [HC]. Build: CMake ≥3.14, 24 options, only Threads required; exports `find_package(NeoPZ)` [HC]. Tests: Catch2, 33 suites; CI: 5 GitHub workflows, macOS always-on gate [HC]. Docs: Doxygen+Sphinx→gh-pages; good header docs, no prose for the creator entry points, getting-started funnel leaves the tree [MC]. No LICENSE file despite "open-source" README [MC]. + +## 3. Domain Model Assessment + +**Well-modeled and clear** [HC]: geometry/computation split (original 1997 design intent, still coherent); "sides" as the universal topological currency (connects, neighbors, transforms, restraints all keyed on sides); materials = weak forms with capability mixins; connect-based conformity with Lagrange-multiplier *levels* elegantly ordering condensability; space families as explicit enums. +**Session-2 additions to the domain map** [HC, line-cited in the wiki]: (1) *Element families differ structurally, not just mathematically* — H1 = one connect per side incl. corners (family flavor resolved at creation time, prism-only); HCurl = no vertex connects, live runtime family switch, covariant Piola with implicit node-id orientation (vs HDiv's explicit `fSideOrient`); discontinuous = one connect per element, modal basis, external-shape enrichment hook; L² pressure in mixed meshes is broken-H1 for p>0 and TPZCompElDisc for p=0. (2) *The restraint machinery is general-purpose*: hanging-node dependencies are L2 projections of coarse traces keyed on geometric side transforms, applied per element with a complex-correct congruence transform; downstream code reuses `AddDependency` for cross-dimensional coupling. (3) *Composition is layered and ordering-sensitive*: ElementGroup (sum) → CondensedCompEl (Schur via TPZMatRed, dependent∧condensed illegal) → SubCompMesh (a mesh that is an element; SaddlePermute → external-connect permutation → equation-filtered factorization; rigid-body-mode-aware). (4) *Children of curved elements inherit the exact map* (TPZGeoElMapped evaluates through the eldest ancestor); the pyramid uniformly refines into 6 pyramids + 4 tets. (5) The Material layer splits cleanly single-space vs combined-spaces at the Contribute signature; electromagnetics is CSTATE-only and feeds the generalised/quadratic eigen mixins + Krylov/LAPACK eigen stack; SBFem assembles a block Hamiltonian and calls LAPACK `dgeev_` directly, bypassing that stack. +**Where domain concepts are hidden/coupled** [HC/MC]: the hybridization geometry protocol (wrap/interface/Lagrange elements with strided matids, `fInterfaces` map whose `TPZHybrid` field names mislabel their contents — `fLagrange` stores the interface id [MC]) is powerful but discoverable only by reading `TPZApproxCreator.cpp`; the meaning of `EStandardSquared`/`ESemi`/`EHDivOptimized` exists in papers and code, not in docs; two generations of MHM machinery (controllers vs creators) coexist, plus a same-named creator in the app repo — a migration in progress that include paths silently arbitrate [HC]; `Material/needrefactor/` duplicates modern physics under old names. +**Confusing to newcomers but justified** (do not "fix" naively): the `.h.h` template-body files, per-topology static shape classes (deliberate de-virtualization), the axes-based gradient frame for dim<3 elements embedded in 3D, refinement-pattern *data* files as runtime input. + +## 4. Execution Flow Assessment + +Canonical pipeline (verified across five slices, `EXECUTION_FLOWS.md`): geometry (`TPZGmshReader` in-tree parser / generators) → spaces (manual per-field cmeshes *or* creators with hybridization+condensation) → materials/BCs per matid → `TPZLinearAnalysis` + struct-matrix (storage×parallelism×filter) → direct (in-house/MKL/MUMPS) or Krylov / app-side Schur (`TPZMatRedSolver`) → outputs (`TPZVTKGenerator` legacy-format .vtk with element subdivision; `PostProcessError` vs `TPZAnalyticSolution`). [HC] +**Clear**: the creator-driven path reads almost like the math; equation counts before/after condensation are first-class; the unit-test slice shows the intended usage idioms. +**Hard to follow**: post-creation mutation sequences (create space → *then* orthogonalize/hybridize-low-order/group/condense as separate app-side steps in iter_elast); interface-element wiring through `fInterfaces` built two phases earlier; solution recovery through condensed wrappers (implicit in `LoadSolution`). +**Outputs and their validity conditions**: benchmark tables = wall-times + peak RSS, valid only per-platform (memory column is KiB on macOS mislabeled MB [HC, measured]); error tables = material-defined norms vs `SetExact` (indices material-specific; error/VTK legs are *disabled* in the benchmark drivers — correctness evidence lives in dFreeBubbles1el + unit tests) [HC]; VTK files = pointwise subdivision samples, no projection (discontinuities representable via duplicated points) [MC]. + +## 5. Algorithmic and Mathematical Assessment + +**Techniques identified & verdicts** (details: `ALGORITHM_NOTES.md`): +- H(div)/H(curl) hierarchical construction (scalar H1 × geometry-based vectors): matches the published spec (De Siqueira–Devloo–Gomes 2013); **conventional-variant, sound** [HC]. +- Contravariant Piola with `1/|detJ|` + explicit `fSideOrient` signs + facet permutation gather; FAD branch for curved derivatives: **conventional in variant factorization** [HC]. Residual expert item: sign composition on reflected/refined configs [LC risk]. +- HDivConstant family (RT0 facet carriers + divergence-free kernel fields): **intentional published variant** [HC]; one confirmed REAL-vs-FAD inconsistency latent for curved×variable-order [HC finding]. +- Hybridization: EStandard conventional; **EStandardSquared = literal hybridization² of broken-H1** (only 2nd-level skeleton global) — structural match to the group's 2025 double-hybrid paper (H1-primal variant; exact correspondence = expert question) [HC trace/MC mapping]; **ESemi = constant-facet-flux duplication** (even/odd connect split, sideOrient=−1 side rebound to wrap) — semi-hybridization à la Carvalho 2024, variant in *which* trace is weakened [HC]. +- Static condensation + rigid-body spaces: coherent; Lagrange levels order the elimination; in-code singular-K00 guard documents the one known trap; library `TPZMatRed` is rigid-body-mode aware [HC]. +- MHM: substructure realization consistent with Araya et al. 2013 expectations (coarse constants = RB spaces) [MC]; two machinery generations flagged. +- App-side Schur solver: split by Lagrange level, matrix-free Schur CG, block-diag ELU preconditioner; **measured mesh-independent iterations** [HC]. +**Conflicts/tensions register** (all classified, none left as vague suspicion): confirmed bugs (RHS-at-pin; FAD index; copy-drops-families; app quartet), possible math risks (thread-shared materials; |detJ|-sign composition; EAvSol coupling under Squared; elastic multiplier asymmetry), intentional variants (families, ESemi-for-Darcy, |detJ| factorization), naming mismatches (solver mode label — with measurable benchmark effect; `TPZHybrid` field names), insufficient evidence (local test crashes attribution). + +## 6. C++ and Architecture Assessment + +(Details: `CPP_TECHNICAL_REVIEW.md`.) **Strengths**: intentional domain architecture; variadic-mixin materials; disciplined `override` (3757) and `[[nodiscard]]` (150); atomic-refcount `TPZAutoPointer`; real parallel-assembly engineering; good header docs. **Weaknesses (all verified, all accidental)**: DebugStop-throws-always (3,029 sites / 9 catches); per-TU `gTolerance` (public setter silently inert); asymmetric mesh-destructor protection + raw-owner copy hazards (`TPZAnalysis::fSolver`); non-const `Contribute` under thread-shared materials; RelWithDebInfo macro gap + 14 dead `#ifdef DEBUG` + warnings off (Xcode warnings explicitly silenced); unenforced layering (single target, Mesh⇄Pre cycle); 963 raw `new` / 0 `unique_ptr`; element-family extension requires ~500 lines with copy-paste dispatch across 14 files; four coexisting template-impl conventions; two naming eras. **Risky patterns**: same-name classes across lib/app repos (Session 2 found more instances: `TPZMixedElasticityND`, `TPZHybridElasticity2D` — the latter simultaneously under edit in the ErrorEstimation app and in this working tree's delta); dead machinery (Backup interface builder, UnitaryLagrange) adjacent to live research code. **Correction (Session 2)**: `needrefactor/` is **not** compiled into `pz` — no `add_subdirectory` and zero symbols in `libpz.dylib` [HC, verified by nm]; the residual risk is include-path shadowing of duplicate class names plus a handful of out-of-library targets (SubStruct, PerfTests, Publications, one unit test) that include its headers. **Extensibility, re-weighed with Session-2 evidence**: the ~500-line cost applies to *adding* an element family; *modifying* one is far cheaper — GFEM injects arbitrary per-point basis enrichment by overriding `ComputeShape` on a `TPZCompElH1` subclass without touching the library, and across six downstream repos only that one computational-element subclass exists versus ~20 material subclasses. The material mixin layer is absorbing nearly all downstream variation, which both validates the design and confirms the element-family API as the singular weak point. **Modernization that pays**: const-Contribute, deleted copies on raw owners, inline-variable fix, typed fatal error, build flags — all mechanical. **Complexity verdict**: the hard-to-read parts of Mesh/Shape/Topology are overwhelmingly *essential* FEM machinery; the five high-severity items are all *accidental* and cheap relative to their risk. + +## 7. Testing and Validation Assessment + +(Details: `TESTING_AND_VALIDATION_REVIEW.md`.) **Proves**: conformity + De Rham exactness incl. under permutations (2D/3D, k≤3); exact linear/constant representation across the creator grid (families×problems×hybridization×condensation×refinement); MUMPS↔Pardiso equality; parallel↔serial assembly equality; curved-map geometry vs exact shapes; fast suite (16.6 s) gated by CI on macOS (+conditional Linux/MKL); **CI green at the pin** [HC]. **Does not prove**: convergence *rates* (except SBFem); anything with nonzero body forces (hence the escaped RHS bug); H(div)×curved; vector spaces × hanging nodes; mesh persistence round-trips; VTK correctness. Operational: per-suite ctest granularity; no coverage; no Windows CI; `[!shouldfail]` debt; **5 suites crash in the local working-tree build** (attribution: post-pin local state) [HC]. **Strategy**: (1) rate matrix w/ body forces + curved meshes; (2) fix/gate the crashing suites; (3) per-TEST_CASE CI granularity + labels; (4) app-repo CI; (5) persistence round-trip; (6) VTK golden file; (7) ASan/TSan jobs; (8) burn down known-fail debt. + +## 8. Performance Assessment + +(Details: `FINDINGS_AND_ROADMAP.md` §A.) **Measured** [HC]: assembly ≈ linear; Schur path ≈ linear solve (mesh-independent CG) vs superlinear sparse direct — crossover ≈100² for this 2D problem; K00 factorization = 72% of iterative t2 at 400². **Likely hotspots**: K00 Cholesky at scale; OR consumer serialization at high thread counts [LC]; skyline in-house paths for mid-size when MKL absent [LC]. **Infrastructure**: PerfTests stale/self-deprecated, not in CI; benchmark drivers carry two instrumentation bugs (units, preconditioner mode). **Opportunities with tradeoffs**: thin perf-CI job (high value/effort); renumbering control-run for the direct baseline; symbolic-factorization reuse across sweeps; PCH/unity + Mesh⇄Pre decycle for build times. **Premature-optimization risks flagged**: no evidence virtual material dispatch or chunk vectors dominate — measure before touching; shared-memory ceiling (no MPI) is a *strategy* decision, not a quick fix. + +## 9. Refactoring Roadmap + +**Low-risk tidy** (days; no algorithm changes): build-config triad (RelWithDebInfo case, `DEBUG`→`PZDEBUG`, `-Wall/-Wextra` in CI); typed fatal error replacing bare `bad_exception`; self-assignment guards (`TPZMatRed::CopyFrom`); approx-creator hygiene cluster (`&&` fix, braces, delete dead Backup/UnitaryLagrange or wire them, remove `fH1Fam`/rotation stub); `TPZCreateApproximationSpace` copy ops `= default`; benchmark instrumentation fixes (app); `~TPZGeoMesh` peer-nulling; delete `TPZAnalysis` copies; LICENSE file. +**Medium-risk structural** (weeks; behavior-preserving, needs review): const-qualify `Contribute/ContributeBC/Solution` hierarchy-wide; `gTolerance` → C++17 inline variable (or the drafted singleton); include-cycle lint + forward-decl `TPZCreateApproximationSpace` out of `pzcmesh.h`; per-TEST_CASE CI + labels + coverage + one sanitizer job; app-repo CI building all targets; creators prose docs + in-tree mesh→solve tutorial; persistence round-trip tests; rate-matrix validation suite; `gRefDBase` injection or internal locking. +**High-risk / expert-gated** (needs FEM owner sign-off + regression nets first): element-family extension API (de-duplicate `NConnectShapeF` dispatch and the 7-override pattern — touches every element family); `needrefactor/` retirement (already out of the `pz` build — Session-2 correction; remaining work = delete/relocate headers and fix the SubStruct/PerfTests/Publications/unit-test includes); symbol-visibility/ABI macros (breaks downstream links); gradual `unique_ptr` migration for unique ownership (963 sites — do opportunistically); distributed-memory strategy (revive BDDC vs couple to external DD solvers); unification of MHM generations and lib/app creator duplicates. + +## 10. Open Questions for Domain Experts + +1. |detJ|+`fSideOrient` composition: is the sign protocol provably consistent on reflected/mirrored and multi-level-refined configurations (the `NormalOrientation` father-walk)? A short derivation or targeted permutation×refinement test would close the last Piola risk. +2. `EStandardSquared` + `EElastic`: what keeps `EAvSol`-level connects globally coupled (the explicit `IncrementElConnected` runs only for `EStandard`)? Works per tests; mechanism opaque. +3. Elastic hybrid multiplier asymmetry (only right interface reset to +1; Darcy resets both): intended? +4. `ComputeOrthogonalizingRestraints` / `HybridizeLowOrderFluxes` (app-side, feeding the observed High-Order/Linear flux split): published or WIP? What is the intended invariant? +5. `EHDivOptimized`: definition/reference? +6. ESemi for Darcy: which trace continuity is *meant* to be weak (the 2024 paper's Darcy remark suggests tangential-weak is unnecessary there)? +7. `TPZMatWithMem` under parallel assembly: how is per-point memory synchronized? +8. Unused `divphiFad` (algebraic divergence used instead on curved elements): intentional? +9. The 5 crashing suites on the working tree: known WIP state? (A rebuild at `4de234fae` would attribute definitively.) +10. Is mesh persistence (save/restore) an active workflow that deserves its round-trip test, or legacy? + +## 11. Evidence Boundary Summary + +**Confirmed by repository evidence [HC]**: everything cited with `path:line` at the pin — the Piola pipeline; hybridization construction incl. Squared/ESemi mechanics; condensation/Lagrange-level machinery; the five C++ H-findings; the at-pin RHS omission (+its upstream fix); FAD/copy/hygiene findings; test inventory; build-system facts; app-repo drift quartet. +**Supported by external references**: expected conformity/Piola/inf-sup invariants (Boffi–Brezzi–Fortin); hybridization frame (Cockburn et al. 2009); the *intent* behind squared/semi hybridization and H(div) flavors (Devloo-group papers 2013–2025); MHM structure (Araya et al. 2013). References informed interpretation only — no code judgment was made from a paper against demonstrated code behavior. +**Measured [run]**: CG mesh-independence; Schur-vs-direct crossover; suite pass/crash census; memory-unit distortion. All runtime claims are about the installed `852a5116c(+)` build, not the pin. +**Inferred [MC/LC]** (marked in place): OR-consumer bottleneck at high thread counts; ESemi-for-Darcy intent; benchmark-favoring effect of unrenumbered direct baseline; crash-cluster attribution to the condensation refactor. +**Session-2 evidence [app-repo / repo]**: the downstream survey claims are app-repo evidence at each repo's 2025-26 HEAD (spot-verified first-hand), *not* statements about the analysis pin; the new subsystem deep dives (element families, TPZConnect, multiphysics, condensation/submeshes, geometry/refinement/maps, Material breadth, SBFem structure, eigen stack) are agent traces with load-bearing lines re-verified at the working tree (delta-file caveats observed). +**Remains uncertain**: the ten expert questions above; deep numerical validation of paths that were structurally traced but never executed here (electromagnetics/eigen solutions, plasticity memory under threads, Frontal, BlackOil); H(curl) usage evidence is in-tree only — none of the five surveyed apps exercises it. +**Should not be changed without expert validation**: shape/topology orientation protocol; Lagrange-level semantics; hybridization sign tables; refinement-pattern data and constraint machinery; the needrefactor carve-out (dependents unknown); anything under §10. diff --git a/ai-analysis/TESTING_AND_VALIDATION_REVIEW.md b/ai-analysis/TESTING_AND_VALIDATION_REVIEW.md new file mode 100644 index 000000000..21c831e8e --- /dev/null +++ b/ai-analysis/TESTING_AND_VALIDATION_REVIEW.md @@ -0,0 +1,57 @@ +# NeoPZ Testing & Validation Review + +**Phase 7 deliverable.** Question: does the repository give confidence in (a) software behavior and (b) mathematical correctness? Evidence: full test-suite inventory (Phase 1 explorer, key files read first-hand in Phases 2/4), a live `ctest` run on the existing Release build [run], CI-status checks via the GitHub API [web], and the validation-relevant findings from Phases 4–5. + +--- + +## 1. What exists (inventory) + +- **Framework**: Catch2 v3.3.2 (FetchContent), 33 suites / ~56 cpp / ~180+ TEST_CASEs, custom event listener distinguishing new failures from `[!shouldfail]`-marked known failures. 40 ctest entries at the build used here. +- **Mathematically substantive suites** (the library's real crown jewels): + - `TestDeRham` — discrete exact-sequence checks at basis level: rank(op(left)) = ker(right) + range-inclusion via SVD, dims 2/3, k=1..3, H1→HCurl→HDiv→L2 incl. HDivConst (read first-hand, TestDeRham.cpp:49-120). + - `TestMesh/TestHDiv` — De Rham on real meshes **including under face/node permutations** (`drham_permute_check`), side-shape continuity, shape order, bilinear reproduction. + - `TestTopology` — constant divergence/curl reproduction per topology + face-orientation data structures. + - `TestHDivApproxSpaceCreator` — the creator pipeline grid: 3 HDiv families × Darcy/Elastic × 4 mesh types × p{1,2} × extra-p × hybridization {ENone,EStandard,ESemi} × RB × condensation × refinement (+MHM creator), asserting exact linear/constant representation, domain integrals, condensed equation counts (read first-hand, :152-216). + - `TestHCurl` (traces, permutations, curls), `TestH1ApproxSpaceCreator`, `TestHDivCollapsed` (fracture elements), `TestSBFem` (actual **convergence-rate** tests), `TestSolverComparison` (MUMPS vs Pardiso cross-backend equality), `TestMultithreading`/`TestStruct` (parallel == serial assembly), `TestBlend`/`TestGeometry` (curved maps vs exact geometry), `TestHangingNode`/`TestCondensedSpace` (constraints), `TestIntegNum` (quadrature exactness), plus matrix/FAD/plumbing suites. +- **CI**: 5 GitHub Actions workflows. macOS job = always-on gate (build + ctest); Linux + MKL jobs conditional on a prebuilt `neopz-deps` image; consumer smoke-test workflow builds NeoPZExamples against an install; docs workflow. **CI is green at the analysis pin** (`6ffd38b` success; also `852a511`) [web]. + +## 2. What the tests prove — and what they don't + +**Proven (strong, unusual for a research FEM code):** +1. Space-conformity invariants *by construction and by permutation* — the orientation protocol that most FEM bugs hide in is directly exercised. +2. Discrete De Rham exactness at rank level for all family pairs, 2D & 3D, k≤3. +3. Exact reproduction of constants/linears through the full creator pipeline across an enormous config grid (incl. hybridization + condensation + refinement). +4. Cross-backend solver equality (MUMPS↔Pardiso) and parallel↔serial assembly equality. +5. Element-level quadrature exactness (partially — several cases commented out). + +**Not proven (the honest gaps):** +1. **Convergence *rates*** — only SBFem tests assert rates; the core H1/H(div)/hybrid paths assert exact representation of low-order solutions, which catches wiring errors but not order-of-accuracy regressions (e.g., a Piola-scaling subtlety on curved meshes would pass every current test). The at-pin missing-RHS bug ([[finding-hybridelasticity2d-missing-rhs-at-pin]]) is the concrete demonstration: **no test drives a material with nonzero body force against a manufactured solution.** +2. **Curved geometry × vector spaces** — TestBlend validates maps, De Rham suites run on affine meshes; the combination (H(div) on curved elements, the topic of an in-tree Publications companion!) is untested; the FAD-branch inconsistency ([[finding-hdivconstant-fad-index]]) lives exactly in that shadow. +3. **hp/hanging-node × vector families** — hanging-node suites exist (H1-centric); constrained H(div)/H(curl) under nonuniform refinement is not visibly covered. +4. **Persistence round-trips** — one matrix round-trip; no gmesh/cmesh save-restore test despite the elaborate versioned-translator machinery. +5. **Post-processing correctness** — VTK output has no golden-file or invariant test (only indirect smoke via a parallel-error test and PostProcessVTK calls in the creator suite). +6. **Known-failing debt is institutionalized**: `[!shouldfail]` on SVD and several skyline ops; commented-out quadrature cases — visible, at least, but unburned-down. + +## 3. Operational health signals + +- **Live run** [run @ working-tree build]: 35/40 pass in 16.6 s (fast suite!); **5 crash** (TestCondensedHangingNodes SIGTRAP; TestReduced/TestErrorAnalysis/TestHangingNode/TestSBFem bus errors). Upstream CI green at the same stamped revision ⇒ attribution points at the then-uncommitted local edits or machine config — [[finding-local-test-crashes-workingtree]]. Either way: **the crash cluster sits in condensation/constraints, the area under active refactor** — exactly where a rate/regression net is thinnest. +- **Granularity**: `catch_discover_tests` disabled (log4cxx interference) ⇒ ctest sees one test per suite; a single crashing TEST_CASE takes down the whole suite's reporting. No ctest LABELS. +- **No coverage tooling** anywhere; no test-result artifacts in CI; no Windows CI despite Windows build support; Linux/MKL legs skippable silently. +- **App repo (divfreebubbles)**: Catch2 tests exist but `BUILD_TESTS=OFF` default, several commented out; **no CI at all** — three independent drift bugs found (uncompilable target, null-deref driver, stale README) are the predictable consequence. +- Reproducibility: versioned persistence exists but untested for meshes; `pz_config.h` stamps git revision (good); refpattern data is runtime-loaded from an absolute path baked at configure time (fragile for relocated installs). +- Meta: no LICENSE/CONTRIBUTING in-tree (legal/hygiene, affects external validation contributions). + +## 4. Recommended validation strategy (prioritized) + +1. **Manufactured-solution rate matrix** (the single highest-value addition): one parametrized suite driving {H1, mixed HDiv (Standard/Constant), hybrid (EStandard/Squared/ESemi)} × {Darcy, elasticity **with nonzero body force**} × {affine, curved} meshes for 3 refinement levels, asserting L2/energy **rates** within tolerance. Directly nets: the RHS-class bug, Piola-on-curved risks, order regressions from family edits. Cost: builds entirely on `TPZAnalyticSolution` + creators already in-tree. +2. **Un-crash the working tree** and add the 5 crashing suites to a required pre-merge gate for the research branches (they run in seconds). +3. **Enable `catch_discover_tests`** (fix the log4cxx detection issue or gate logging in tests) so CI failures name the TEST_CASE; add LABELS for `ctest -L math|plumbing|solver`. +4. **App-repo CI**: build all registered targets + run the fast Catch2 tests on push — would have caught all three drift findings. Mirror NeoPZ's consumer-smoke workflow. +5. **Persistence round-trip test** for gmesh+cmesh (+ one refined mesh with dependencies) — protects the translator machinery that reproducibility claims rest on. +6. **Golden-file VTK test** (tiny mesh, fixed fields, byte-compare modulo float formatting) + a pyramid/prism cell-type check. +7. **Coverage + sanitizers in CI** (one Debug+ASan job; one TSan job running TestMultithreading and the OR/OT paths — pairs with [[finding-thread-shared-materials]]). +8. Burn down `[!shouldfail]`/commented tests or convert them to tracked issues; they currently encode known-unknowns invisibly. + +## 5. Verdict + +Software-behavior confidence: **moderate-to-good** (fast, broad, CI-gated on two platforms; weakened by granularity, coverage-blindness, and platform gaps). Mathematical-correctness confidence: **good at the invariant level, weak at the accuracy level** — the suite is unusually strong on structural/conformity invariants (permutation-proof De Rham checks are genuinely rare) and unusually thin on convergence rates and curved-geometry combinations; the two confirmed at-pin math-adjacent defects both live precisely in the untested shadows. diff --git a/ai-analysis/wiki/apps/app-error-estimation.md b/ai-analysis/wiki/apps/app-error-estimation.md new file mode 100644 index 000000000..ced8cd928 --- /dev/null +++ b/ai-analysis/wiki/apps/app-error-estimation.md @@ -0,0 +1,31 @@ +--- +type: app-survey +status: reviewed +updated: 2026-07-06 +confidence: medium +evidence-commit: "app development @ d6c0496 (2025-11-05); embedded neopz Australia25 @ 85cafdd8c (2025-11-23)" +tags: + - neopz + - downstream + - error-estimation + - adaptivity + - sbfem +--- + +# App survey: ErrorEstimation (~/GitHub/ErrorEstimationResearch) + +> Downstream-usage evidence (Session 2). Claims [agent], load-bearing ones spot-verified [✓]. Citations refer to the app repo. + +**What it is.** An **a-posteriori error-estimation and adaptivity research suite**: solve (mostly Darcy/Poisson, newly elasticity), **reconstruct** an improved conforming solution in an auxiliary space, use the difference as an element-wise estimator, and drive h/hp-adaptive loops. Four estimator families: HDiv-mixed potential reconstruction, Hybrid-H1 reconstruction (H1 and HDiv flavors), MHM estimation, and patch-based partition-of-unity flux reconstruction. ~15 targets over an `ErrorEstimationLib`; active line = `ErrorNaca` (+2DSqrt/Lshaped/contrasting-permeability benchmarks), the HybridH1 reconstructions, and a new SBFem/elasticity thread (Nov 2025). + +**Library surface exercised:** +- **The reconstruction layer** (the core novelty): `TPZHDivErrorEstimator` owns a `TPZMultiphysicsCompMesh fPostProcMesh` and a `TPZHybridizeHDiv` [✓ `ErrorEstimation/TPZHDivErrorEstimator.h:30,72`]; `PotentialReconstruction()` clones the solved pressure mesh, builds skeleton geo+comp elements, computes edge and nodal pressure averages, and produces a conforming potential — post-processable in **H(div)++ or H1** (`fPostProcesswithHDiv`). Sibling drivers `TPZHybridH1CreateH1Reconstruction`/`...HDivReconstruction` do the same from hybrid-H1 solutions. `TPZPostProcessError` [✓ `.h:85`] runs colored **patch solves keyed on partition-of-unity connects**. This whole layer is built from library primitives: mesh cloning, `TPZHybridizeHDiv`, `TPZElementGroup`+`TPZCondensedCompElT`, `TPZSubCompMesh` traversal, order-increase utilities (`IncreaseSideOrders` — HDiv++ as an estimation device). +- **Closed adaptive loops**: `ErrorNaca.cpp` runs a 13-step loop [✓ `Hrefinement`/`HPrefinement` :487-489] — estimator → per-element refinement indicator → `gel->Divide` / p-order maps → re-solve. `Tools::hAdaptivity`, `RandomRefinement`, MHM skeleton division (`DivideSkeletonElements`) round out the refinement API usage. This is the missing in-library "adaptive driver" of [[hp-adaptivity]] — it lives here, downstream. +- **Singularity-resolution geometry**: mesh styles `{ETraditional, ECollapsed, EQuarterPoint, ESBFem}` [✓ `ErrorNaca.cpp:241`] — **quarter-point elements** [✓ `CreateQuarterPointElements` :149,395], collapsed elements, and SBFem element groups as alternatives around the NACA trailing edge; custom exact map `TPZNacaProfile : TPZBlendNACA` [✓ `tpznacaprofile.h:31`] (the vendored NACA SpecialMap subclassed downstream). SBFem extensions: `TPZBuildSBFemHybrid : TPZBuildSBFem`, `TPZSBFemElementGroupPostProcess : TPZElementGroup`. +- **Materials as estimation logic**: ~12 custom materials subclass `TPZMixedPoisson`/`TPZDarcyFlow`/`TPZHybridDarcyFlow`/`TPZElasticity2D`, mixing in `TPZMatCombinedSpacesT`+`TPZMatErrorCombinedSpaces` so that `Contribute` computes estimator contributions — including a template mixin `TPZMixedErrorEstimate` parameterized over the wrapped material. The material interface carries estimation logic, not just weak forms. +- **Cross-repo lineage flag**: an app-side `TPZHybridElasticity2D : TPZElasticity2D, TPZMatCombinedSpacesT, TPZMatErrorCombinedSpaces` [✓ `ErrorEstimation/Material/TPZHybridElasticity2D.h:25`, edited 2025-11-05] shares its name with the library's `Material/Elasticity/TPZHybridElasticity2D` — one of the 5 working-tree delta files of this engagement's pin. The SemiHybridElasticity work spans both repos; same-name-class migration risk (cf. `CPP_TECHNICAL_REVIEW.md` §6) applies here too. +- Spaces: H1, HDiv (incl. ++enrichment), discontinuous L2, multiphysics — manual `SetAllCreateFunctions*` composition plus a custom space factory `TPZCreateHybridH1Space` (pre-dates/parallels the library `TPZApproxCreator` layer). Solvers: direct only (`TPZSSpStructMatrix`, skyline, `TPZParFrontStructMatrix` frontal). + +**What it teaches about the library.** (1) Error estimation and adaptivity are a *platform capability*: everything the estimators need (cloning, hybridization, condensation, submesh traversal, order manipulation) already exists as library primitives — but the drivers live downstream, confirming the [[hp-adaptivity]] page's hypothesis. (2) Mesh cloning + material swapping is a supported (if undocumented) workflow. (3) The geometry layer's exotic corners (quarter-point, collapsed, blend-NACA, SBFem) are exercised together in one adaptive driver. (4) A third independent app running its own MatRed-free reconstruction solves per patch shows small-dense local solves are a common downstream idiom. + +Related: [[error-estimation-convergence]] · [[hp-adaptivity]] · [[hybridization]] · [[sbfem]] · [[condensation-groups-submeshes]] · [[geometry-refinement-maps]] · [[apps-overview]] diff --git a/ai-analysis/wiki/apps/app-gfem.md b/ai-analysis/wiki/apps/app-gfem.md new file mode 100644 index 000000000..44d4b5e41 --- /dev/null +++ b/ai-analysis/wiki/apps/app-gfem.md @@ -0,0 +1,32 @@ +--- +type: app-survey +status: reviewed +updated: 2026-07-06 +confidence: medium +evidence-commit: "app @ 2025-12-18 HEAD; embedded neopz Australia25 @ 182a80985 (2025-12-16)" +tags: + - neopz + - downstream + - gfem + - fracture + - sbfem +--- + +# App survey: GFEM (~/GitHub/GFemResearch) + +> Downstream-usage evidence (Session 2). Claims [agent], load-bearing ones spot-verified [✓]. Citations refer to the app repo. + +**What it is.** **Generalized FEM for fracture mechanics**: enriched H1 approximations carrying displacement-jump discontinuities across a crack and singular fields at the crack tip, 2D and 3D (Darcy + elasticity physics). Targets: `GFem2D`, `GFem3D` (penny-shaped crack), `SBFem2D` (derives the singular enrichment modes via a scaled-boundary eigen-analysis), `TestGFemEnrichment`, 2 Catch2 test targets, all over a shared `GFEM_library` of NeoPZ extensions. + +**Library surface exercised:** +- **Element-level extension — the headline**: `TPZGFemCompElH1 : TPZCompElH1` [✓ `NeoPZ_extensions/TPZGFemCompElH1.h:9`] overrides `ComputeShape`/`ComputeRequiredData` to multiply standard H1 shapes by an enrichment/jump function per integration point (product rule for gradients) — partition-of-unity enrichment injected through the documented `ComputeShape` seam, instantiated for linear/triangle/quad/tetra shapes. Partner subclass `TPZGFemCompMesh : TPZCompMesh` carries a `std::map` associating enrichment functions to **connects** [✓ `TPZGFemCompMesh.h:25,32`]. +- **Multiphysics as space composition**: background H1 + enriched GFem (+ optional H1 "mirror") atomic meshes combined via `TPZMultiphysicsCompMesh::BuildMultiphysicsSpace`; the custom combined-spaces materials (`TPZGFemDarcyFlow`, `TPZGFemElasticity2D/3D` — each inheriting *both* the library single-space physics class and `TPZMatCombinedSpacesT` + `TPZMatErrorCombinedSpaces`) sum sub-mesh contributions in `Solution()`. No HDiv/HCurl/L2 anywhere — a pure H1/multiphysics stress test. +- **SBFem as a production tool**: `TPZBuildSBFem` + `TPZSBFemElementGroup::EigenValues()/LoadEigenVector()` [✓ `2D/SBFem2D.cpp:494,592`] extract crack-tip singular modes from a JSON crack definition — the library's scaled-boundary eigen machinery used to *generate basis functions* for another method ([[sbfem]]). +- **Custom StrMatrix/Matrix pair**: `TPZSSpMatRedStructMatrix : TPZStructMatrixT, TPar` [✓ `NeoPZ_extensions/TPZSSpMatRedStructMatrix.h:15`] + app-side `TPZSparseMatRed : TPZMatrix` produce a K00(background)/K11(enrichment) block reduction solved by CG preconditioned with direct LDLt of K11 (`3D/GFem3D.cpp:978-1008`) — the same MatRed pattern as divfreebubbles, independently reimplemented for a conditioning problem specific to enrichment methods. +- **Conditioning research on the connect layer**: `TPZGFemOrthogonal` orthogonalizes enrichment DOFs against the background space patch-by-patch using local dense `SolveEigenProblem` + `TPZMatRed` — near-linear-dependence control that only enrichment methods need. +- **Geometry**: gmsh input; `gRefDBase.InitializeRefPatterns` + **`TPZRefPatternTools::RefineDirectional` toward the crack tip** [✓ `2D/GFem2D.cpp:254`]; `TPZArc3D` + `TPZGeoBlend` curved crack-tip sectors; programmatic node-by-node geometry for SBFem domains. +- Embedded neopz on branch `Australia25` with app-motivated fixes (eigenvector loading resize; linear-element subdivision) — same downstream-drives-library pattern as wann. + +**What it teaches about the library.** (1) The `TPZCompElH1`/`ComputeShape` pipeline is open enough for arbitrary per-point basis enrichment without touching the library — the cleanest evidence for element-layer extensibility (contrast the ~500-line new-family cost noted in `CPP_TECHNICAL_REVIEW.md` §6: *modifying* a family is much cheaper than *adding* one). (2) `TPZMultiphysicsCompMesh` composes same-physics spaces (background+enrichment), not just different fields. (3) SBFem is live downstream, not a dormant breadth item. (4) MatRed-style block reduction is a recurring *user pattern* across independent apps — a strong argument for first-class library support. + +Related: [[element-families]] · [[multiphysics-composition]] · [[sbfem]] · [[refinement-hanging-nodes]] · [[matrix-and-solvers]] · [[apps-overview]] diff --git a/ai-analysis/wiki/apps/app-iterative-saddle-point.md b/ai-analysis/wiki/apps/app-iterative-saddle-point.md new file mode 100644 index 000000000..c721d0fe1 --- /dev/null +++ b/ai-analysis/wiki/apps/app-iterative-saddle-point.md @@ -0,0 +1,29 @@ +--- +type: app-survey +status: reviewed +updated: 2026-07-06 +confidence: medium +evidence-commit: "app main @ 317b0c6 (2026-03-27); embedded neopz develop @ d366830a5 (2026-03-20)" +tags: + - neopz + - downstream + - saddle-point + - solvers +--- + +# App survey: Iterative-Saddle_Point (~/GitHub/IterativeResearch) + +> Downstream-usage evidence (Session 2). Claims are [agent] from a read-only survey with the load-bearing ones spot-verified first-hand [✓]. Citations refer to the app repo, **not** the NeoPZ pin. + +**What it is.** Research app for **iteratively solving saddle-point (mixed/incompressible) systems via a compressibility perturbation** (augmented-Lagrangian/Uzawa-style): add `−α` to the pressure diagonal so the system becomes SPD and Cholesky-factorizable once, then outer-iterate to recover the incompressible solution [✓ `sources/TPZMixedCompressibleDarcyFlow.cpp:233` — `ek(phrq+ip,phrq+ip) += -fAlpha*weight`]. Targets: `iterative-no-condense-darcy`, `iterative-condensed-darcy`, `iterative-condensed-stokes` (`targets/CMakeLists.txt:5-11`); shell scripts sweep mesh size × α ∈ [1e+1…1e−6]. + +**Library surface exercised** (beyond the divfreebubbles axis): +- **Spaces**: HDiv (`EHDivConstant`/`EHDivStandard`) flux × discontinuous L2 pressure × continuous H1 traction, combined in `TPZMultiphysicsCompMesh`. *Both* construction idioms: `TPZHDivApproxCreator` (Darcy, `iterative-condensed-darcy.cpp:448-472`) and fully **manual atomic-mesh assembly** for Stokes (4 atomic-mesh builders; `BuildMultiphysicsSpace`, `iterative-condensed-stokes.cpp:664-757`). +- **Manual hybridization of Stokes**: tangential-velocity/traction Lagrange spaces (`SetLagrangeMultiplier`), geometric-element surgery via `TPZGeoElBC` + `BuildConnectivity`, explicit `TPZMultiphysicsInterfaceElement` creation (`iterative-condensed-stokes.cpp:203-413`), then **manual `TPZElementGroup` + `TPZCondensedCompElT`** condensation (`:784-901`) — the do-it-yourself counterpart of what `TPZApproxCreator` automates ([[hybridization]], [[condensation-groups-submeshes]]). +- **Low-level Matrix/Solvers usage** [✓]: hand-assembled divergence operator Bᵀ as CSR `TPZFYsmpMatrix::SetData(iBT,jBT,valBT)` (`iterative-condensed-darcy.cpp:318`, `...-stokes.cpp:1066`); matrix-free `MultAdd` residual updates; `Clone()` of the global `TPZSYsmpMatrixPardiso` + direct diagonal mutation; `SetDefPositive(true)`; one factorization reused across all outer iterations. The "iterative" method is a bespoke outer loop around a direct inner solve — no `TPZMatRed`, no library Krylov. +- **Materials as the extension layer**: 4 custom materials, all on `TPZMatBase, TPZMatErrorCombinedSpaces, …>` [✓ `TPZMixedCompressibleDarcyFlow.h:25-26`; also `TPZHybridStokes`, `TPZHybridCompressibleStokes`, `TPZInterfaceStokes` (+`TPZLagrangeMultiplierBase`)]. No custom elements/struct-matrices/analyses. One material calls **`cblas_dgemm` directly inside `Contribute`** [✓ `TPZMixedCompressibleDarcyFlow.cpp:122,143,163`]. +- **Geometry/config**: `TPZGeoMeshTools::CreateGeoMeshOnGrid` structured grids (hex/tet/prism); `TPZGmshReader` Poiseuille meshes; JSON-driven problem config (`nlohmann::json`). Renumbering `EMetis` (direct) vs `ENone` (iterative). No refinement, no curved maps. + +**What it teaches about the library.** (1) The Matrix/Solvers layer is a *user-facing research surface*, not just plumbing — researchers hand-assemble coupling operators in CSR, clone and mutate Pardiso matrices, and exploit factorization reuse. (2) The manual Stokes path documents exactly what the creator layer abstracts away (and that vector-valued dim−1 multiplier spaces work). (3) Material-layer-only extension suffices for a whole solver-methodology study. + +Related: [[matrix-and-solvers]] · [[hybridization]] · [[condensation-groups-submeshes]] · [[mixed-methods]] · [[apps-overview]] diff --git a/ai-analysis/wiki/apps/app-mixed-elasticity.md b/ai-analysis/wiki/apps/app-mixed-elasticity.md new file mode 100644 index 000000000..837acca1f --- /dev/null +++ b/ai-analysis/wiki/apps/app-mixed-elasticity.md @@ -0,0 +1,32 @@ +--- +type: app-survey +status: reviewed +updated: 2026-07-06 +confidence: medium +evidence-commit: "app SymTensor @ 0a135dc (2025-05-19); embedded neopz develop @ 2937b5a90 (2025-05-26)" +tags: + - neopz + - downstream + - elasticity + - mixed-methods + - mhm +--- + +# App survey: MixedElasticity (~/GitHub/MixedElasticityResearch) + +> Downstream-usage evidence (Session 2). Claims [agent], load-bearing ones spot-verified [✓]. Citations refer to the app repo. + +**What it is.** Research code for **mixed (stress-based, Hellinger–Reissner) elasticity**: stress tensor as the primary H(div) unknown, L2 displacement, and symmetry enforced either **weakly** (rotation/skew multiplier — PEERS/AFW style) or **strongly** (a Johnson–Mercier symmetric-tensor element built at app level). Three subprojects: `Mixed2D` (~11 targets: square/oscillatory/Girkmann/Yotov/HPC4E benchmarks, 3- and 5-field, MHM variants, H1 reference), `MHM-Elas-3D` (`voronoi_mixed_elas` via library creator), `SymTensor` (newest thread, strongly symmetric tensors). + +**Library surface exercised:** +- **Tensor-valued H(div)**: stress rows as H(div) vectors with `NStateVariables = dim` — the same element family carrying matrix-valued fields, something scalar Darcy never shows. Displacement = discontinuous L2 via **`TPZCompElDiscScaled : TPZCompElDisc`** [✓ `Mixed2D/TPZCompelDiscScaled.h:17`] — shape functions scaled by element size for conditioning (a downstream subclass of the *discontinuous* element family). +- **Weak symmetry**: rotation/skew multiplier space (nstate 3 in 2D / 6 in 3D) + rigid-body constant multiplier spaces (distributed force, average displacement) — multiphysics meshes of **3, 5, and 7 fields** (`main.cpp:1249`, `main-five.cpp:676-713`, MHM 7-space drivers). Lagrange-level machinery orders their condensation. +- **Strong symmetry at app level (SymTensor)**: Johnson–Mercier macro-elements built from **custom runtime `TPZRefPattern`s** (`TriangleRef`/`QuadRef` → `CreateJohnsonMercier` [✓ `SymTensor/MeshConditioning.cpp:13,30,50`]) + continuous-but-disconnected elements with hand-stitched center-node continuity + a custom tensor interface `TPZInterfaceSymTensor : TPZLagrangeMultiplierCS` — a *new space family assembled downstream from library primitives* (refinement patterns used as a space-construction device, not just adaptivity). Includes rigid-body-mode verification via `SolveEigenProblem` on the assembled matrix (`main-sym.cpp:329-347`). +- **All three space-construction idioms in one repo**: manual `SetAllCreateFunctions*` builders (`TPZMixedElasticityCMeshCreator`), the library `TPZHDivApproxCreator` (`voronoi_mixed_elas.cpp:94-150` [✓ `ProblemType::EElastic` :96; rigid-body spaces off :97]), and `TPZHybridizeHDiv` procedural hybridization + `TPZCompMeshTools::GroupElements/CondenseElements` + manual `TPZElementGroup`/`TPZCondensedCompElT` (`MeshConditioning.cpp:539-578`). +- **MHM at scale**: `TPZMHMeshControl`/`TPZMHMixedMeshControl` with `BuildComputationalMesh(substruct=true)` [✓ `main-seven.cpp:1277`] — the *controller* generation of MHM (which the divfreebubbles slice bypassed in favor of app-side creators) driving `TPZSubCompMesh` substructuring for 2D/3D elasticity, incl. nearly-incompressible cases. +- Materials upstreamed: the app's `TPZMixedElasticityND` (combined-spaces, Voigt handling, axisymmetric option) has a library twin in `Elasticity/TPZMixedElasticityND` — a documented app→lib migration case (cf. the same-name-class risk in `CPP_TECHNICAL_REVIEW.md` §6). Note the divfreebubbles finding [[finding-voronoi-null-ganalytic]] concerns a same-named `voronoi_mixed_elas` driver — the lineage spans repos. +- Geometry: gmsh (incl. curved Girkmann dome via `TPZArc3D`+blend), `TPZGenGrid3D`, honeycomb meshes; struct-matrix breadth incl. `TPZParFrontStructMatrix` (frontal solver actually used downstream). + +**What it teaches about the library.** (1) The multiphysics + Lagrange-level design scales to 5–7 coupled fields without library changes. (2) Refinement patterns double as macro-element space constructors. (3) The MHM controller generation is alive downstream even as the creator generation replaces it — both must be treated as supported API. (4) App→lib material migration (`TPZMixedElasticityND`) is the concrete example of how the library grows. + +Related: [[mixed-methods]] · [[hybridization]] · [[mhm]] · [[condensation-groups-submeshes]] · [[element-families]] · [[refinement-hanging-nodes]] · [[apps-overview]] diff --git a/ai-analysis/wiki/apps/app-wann.md b/ai-analysis/wiki/apps/app-wann.md new file mode 100644 index 000000000..554ff9530 --- /dev/null +++ b/ai-analysis/wiki/apps/app-wann.md @@ -0,0 +1,31 @@ +--- +type: app-survey +status: reviewed +updated: 2026-07-06 +confidence: medium +evidence-commit: "app @ 2025-09-23 HEAD; embedded neopz develop @ f3b4000be (2025-09-18)" +tags: + - neopz + - downstream + - darcy + - multiscale-coupling +--- + +# App survey: wann (~/GitHub/WannResearch) + +> Downstream-usage evidence (Session 2). Claims [agent], load-bearing ones spot-verified [✓]. Note: agent citations said `sources/`; actual dir is `src/` (corrected below where verified). + +**What it is.** "Wellbore flow ANalysis using Neural Networks": a coupled **3D-reservoir + 1D-wellbore mixed-Darcy simulator** whose post-processed output (position → productivity index) trains a downstream PyTorch model. Targets: `wann3d` (JSON-configured coupled solve + VTK + ANN-training export), `wann3dRef` (adds an H1 companion mesh + H1-vs-mixed error estimator driving adaptive h-refinement), `oldwann3d`, `hanging-nodes-test`, `test-divide`. + +**Library surface exercised:** +- **Dimensionally heterogeneous multiphysics**: 3D HDiv reservoir + 2D H1 "pressure skin" on the well cylinder + 1D HDiv wellbore, glued in one `TPZMultiphysicsCompMesh` with `TPZLagrangeMultiplierCS` + `TPZMultiphysicsInterfaceElement` — hybridization/condensation machinery explicitly *disabled* (`SetShouldCondense(false)` [✓ `targets/old-wann3d.cpp:152`]). +- **Direct TPZConnect surgery** [✓ `src/TPZWannApproxTools.cpp:242-244,546`]: `AllocateNewConnect`, `SetConnectIndex`, `SetLagrangeMultiplier`, and hand-built **`AddDependency` restraints** to weld spaces of different dimension along the well — downstream code programs the connect/dependency layer directly ([[TPZConnect]]). +- **Curved geometry a-posteriori**: mesh nodes projected onto the well cylinder, then `TPZChangeEl::ChangeToCylinder` (exact `TPZCylinderMap`) with neighbor `ChangeToGeoBlend` transition elements [✓ `src/TPZWannGeometryTools.cpp:157,187`] — the SpecialMaps/blend workflow on an imported mesh ([[geometry-refinement-maps]]). +- **Refinement breadth**: uniform (`TPZCheckGeom::UniformRefine`), **directional refinement** toward well heel/toe (`gRefDBase.InitializeRefPatterns` + `TPZRefPatternTools::RefineDirectional` [✓ `src/TPZWannGeometryTools.cpp:34-36`]), and estimator-driven adaptive `gel->Divide` loops — refinement patterns exercised as a live research tool, not a legacy feature. +- **Custom material**: `TPZNonlinearWell : TPZMatBase, TPZMatErrorCombinedSpaces>` [✓ `src/TPZNonlinearWell.h:23`] — a nonlinear (friction/Forchheimer-type, |Q|^{3/4}) wellbore law hand-assembling a Newton tangent inside `Contribute`; compiled but not yet wired to a target (WIP). +- **Estimation**: hand-rolled H1-vs-mixed energy-norm comparison (two discretizations of the same problem as mutual error estimators), `std::thread`-parallel — a downstream pattern the [[app-error-estimation]] repo industrializes. +- Solvers: direct only (`TPZSSpStructMatrix` + `ELDLt`/`ECholesky`). Everything real-valued (`STATE`); no eigenproblems, no HCurl, no complex scalars [agent, exhaustive grep]. + +**What it teaches about the library.** (1) NeoPZ supports genuinely multi-dimensional coupled problems (3D/2D/1D in one mesh) — but at the cost of manual connect/dependency programming; there is no creator-level support for this pattern. (2) The connect-restraint (`AddDependency`) machinery doubles as a general-purpose coupling tool beyond hanging nodes. (3) Refinement patterns + cylinder/blend maps are actively used downstream. (4) The embedded neopz carries wann-motivated fixes on develop (boundary-element orientation, side-orient-aware dependency verification, 2025-09) — downstream needs drive library evolution. + +Related: [[TPZConnect]] · [[geometry-refinement-maps]] · [[refinement-hanging-nodes]] · [[multiphysics-composition]] · [[apps-overview]] diff --git a/ai-analysis/wiki/apps/apps-overview.md b/ai-analysis/wiki/apps/apps-overview.md new file mode 100644 index 000000000..5f7375f4b --- /dev/null +++ b/ai-analysis/wiki/apps/apps-overview.md @@ -0,0 +1,37 @@ +--- +type: app-survey +status: reviewed +updated: 2026-07-06 +confidence: medium +evidence-commit: "surveys of five app repos at their 2025-2026 HEADs (see each page)" +tags: + - neopz + - downstream + - usage-breadth +--- + +# Downstream usage survey — the five most recent NeoPZ applications + +**Purpose (Session 2).** The Session-1 assessment leaned on one application (divfreebubbles: mixed/hybrid H(div) Darcy + hybrid H1 elasticity). To judge the *library* rather than one usage of it, this survey reads the five most recently active application repos under `~/GitHub`, each embedding its own NeoPZ copy (all near-develop; branches noted per page). Method: one read-only explorer per repo, load-bearing claims spot-verified first-hand [✓]. Evidence class: app-repo evidence — **not** statements about the analysis pin. + +| App (last active) | Problem domain | Spaces used | Space-construction idiom | Distinctive library surface | +| ---------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| [[app-iterative-saddle-point]] (2026-03) | Uzawa/augmented-Lagrangian iteration for mixed Darcy & Stokes | HDiv(Constant/Standard) × L2 × H1 traction, multiphysics | creator (Darcy) + fully manual (Stokes) | hand-built CSR operators, Pardiso matrix cloning/mutation, factorization reuse; manual Stokes hybridization + manual condensation | +| [[app-gfem]] (2025-12) | GFEM fracture mechanics (jump + singular enrichment) | H1 only + multiphysics composition | manual + custom `TPZCompElH1` subclass | element-level shape enrichment via `ComputeShape` override; connect→function maps; SBFem eigenmodes as enrichment generator; custom StrMatrix/MatRed | +| [[app-error-estimation]] (2025-11) | a-posteriori estimation + h/hp-adaptivity | H1, HDiv(++), L2, multiphysics | manual + own space factory | solution reconstruction (clone/swap/average), patch solves, closed adaptive loops, quarter-point/collapsed/SBFem/NACA-blend geometry | +| [[app-wann]] (2025-09) | 3D reservoir + 1D wellbore coupled Darcy → ANN training data | HDiv × H1 skin × L2, multiphysics | creator + manual connect surgery | 3D/2D/1D dimensionally heterogeneous coupling via `AddDependency`; cylinder/blend curved maps; directional refinement | +| [[app-mixed-elasticity]] (2025-05) | stress-based (Hellinger–Reissner) elasticity, weak & strong symmetry | tensor-valued HDiv × L2 × rotation × RB constants (3–7 fields) | manual + creator + `TPZHybridizeHDiv` | weak-symmetry multipliers; Johnson–Mercier macro-elements from custom refpatterns; MHM controllers with `TPZSubCompMesh`; frontal solver | + +## Cross-cutting observations (feed the Session-2 deliverable revisions) + +1. **Every space family except H(curl) is heavily used downstream.** H1 is not a "lesser" space here — two of five apps are H1-centric (GFEM, much of ErrorEstimation). Discontinuous/L2 spaces appear in every mixed app (pressure, rotation, constants), including a downstream subclass of `TPZCompElDisc` (`TPZCompElDiscScaled`). H(curl)/electromagnetics and complex scalars did **not** appear in these five — that usage lives elsewhere (e.g. the older WGMAResearch line; noted as a boundary, not absence of capability). +2. **Manual space construction is alive and load-bearing.** All five apps use `SetAllCreateFunctions*` + atomic-mesh composition somewhere; three also use `TPZ*ApproxCreator`; two wrap their own space factories. The creator layer is a convenience roof, not the foundation — reviews must treat the low-level path as first-class API. +3. **The connect/dependency layer is a public research surface.** wann programs `AllocateNewConnect`/`AddDependency` directly for cross-dimensional coupling; GFEM keys enrichment functions to connect indices; MixedElasticity hand-stitches connect continuity for macro-elements. TPZConnect is not an internal detail ([[TPZConnect]]). +4. **MatRed-style block reduction is a recurring independent idiom** (divfreebubbles' `TPZSparseMatRed`, GFEM's `TPZSSpMatRedStructMatrix`+`TPZSparseMatRed`, Iterative's hand-built Schur loop) — three separate reimplementations of the same pattern argue for a first-class library citizen. +5. **Refinement patterns are used three ways**: adaptivity (ErrorEstimation), directional/geometric grading (wann, GFEM crack tips), and **space construction** (MixedElasticity's Johnson–Mercier splits). The runtime-pattern design earns its keep. +6. **The material mixin layer absorbs most extension needs**: ~20 downstream material classes across the five apps, typically `TPZMatBase` or subclasses of concrete physics materials; several carry estimation or nonlinear-Newton logic. Only GFEM needed a computational-element subclass; nobody needed to touch Topology/Shape/Geom internals. +7. **App→lib migration is the growth mechanism — and a standing risk.** Observed same-name classes across app/lib: `TPZMixedElasticityND`, `TPZHybridElasticity2D` (the ErrorEstimation copy edited 2025-11 vs the library delta file in this very working tree), `TPZMHMHDivApproxCreator`, `TPZSparseMatRed`. Include paths silently arbitrate which is compiled (cf. `CPP_TECHNICAL_REVIEW.md` §6). +8. **Embedded NeoPZ copies confirm the user's "few changes" description**: all five sit on develop or short-lived branches (`Australia25` ×2) whose recent commits are app-motivated library fixes (HDiv side-orient dependency checks for wann; eigenvector-loading and element-subdivision fixes for GFEM) — downstream needs drive library evolution in small increments. +9. **Solver usage is direct-dominated** (Pardiso/LDLt/Cholesky, one frontal user); the only Krylov uses are bespoke (GFEM's preconditioned CG on a Schur complement; Iterative's outer Uzawa loop). Eigen-analysis appears via SBFem groups and matrix-level `SolveEigenProblem`, not `TPZEigenAnalysis`. + +Related: [[divfree-support-lib]] (the sixth data point) · [[element-families]] · [[TPZConnect]] · [[multiphysics-composition]] · [[condensation-groups-submeshes]] diff --git a/ai-analysis/wiki/code/TPZAnalysis.md b/ai-analysis/wiki/code/TPZAnalysis.md new file mode 100644 index 000000000..053542266 --- /dev/null +++ b/ai-analysis/wiki/code/TPZAnalysis.md @@ -0,0 +1,36 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - analysis + - solver +--- + +# TPZAnalysis — the solve orchestrator + +## Responsibility +"Implements the sequence of actions to perform a finite element analysis" (header @brief [repo]): owns the [[TPZCompMesh]], equation renumbering, a [[structural-matrices|structural matrix]], a solver ([[matrix-and-solvers]]), the solution vector, exact-solution hooks, and post-processing ([[post-processing-vtk]], [[error-estimation-convergence]]). + +## Key facts (verified [repo], Analysis/TPZAnalysis.h) +- Members: `TPZGeoMesh* fGeoMesh`, `TPZCompMesh* fCompMesh`, `TPZGraphMesh* fGraphMesh[3]` (one per dim), `TPZSolutionMatrix fSolution`, `TPZSolver* fSolver`, scalar/vector/tensor post-process name tables (lines 61-80). +- Renumbering options: `RenumType {ENone, EDefault(Metis-or-Sloan), ESloan, ECutHillMcKee, ECutHillMcKeeFast, EMetis}` (lines 47-54) — bandwidth/fill reduction before equation numbering. +- Built-in preconditioner factory: `Precond::{Jacobi, BlockJacobi, Element, NodeCentered}` (lines 30-45). +- Subclasses: `TPZLinearAnalysis` (linear static; the one used by divfreebubbles), `TPZEigenAnalysis` (+quadratic), `pznonlinanalysis`, `pztransientanalysis`, `pzmganalysis` (multigrid), substructure/frontal variants [agent paths]. + +## Assemble/Solve mechanics (verified [repo Analysis/TPZLinearAnalysis.cpp:35-180]) +- `Assemble()` dispatches real/complex → `AssembleT`: if no struct matrix set, defaults to `TPZSpStructMatrix` (MKL) else nonsym skyline, with console notice; if no solver, defaults to LU; **matrix reuse**: if solver already holds a right-sized matrix it's zeroed and re-assembled in place, else `fStructMatrix->CreateAssemble(fRhs)` builds it (:57-90). RHS sized by `ComputeNumberofLoadCases()`. +- `Solve()` → `SolveT`: guards rhs size, respects `NReducedEquations()` (equation-filter path), computes residual norm, delegates to the `TPZMatrixSolver` (:128-180). + +## Canonical use (observed in `divfreebubbles/targets/iter_elast.cpp:274-337` [repo]) +`TPZLinearAnalysis an(cmesh, RenumType::ENone); an.SetExact(...); an.SetStructuralMatrix(matskl); an.SetSolver(step); an.Assemble(); an.Solve();` then error via `an.PostProcessError(...)` and VTK via `TPZVTKGenerator` (or legacy `DefineGraphMesh/PostProcess`). + +## Related +[[TPZCompMesh]] · [[structural-matrices]] · [[matrix-and-solvers]] · [[assembly]] · [[post-processing-vtk]] · [[error-estimation-convergence]] + +## Open questions +- `TPZAnalysis` is `TPZSavable` — is a full analysis actually serializable in practice? (persistence coverage is thin [agent]) → Phase 7. +- Ownership of `fSolver`/struct-matrix (raw pointers + clones?) → Phase 5. diff --git a/ai-analysis/wiki/code/TPZAutoPointer.md b/ai-analysis/wiki/code/TPZAutoPointer.md new file mode 100644 index 000000000..f5cea7d0f --- /dev/null +++ b/ai-analysis/wiki/code/TPZAutoPointer.md @@ -0,0 +1,28 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - util + - memory +--- + +# TPZAutoPointer — reference-counted smart pointer + +## Responsibility +NeoPZ's own shared-ownership smart pointer (predates std::shared_ptr; authored by P. Devloo). Wraps `T*` in a heap `TPZReference` holding the pointer + `std::atomic_int` counter (Util/tpzautopointer.h:36-60 [repo]). + +## Facts [repo] +- Thread-safe counting via atomics (commented-out legacy mutex machinery still visible, lines 23-30). +- Non-intrusive (external control block), no weak-pointer concept, no custom deleters (as far as read; full API pending). +- Pervasive in APIs alongside raw pointers: e.g. `TPZStructMatrix` accepts both `TPZCompMesh*` (non-owning) and `TPZAutoPointer` (StrMatrix/TPZStructMatrix.h:55-58), `TPZCompMesh` holds both `fReference` raw and `fGMesh` auto (pzcmesh.h:49-54). This dual convention is a recurring ownership-ambiguity theme → Phase 5. + +## Related +[[TPZCompMesh]] · [[structural-matrices]] · [[matrix-and-solvers]] + +## Open questions +- Conversion semantics between templated types (`TPZAutoPointerDynamicCast`?), aliasing, and cycles (gmesh↔cmesh back-pointers are raw, so no cycle leak — intentional?). +- Interaction with persistence (auto pointers in `Read/Write`). diff --git a/ai-analysis/wiki/code/TPZCompElHDiv.md b/ai-analysis/wiki/code/TPZCompElHDiv.md new file mode 100644 index 000000000..015478d48 --- /dev/null +++ b/ai-analysis/wiki/code/TPZCompElHDiv.md @@ -0,0 +1,42 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - neopz + - hdiv + - hcurl + - elements +--- + +# TPZCompElHDiv & vector-space element families + +## Responsibility +Computational elements implementing H(div)- and H(curl)-conforming spaces on the mesh: face/edge connects shared between neighbors carry the normal/tangential trace continuity; internal connects carry bubbles. + +## Key files [repo paths; internals to be verified in Phases 2/4] +- `Mesh/pzelchdiv.h` — `TPZCompElHDiv`: main H(div) element (template over topology). +- `Mesh/pzelchdivbound2.h` — boundary-side H(div) element (`TPZCompElHDivBound2`). +- `Mesh/TPZCompElHDivCollapsed.h` — collapsed-dimension H(div) elements (fracture flow). +- `Mesh/TPZCompElHDivDuplConnects*.h` — duplicated-connect variant (semi-hybridization support). +- `Mesh/TPZCompElKernelHDiv.h`, `TPZCompElKernelHDiv3D.h` — "kernel H(div)": divergence-free subspace elements built from curls/potentials → the divfreebubbles research topic. +- `Mesh/TPZCompElHCurl.h` (+ `TPZCompElHCurlFull` etc.), `Mesh/TPZHCurlEquationFilter.h` — H(curl) family. +- `Mesh/TPZCompElDisc.h` — discontinuous (L²) elements; `Mesh/pzelctemp.h` (`TPZIntelGen`) — generic H1 interpolated element. +- Shape-side counterparts in `Shape/TPZShapeHDiv*.h`, `Shape/TPZShapeHCurl*.h` → [[shape-functions]]. + +## Space "families" (flavors) [repo] +`Shape/TPZEnumApproxFamily.h` defines `HDivFamily {EHDivStandard, EHDivConstant, EHDivKernel}` (names per usage in divfreebubbles/UnitTests; exact enumerators to re-verify), `H1Family`, `HCurlFamily`. Family selection flows through [[approx-space-creators]] → element constructors → shape classes. `EHDivConstant` = constant-divergence flavor (RT0-like divergence structure with higher-order trace? → to pin down in Phase 3/4 vs Devloo-group papers). + +## Continuity & mapping mechanics (verified, Phase 4) +Conformity = shared face connects + a three-part orientation protocol: (1) `fSideOrient[face] = Reference()->NormalOrientation(side)` fixed at construction (`pzelchdiv.cpp:49-53`); (2) signs folded into master directions in the Shape layer (`TPZShapeHDiv.cpp:104`); (3) facet-DOF permutation gather from corner-node ids (`HDivPermutation`, `TPZShapeHDiv.cpp:407-459`) so neighbor facet functions match. Master→physical map = **contravariant Piola with |detJ| convention** applied in `ComputeShape` (`pzelchdiv.cpp:1032-1033` [repo read]); FAD branch for curved-element derivative exactness (`:979-1031`). Full trace: [[piola-transformations]]. Unit tests `drham_check`/`drham_permute_check`/`sideshape_continuity` validate exactly this protocol. + +## Related +[[shape-functions]] · [[topology-module]] · [[hdiv-space]] · [[hcurl-space]] · [[de-rham-complex]] · [[piola-transformations]] · [[approx-space-creators]] · [[mixed-methods]] + +## Session 2 note +The sibling families are now documented in [[element-families]] (H1/HCurl/discontinuous/interfaces). Contrast worth remembering: HDiv orientation = explicit `fSideOrient` sign array; HCurl = implicit node-id transform ids; H1 = shared connects only. HCurl's covariant transform confirmed (`TransformShape`) — see [[piola-transformations]]. + +## Open questions +- Relationship between `EHDivKernel` elements and `TPZCompElKernelHDiv` (same thing? flavor vs class split?). diff --git a/ai-analysis/wiki/code/TPZCompMesh.md b/ai-analysis/wiki/code/TPZCompMesh.md new file mode 100644 index 000000000..3766e24cf --- /dev/null +++ b/ai-analysis/wiki/code/TPZCompMesh.md @@ -0,0 +1,41 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - mesh + - approximation +--- + +# TPZCompMesh — computational mesh + +## Responsibility +The discretization object: computational elements (`TPZCompEl`), connects (DOF bundles), materials, the block structure of the solution, and the solution vector itself. Built *over* a [[TPZGeoMesh]]; the approximation space flavor is decided by an embedded factory ([[approx-space-creators]]). + +## Key files +- `Mesh/pzcmesh.h` / `.cpp` [repo]: members `TPZGeoMesh* fReference` (+ optional owning `TPZAutoPointer fGMesh` — *dual raw/smart reference*, pzcmesh.h:49-54), `TPZAdmChunkVector fElementVec`, `TPZAdmChunkVector fConnectVec`, `std::map fMaterialVec`, `TPZBlock fSolutionBlock`, `TPZSolutionMatrix fSolution` (pzcmesh.h:59-72). Includes `pzcreateapproxspace.h` (Pre/) at pzcmesh.h:18 — Mesh↔Pre coupling. +- `Mesh/pzconnect.h` — `TPZConnect`: order, number of state vars, sequence number into the block structure, dependency matrices (hanging-node constraints), Lagrange multiplier level. Central to [[assembly]] and [[static-condensation]]. *(field list [agent]; re-verify Phase 2)* +- `Mesh/pzcompel.h` — abstract `TPZCompEl`; `Mesh/pzinterpolationspace.h` + `Mesh/pzintel.h` — interpolation-space layer (`TPZInterpolatedElement`) implementing p-orders, side connects, constraints. +- `Mesh/TPZMultiphysicsCompMesh.h` — combines several atomic cmeshes (flux, pressure, …) into one multiphysics space → [[mixed-methods]]. +- `Mesh/pzsubcmesh.h` — `TPZSubCompMesh`: a cmesh that *is* a computational element of a parent mesh (substructuring / [[mhm]]). +- `Mesh/pzcondensedcompel.h`, `Mesh/pzelementgroup.h` — element grouping + static condensation wrappers → [[static-condensation]]. +- `Mesh/pzelmat.h` / `TPZElementMatrixT.h` — element matrices (`ek`, `ef`) produced during [[assembly]]. + +## Notable design facts +- Connects (not nodes) are the DOF unit: an H(div) element has face connects + an internal connect; continuity is imposed by *sharing connects* across elements. [repo pattern; detailed verification in Phase 2/4] +- `TPZConnect` carries hanging-node dependency matrices (`TPZDepend`) — constraints are resolved at assembly time, not by modifying shape functions. *(mechanism [agent]; verify in [[refinement-hanging-nodes]] trace)* +- The mesh owns an `ApproxSpace()` (`TPZCreateApproximationSpace`) that stamps which element type gets created per geometry → [[approx-space-creators]]. +- `NEquations()` reflects condensed system size vs `Solution().Rows()` full size (used by divfreebubbles `iter_elast.cpp:257-272` [repo]). + +## Related +[[TPZGeoMesh]] · [[approx-space-creators]] · [[material-system]] · [[assembly]] · [[static-condensation]] · [[structural-matrices]] · [[persistence]] + +## Session 2 additions +- `fBlock` vs `fSolutionBlock` **resolved**: both index `fSolution`; `fBlock` is the *target* layout, `fSolutionBlock` the *current* one — `ExpandSolutionInternal` resequences, copies block-by-block, then assigns `fSolutionBlock = fBlock` (`pzcmesh.cpp:484-525`). Renumbering strata and `SaddlePermute` Lagrange-level ordering: [[TPZConnect]]. +- Deep-dive pages now exist for the composition layers this page indexes: [[TPZConnect]], [[multiphysics-composition]], [[condensation-groups-submeshes]], [[element-families]]. + +## Open questions +- Who owns materials? (`fMaterialVec` holds raw pointers; `TPZCompMesh` destructor behavior → Phase 5 ownership review.) diff --git a/ai-analysis/wiki/code/TPZConnect.md b/ai-analysis/wiki/code/TPZConnect.md new file mode 100644 index 000000000..fdcc04de2 --- /dev/null +++ b/ai-analysis/wiki/code/TPZConnect.md @@ -0,0 +1,40 @@ +--- +type: code +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - mesh + - dof + - restraints +--- + +# TPZConnect — DOF bundles, restraints, Lagrange levels + +Session-2 deep dive (agent trace, load-bearing lines re-verified [✓]). The DOF unit of the library: everything the user described as "shape function restraints" lives here. + +## Anatomy (`Mesh/pzconnect.h`) +- `fSequenceNumber` (:32) — block number in `TPZCompMesh::fBlock`; −1 = unused. The single indirection connect→equations. +- `fNElConnected` (:35) — reference count of elements using this connect; **the** input to condensation decisions (`NElConnected()==1` ⇒ internal). +- Packed `union {fFlags; struct{fOrder, fNState, fLagrangeMultiplier, fIsCondensed}}` [✓ :42-60] — order, states/shape, **Lagrange level** (a small integer, not a bool: "level n multipliers need to be numbered after the multipliers of level n−1"), condensed flag, all in 4 bytes. +- `fNShape` (:60); `NDof() = fNShape*fNState` (:174-177). + +## Dependency (restraint) machinery +- `fDependList` (:131): singly linked `TPZDependBase` list; `TPZDepend` (:95-128) adds `fDepMatrix` — real and complex restraints coexist by templating. +- Semantics: dependent connect's DOFs = dep-matrix combination of the master's. Two interpretations at assembly (`Mesh/TPZElementMatrixT.cpp:327-343`): *shape* restraints (block-diagonal expansion by nstate) vs *algebraic* restraints (matrix as-is). +- **Creation** — the hanging-node path: `TPZInterpolatedElement::RestrainSideT` (`Mesh/pzintel.cpp:872-1131`) builds a side mass matrix `M` (small side) + cross matrix `MSL` against the large neighbor's trace (pulled back through the geometric `SideTransform3`), solves `M⁻¹·MSL` by LU [✓ :964-967], and registers per-connect-pair blocks via `AddDependency` [✓ :1047-1050] (blocks with norm <1e-8 zeroed). So a hanging connect's restraint is literally the L2 projection of the coarse trace basis; the only geometric input is the side transform ([[geometry-refinement-maps]] §3). HCurl and HDiv override `RestrainSide` (`TPZCompElHCurl.cpp:622`, `pzelchdiv.cpp:1193-1196`). +- **Application** — per element in `TPZElementMatrixT::ApplyConstraints` (`TPZElementMatrixT.cpp:135-393`): `BuildConnectList` closes the set over masters; `BuildDependencyOrder` (`pzconnect.cpp:623-662`) fixes a topological order; then the congruence transform `Dᴴ·K·D` is applied through `TPZMatrixWindow::MultAdd` with **conjugate-transpose** flag [✓ `transp_a=2`, :359-366] — complex-correct. The shape-level analog `ExpandShape` (`pzconnect.cpp:387-444`) is real-only and hard-aborts on complex (:402-408). +- Downstream evidence that this is public API: wann glues 3D/2D/1D spaces with hand-built `AddDependency` calls ([[app-wann]]); GFEM keys enrichment functions to connect indices ([[app-gfem]]). + +## Invariants (enforced by DebugStop, not types) +- **Condensed and dependent are mutually exclusive**: `CleanUpUnconnectedNodes` DebugStops on the combination [✓ `pzcmesh.cpp:618-624`, PZDEBUG only]; `TPZCondensedCompElT::Resequence` refuses to condense a dependent connect (`pzcondensedcompel.cpp:310-314`). +- `Reset()` DebugStops if `fDependList` non-null (`pzconnect.h:151-155`) — callers must `RemoveDepend()` first (e.g. `TPZMultiphysicsCompMesh.cpp:44-47`). + +## Block structure & ordering (`Mesh/pzcmesh.cpp`) +- `fBlock` (target layout) vs `fSolutionBlock` (current layout of `fSolution`); `ExpandSolutionInternal` (:484-525) resequences and copies block-by-block, then `fSolutionBlock = fBlock`. +- `CleanUpUnconnectedNodes` (:588-798) renumbers into strata: **independent → condensed → dependent → freed** (:615-704). +- `SaddlePermute` (:2465-2723; an older version at :2372 is retired) orders connects globally by ascending Lagrange level so saddle-point factorizations eliminate in the right order — the mechanism behind "Lagrange levels order condensability" ([[static-condensation]], [[hybridization]]). Submesh variants subtract external connects. + +Related: [[TPZCompMesh]] · [[refinement-hanging-nodes]] · [[condensation-groups-submeshes]] · [[multiphysics-composition]] · [[assembly]] diff --git a/ai-analysis/wiki/code/TPZGeoMesh.md b/ai-analysis/wiki/code/TPZGeoMesh.md new file mode 100644 index 000000000..def789465 --- /dev/null +++ b/ai-analysis/wiki/code/TPZGeoMesh.md @@ -0,0 +1,37 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - mesh + - geometry +--- + +# TPZGeoMesh — geometric mesh + +## Responsibility +Container for the *geometry and topology* of the discretization: geometric elements, nodes, and elementwise/nodal BC identifiers — no degrees of freedom (those live in [[TPZCompMesh]]). Holds the refinement genealogy (father/son element trees) that underpins [[refinement-hanging-nodes]]. + +## Key files +- `Mesh/pzgmesh.h` / `.cpp` — the mesh: `TPZAdmChunkVector fElementVec`, `TPZAdmChunkVector fNodeVec`, mesh dimension `fDim`, name, and a back-pointer `TPZCompMesh* fReference` (pzgmesh.h:48-70 [repo]). +- `Mesh/pzgeoel.h` — abstract `TPZGeoEl` (element = topology + material id + node indices + neighbor connectivity via sides). +- `Mesh/pzgeoelside.h` — `TPZGeoElSide`: the (element, side) pair used for all neighborhood traversal; neighbors form circular linked lists along shared sides. *(mechanism [agent]; verify in Phase 2 traces)* +- `Mesh/pzgeoelrefless.h(.h)` — `TPZGeoElRefLess`: concrete element without refinement capability; template body in the unusual `.h.h` companion file. +- `Mesh/tpzgeoelrefpattern.h(.h)` — `TPZGeoElRefPattern`: refinable element driven by [[refinement-hanging-nodes|refinement patterns]]. +- `Geom/*` + `SpecialMaps/*` — the per-topology map classes `TGeo` plugged into the element templates → [[geometric-mappings]]. + +## Notable design facts [repo] +- `GMESHNOMATERIAL -9999` sentinel for "no material" (pzgmesh.h:24). +- Interface-material map keyed by material-id pairs (pzgmesh.h:72-75) — supports DG/interface constructions. +- Mutual raw-pointer reference with the computational mesh (`fReference` both ways; pzcmesh.h:49) — the "reference" mechanism used to associate geo↔comp elements. Lifetime/ownership implications → Phase 5. +- Storage is chunked (`TPZAdmChunkVector`) so element/node pointers survive vector growth; free slots are recycled. + +## Related +[[TPZCompMesh]] · [[geometric-mappings]] · [[refinement-hanging-nodes]] · [[topology-module]] · [[mesh-io-generators]] + +## Open questions +- Exact semantics of `ResetReference/LoadReferences` in multi-cmesh (multiphysics) workflows — needed for the Phase 2 flow traces. +- Ownership: who deletes `TPZGeoEl*` — mesh destructor? (Phase 5 lifetime review.) diff --git a/ai-analysis/wiki/code/approx-space-creators.md b/ai-analysis/wiki/code/approx-space-creators.md new file mode 100644 index 000000000..8d2e85d50 --- /dev/null +++ b/ai-analysis/wiki/code/approx-space-creators.md @@ -0,0 +1,36 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - approximation + - hybridization +--- + +# Approximation-space creators + +## Responsibility +Two layers that decide *which computational element type* is instantiated on each geometric element, and orchestrate multi-mesh (multiphysics) space construction, hybridization and condensation. + +## Layer 1 — element factory (verified [repo]) +`Pre/pzcreateapproxspace.h` — `TPZCreateApproximationSpace` (Devloo, since 2009; header @brief "Administer the creation of approximation spaces"): a table of 8 function pointers `TCreateFunction fp[8]` (one per element topology: point…cube) plus flags (`fCreateHybridMesh`, `fCreateLagrangeMultiplier`, `fCreateWithMemory`) and space-family flavors `HDivFamily/H1Family/HCurlFamily` (pzcreateapproxspace.h:27-53). Styles: `EContinuous, EDiscontinuous, EHDiv, EHCurl, EMultiphysics, ESBFem, …` (line 50). Every [[TPZCompMesh]] embeds one (pzcmesh.h:18 include). +**Correction C1:** an explorer report placed this file in `Mesh/`; it is in `Pre/` (see log). +**OQ1:** copy ctor/`operator=` appear not to copy the family flags / style (lines 58-75, tail unread) — verify in Phase 5. + +## Layer 2 — problem-level creators (verified [repo]) +`Pre/TPZApproxCreator.h` — abstract base `TPZApproxCreator`: holds `HybridizationType {ENone, EStandard, EStandardSquared, ESemi}`, `ProblemType {ENone, EElastic, EDarcy, EStokes}`, material map, default p-order, `fExtraInternalPOrder` (hdiv+/hdiv++), `fShouldCondense`, `fIsRBSpaces` (rigid-body/constant enrichment enabling full internal condensation), and a nested `HybridizationData` struct managing wrap/interface/Lagrange material ids (TPZApproxCreator.h:15-16,38-100). +Concrete: `Pre/TPZHDivApproxCreator.{h,cpp}` (mixed H(div)×L² spaces), `Pre/TPZH1ApproxCreator.{h,cpp}` (**in the 5-file develop delta** — hybrid H1 spaces; cite only after `git show develop:` cross-check), MHM variants `Pre/TPZMHMHDivApproxCreator.h` / `TPZMHMH1ApproxCreator.h` [agent]. +Older/parallel machinery: `Pre/TPZHybridizeHDiv.h` (procedural H(div) hybridization used by e.g. divfreebubbles `2frac`), MHM mesh controllers `Pre/TPZMHMeshControl.h`, `TPZMHMixedMeshControl.h`, `TPZMHMixedHybridMeshControl.h` [agent] → [[mhm]]. + +## Downstream extension +divfreebubbles derives `TPZH1HybridApproxCreator` (app-side) adding `ComputeOrthogonalizingRestraints`, `HybridizeLowOrderFluxes`, `GroupAndCondenseElements` (used in `targets/iter_elast.cpp:218-233` [repo]) → [[divfree-support-lib]], [[flow-iter-elast]]. + +## Related +[[TPZCompMesh]] · [[hybridization]] · [[static-condensation]] · [[mixed-methods]] · [[TPZCompElHDiv]] · [[material-system]] · [[mhm]] + +## Open questions +- Division of labor between `TPZHybridizeHDiv` (older) and `TPZApproxCreator` hybridization (newer): duplication or complementary? → Phase 4/5. +- Meaning and math of `EStandardSquared` ("squared" hybridization — Lagrange multiplier hybridized twice?) and `ESemi` (semi-hybridization) → [[hybridization]] research, Phase 3, vs Devloo-group papers. diff --git a/ai-analysis/wiki/code/condensation-groups-submeshes.md b/ai-analysis/wiki/code/condensation-groups-submeshes.md new file mode 100644 index 000000000..e0ce55093 --- /dev/null +++ b/ai-analysis/wiki/code/condensation-groups-submeshes.md @@ -0,0 +1,40 @@ +--- +type: code +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 (working-tree notes marked) +tags: + - neopz + - mesh + - condensation + - substructuring +--- + +# Element composition: TPZElementGroup, TPZCondensedCompEl, TPZSubCompMesh + +Session-2 deep dive (agent trace, load-bearing lines re-verified [✓]). The three composition layers the user-visible concepts ([[static-condensation]], [[mhm]]) are built from. + +## TPZElementGroup (`Mesh/pzelementgroup.{h,cpp}`) +A `TPZCompEl` owning a stack of elements + the union of their connects (`.h:24-25`). `AddElement` merges connects and **hides the element from the mesh** (nulls its `fElementVec` slot, `.cpp:72`); `Unwrap` restores. `CalcStiffInternal` (`.cpp:218-323`) sums member `ek/ef` into one dense block by connect map — pure summation, no elimination. `ReorderConnects` (`.cpp:116-145`) puts internal connects (`NElConnected()==1`, no dependency) first; `ExpandConnects` (`.cpp:431-448`) closes the connect list over dependency masters — called right before condensation wrapping. Downstream subclassing exists (`TPZSBFemElementGroupPostProcess` in [[app-error-estimation]]; `TPZSBFemElementGroup` in-library, [[sbfem]]). + +## TPZCondensedCompEl (`Mesh/pzcondensedcompel.{h,cpp}`) +Decorator holding `fReferenceCompEl` + split connect lists; `NConnects()/ConnectIndex()` expose **only active connects** (`.h:52-65`) — that is the whole trick. `TPZCondensedCompElT` owns a `TPZMatRed> fCondensed` (`.h:192`). +- `Resequence` (`.cpp:286-377`): any connect with `NElConnected()==1 && !HasDependency()` is force-condensed (:302-305); dependent connects can never be condensed [✓ DebugStop :310-314]; partition = condensed | active | dependent-but-kept. +- `CalcStiff` (`.cpp:384-693`): reference `CalcStiff` → `ApplyConstraints` **first** (:420-422, restraints before condensation) → reorder to `[condensed|active]` → `fCondensed.K11Reduced(K11,F1)` Schur complement → only the active block reaches the global matrix. `SetKeepMatrix(false)` frees internal blocks after condensation (:687-692) — the memory mode used by the HDiv creator. An experimental `USING_DGER` in-place LDLᵀ path (:468-579) DebugStops for non-double. +- `LoadSolution` (`.cpp:733-841`): gathers the active solution, `fCondensed.UGlobal(u1, elsol)` back-substitutes internals (:810), scatters into the mesh solution, recurses into the wrapped element — the implicit recovery step observed in every flow. + +## TPZSubCompMesh (`Mesh/pzsubcmesh.{h,cpp}`, `Analysis/pzsmanal.cpp`) +Multiple-inherits **`TPZCompMesh` and `TPZCompEl`** [✓ `.h:32-35`] — a mesh that is an element of its father (the Schur-complement substructuring unit the user described). +- Bookkeeping: `fConnectIndex` (father indices of external connects), `fExternalLocIndex` (−1 = internal), father↔local maps (`.h:46-54`). `TransferElement`/`MakeAllInternal` demote connects to internal when `NElConnected()==1`, co-transferring dependency masters (`.cpp:484-571`). +- `SetAnalysis{Sparse,NonSymSparse,Skyline,Frontal}` install an internal `TPZSubMeshAnalysis` and — order matters — run `SaddlePermute()` **then** `PermuteExternalConnects()` before matrix creation (e.g. `.cpp:1385,1394`), giving the layout `[internal | external | constrained]`; the struct matrix's equation filter is restricted to `0..numinternal` (:1400). A GMRES-preconditioned option exists (:1408-1421). +- Schur exposure: father calls `CalcStiffInternal` (`.cpp:999-1225`) → `TPZSubMeshAnalysis::CondensedSolution` → `matred->K11Reduced(ek,ef)` [✓ `pzsmanal.cpp:152-158`] — condensed stiffness over external connects only; `AssembleInternal` builds the `TPZMatRed(numeq,numinternal)` and passes the **rigid-body-mode count** (`pzsmanal.cpp:108`). `LoadSolution` reverses via `UGlobal`. +- Floating substructures: `SetNumberRigidBodyModes(nrigid, lagrange)` (`.cpp:2124-2169`) allocates a tagged singular connect so `TPZMatRed` avoids factorizing a singular K00 — the library-level mechanism behind MHM's rigid-body coarse spaces. +- Drivers: `TPZCompMeshTools::PutinSubmeshes` (`Mesh/TPZCompMeshTools.cpp:462-529`) with `KeepOneLagrangian` (fixes the rigid mode); MHM controllers create submeshes directly (`Pre/TPZMHMeshControl.cpp:1413`). + +## Composition pipeline & ordering constraints (fragile, DebugStop-enforced) +Canonical creator sequence (`TPZHDivApproxCreator::GroupAndCondenseElements`, `Pre/TPZHDivApproxCreator.cpp:658-710`): associate → `TPZElementGroup`s → **`ComputeNodElCon()` after grouping** (:691) → wrap in `TPZCondensedCompElT` with `SetKeepMatrix(false)` → `CleanUpUnconnectedNodes()`. Invariants: restraints resolve before condensation; condensed ∧ dependent is illegal (PZDEBUG DebugStop, `pzcmesh.cpp:618-624`); `SaddlePermute` before external-connect permutation before matrix creation; multiphysics `AddConnects` must re-offset dependency masters. *Working-tree note*: commit `852a5116c` (post-pin) split the H1 creator's `GroupElements`/`CondenseElements` and made the latter virtual — `TPZCompMeshTools::CondenseElements` keeps connects with `LagrangeMultiplier() >= LagrangeLevelNotCondensed` out by pre-incrementing `NElConnected` (`TPZCompMeshTools.cpp:607-618`), with a deliberately commented-out guard at :631. + +Downstream: manual `TPZElementGroup`+`TPZCondensedCompElT` composition in [[app-iterative-saddle-point]] and [[app-mixed-elasticity]]; submesh-aware estimators in [[app-error-estimation]]. + +Related: [[static-condensation]] · [[TPZConnect]] · [[matrix-and-solvers]] (TPZMatRed) · [[mhm]] · [[multiphysics-composition]] diff --git a/ai-analysis/wiki/code/divfree-support-lib.md b/ai-analysis/wiki/code/divfree-support-lib.md new file mode 100644 index 000000000..7395f9939 --- /dev/null +++ b/ai-analysis/wiki/code/divfree-support-lib.md @@ -0,0 +1,30 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - application + - hdiv +--- + +# divfree/ — application support library (repo: ../divfreebubbles) + +> Application-repo code (branch `3DKernelHdiv`), **not** part of NeoPZ. It is the vehicle for the execution-flow analysis and shows how downstream research code extends the library. + +## Contents [repo paths under `divfreebubbles/divfree/`; purposes agent-cited, key ones verified via iter_elast] +- **Materials**: `TPZMatDivFreeBubbles.h` (namesake Laplace-with-divfree-bubbles), `TPZMixedDarcyH1.h`, `TPZMixedDarcyFlowHybrid.h`, `TPZMixedDarcyFlowOrtotropic.h` (+`TPZOrtotropicPermeability`), `TPZMatCurlDotCurl.h`. +- **Creators**: `TPZH1HybridApproxCreator.h` — derives NeoPZ `Pre/TPZH1ApproxCreator` (a develop-delta file); adds `ComputeOrthogonalizingRestraints`, `HybridizeLowOrderFluxes`, `GroupAndCondenseElements` (called in `targets/iter_elast.cpp:229-233` [repo]). `TPZMHMGeoMeshCreator.h`, `TPZMHMHDivApproxCreator.h`, `TPZMixedElasticityCMeshCreator.h`. +- **Custom elements** (excluded from current build [agent]): `TPZCompElHDivDuplConnects{,Bound}.h` (duplicated connects for semi-hybridization), `TPZCompElConstFluxHybrid.h`, `TPZAlgebraicInterface.h`. +- **Solvers**: `TPZMatRedSolver.h` — Schur-complement/matrix-reduction driver, modes `EDefault/EDarcyHDiv/EDarcyH1Hybrid/EMHMSparse`; `TPZSparseMatRed.h`, `TPZDoubleMatRed.h`. Relationship to NeoPZ's own `TPZMatRed` → open question in [[matrix-and-solvers]]. +- **Utils**: `TPZKernelHdivUtils.h` (print/solve/error helpers used by most targets), `TPZKernelHdivHybridizer.h` (excluded from build), `Common.{h,cpp}` (enums, `LaplaceExact`, UNSW quadtree reader), vendored `JSON.hpp`, generated `divfree_config.h` (absolute `MESHDIR`). +- `deprecated/TPZHDivApproxSpaceCreator.h` — superseded 50KB space creator [agent]. + +## Why it matters for the NeoPZ assessment +- Shows the *extension surface* actually used by researchers: derive approx creators, add materials, wrap solvers → extensibility evidence for Phase 5. +- The semi-hybrid / duplicated-connects / kernel-H(div) line here mirrors in-library counterparts (`Mesh/TPZCompElHDivDuplConnects*`, `TPZCompElKernelHDiv*`) — migration path app→lib visible in git history [inference]. + +## Related +[[approx-space-creators]] · [[TPZCompElHDiv]] · [[hybridization]] · [[flow-iter-elast]] · [[flow-dupl-connects]] · [[flow-mhm-hdivconstant]] · [[apps-overview]] (Session 2: five more downstream apps surveyed — this repo is one data point of six) diff --git a/ai-analysis/wiki/code/element-families.md b/ai-analysis/wiki/code/element-families.md new file mode 100644 index 000000000..a2bb27c8f --- /dev/null +++ b/ai-analysis/wiki/code/element-families.md @@ -0,0 +1,44 @@ +--- +type: code +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - elements + - h1 + - hcurl + - discontinuous +--- + +# Element families beyond H(div): H1, H(curl), discontinuous, interfaces + +Session-2 deep dive (agent trace, load-bearing lines re-verified [✓]). Companion to [[TPZCompElHDiv]] — fills in the families Session 1 under-covered. + +## H1 continuous — `TPZCompElH1` +`TPZCompElH1 : TPZIntelGen : TPZInterpolatedElement` (`Mesh/TPZCompElH1.h:11-12`, `pzelctemp.h:19-20`). **One connect per topological side including corners** (`fConnectIndexes[TSHAPE::NSides]`, `NConnects()==NSides`); side↔connect maps forward to the topology. `SetSideOrder` (`TPZCompElH1.cpp:164-213`) propagates order changes to block sizes and neighbor integration rules; `EffectiveSideOrder` = max over contained sub-sides (:216-243) — the face≥edge order rule. Shape work delegates to `TPZShapeH1` (corner × generating-function blend + internal). Hanging nodes: inherits the generic scalar `RestrainSide` — full support. +**H1Family subtlety** [✓ `pzcreateapproxspace.cpp:111-121`]: `fh1fam` is stored but never branched on at runtime — `EH1WidePrism` is resolved *at creation* by instantiating `TPZCompElH1` instead of ``. Only prisms have a variant; for all other topologies the family is a no-op. + +## H(curl) — `TPZCompElHCurl` +Same `TPZIntelGen` skeleton, different DOF model: **no vertex connects** (`fConnectIndexes[NSides−NCornerNodes]`, `TPZCompElHCurl.h:24-25`); connects self-built in `CreateHCurlConnects` (`.cpp:598-618`). `HCurlFamily` **is a live runtime switch** (`fhcurlfam`): `NConnectShapeF`/`InitMaterialData`/`ComputeShape` branch to `TPZShapeHCurl` vs `TPZShapeHCurlNoGrads` with deliberate no-default switches (`.cpp:215-228,309-318,374-382`). +- **Covariant Piola** applied in `TransformShape` [✓ `.cpp:564-578`, comment "applies covariant piola transform"]: `phi = axesᵀ·J⁻ᵀ·phî`; curl transformed separately (`TransformCurl`, 3D: `J·curl̂/detJ`; 1D/2D: `curl̂/detJ`) — closing the "H(curl) covariant trace not yet done" item in [[piola-transformations]] at the structural level. +- **Orientation: implicit via node-id transform ids** (`TPZShapeHCurl::Initialize` → `GetTransformId` → `ComputeHCurlDirections`), vs HDiv's explicit `fSideOrient` sign array — the two vector families solve the same problem by different protocols. +- Own vector-valued `RestrainSideT` (L2 trace projection, `.cpp:620+`; DebugStops if small-side order < large-side order :671-672) — hanging nodes supported via a dedicated path. +- Dead-ends: **pyramid and point unavailable** [✓ `HCURL_EL_NOT_AVAILABLE` → DebugStop, `pzcreateapproxspace.cpp:726-728`]; map-clone ctor DebugStops ("never tested, better safe than sorry", `TPZCompElHCurl.cpp:59`). + +## Discontinuous — `TPZCompElDisc` +Derives **directly from `TPZInterpolationSpace`** (not `TPZInterpolatedElement`): **a single connect for the whole element** [✓ `TPZCompElDisc.cpp:377-383`]. Modal/orthogonal basis about the element center (`TPZShapeDisc`, types {ETensorial, EOrdemTotal, …Full}), normalizing constant `fConstC`, optional evaluation in global X coords, and **appendable external shape functions** (`fExternalShape`) — the enrichment hook. No side connects ⇒ no restraints; continuity is weak (interfaces). Created via `SetAllCreateFunctionsDiscontinuous()` (all topologies → `TPZCompElDisc::CreateDisc`). Downstream subclass: `TPZCompElDiscScaled` (element-size scaling, [[app-mixed-elasticity]]). + +## How mixed meshes realize L2 pressure (nuance worth remembering) +[✓ `TPZHDivApproxCreator::CreateL2Space`, `TPZHDivApproxCreator.cpp:465-478`]: for p>0 the "L2" mesh is **broken-H1** — `SetAllCreateFunctionsContinuous()` + `ApproxSpace().CreateDisconnectedElements(true)`, where disconnection is achieved by `ResetReference()` right after each element's creation (`pzcreateapproxspace.cpp:232-234`, flag `fCreateHybridMesh`), so neighbors can't share connects; for p=0 (and always for `EHDivConstant`) it is a genuine order-0 `TPZCompElDisc`. There is **no** `EDisconnected` enum. `TPZL2Projection(/CS/HDiv/HCurl)` are *materials* (projection weak forms), orthogonal to the element choice. + +## Interface elements & the DG path +- Single-space: `TPZInterfaceElement : TPZCompEl` (`TPZInterfaceEl.h:29`) stores left/right `TPZCompElSide`s + center normal; requires the material to implement `TPZMatInterfaceSingleSpace` (dynamic_cast, `.cpp:256-257`) and calls `ContributeInterface(data, dataleft, dataright, …)` — classic DG jump/flux terms. Auto-created by `TPZInterpolationSpace::CreateInterfaces` where a neighbor is discontinuous (`pzinterpolationspace.cpp:760-849`). +- Multiphysics: `TPZMultiphysicsInterfaceElement` + `TPZMatInterfaceCombinedSpaces` (`TPZMultiphysicsInterfaceEl.cpp:335-336,424`) — the glue of [[hybridization]] and of downstream Lagrange couplings ([[app-wann]], [[app-iterative-saddle-point]]). +- **The DG recipe is compositional**, not a dedicated creator: discontinuous (or broken-H1) space → `AutoBuild` → `TPZCreateApproximationSpace::CreateInterfaceElements` (`pzcreateapproxspace.cpp:1243-1268`) → interface-capable material. `AutoBuildContDisc` supports mixed continuous+discontinuous partitions. (No `SetAllCreateFunctionsDiscontinuousReferred` exists.) + +## Dispatch summary (`Pre/pzcreateapproxspace.{h,cpp}`) +8-slot `std::function` table `fp[8]` per topology; `CreateCompEl` switches on `gel->Type()` (:1059-1091); style tracked in `fStyle {ENone, EContinuous, EDiscontinuous, EHDiv, EHCurl, EMultiphysics, EMultiphysicsSBFem, ESBFem, ECustom}`. Full `SetAllCreateFunctions*` inventory: Continuous(+WithMem), Discontinuous, HDiv(+DuplConnects, +Pressure — the latter `#ifndef STATE_COMPLEX`), HCurl(+WithMem), SBFem(+Multiphysics, LAPACK-gated), MultiphysicElem(+WithMem), custom table (`SetCreateFunctions`). Family flavors (`fh1fam/fhdivfam/fhcurlfam`) are captured into the creation lambdas. An abandoned `SetAllCreateFunctionsHDivFull` block sits commented at :927-969. + +Related: [[TPZCompElHDiv]] · [[shape-functions]] · [[approx-space-creators]] · [[TPZConnect]] · [[discontinuous-l2-dg]] · [[h1-space]] · [[hcurl-space]] diff --git a/ai-analysis/wiki/code/geometry-refinement-maps.md b/ai-analysis/wiki/code/geometry-refinement-maps.md new file mode 100644 index 000000000..bf66a2b7d --- /dev/null +++ b/ai-analysis/wiki/code/geometry-refinement-maps.md @@ -0,0 +1,43 @@ +--- +type: code +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - geometry + - refinement + - curved-maps +--- + +# Geometry layer: element hierarchy, refinement patterns, nonlinear maps + +Session-2 deep dive (agent trace, load-bearing lines re-verified [✓]). Code-level companion to [[TPZGeoMesh]], [[geometric-mappings]], [[refinement-hanging-nodes]]. + +## 1. Element hierarchy (policy-based template stack) +`TPZGeoEl` (`Mesh/pzgeoel.h:41`, abstract: X/GradX in REAL and Fad flavors :554-563, Divide/genealogy seams, CreateBCGeoEl) → `TPZGeoElRefLess` (`pzgeoelrefless.h:31`: owns `TGeo fGeo` + neighbor ring; forwards X/GradX to the Geom policy; `Divide` DebugStops) → either `TPZGeoElRefPattern` (`tpzgeoelrefpattern.h:34`: `fSubEl` + `TPZAutoPointer`; general `Divide` :356-509) or `TPZGeoElement` (uniform; forwards to `TRef::` static tables). `TPZGeoMesh::CreateGeoElement(..., reftype)` picks uniform vs pattern (`pzgmesh.cpp:1333+`). The `.h.h` files are out-of-line template bodies. `Jacobian` is non-virtual in the base: QR-factors 3×dim `GradX` into square `jac` + orthonormal `axes` (`pzgeoel.h:542-551`) — the mechanism that lets 2D elements live in 3D. + +## 2. Refinement: uniform tables vs runtime patterns +- Uniform `TPZRef*` (e.g. `Refine/pzreftriangle.cpp`): pure static data (son corners, mid-side coords, son→father transforms `buildt`, `fatherside`). `NewMidSideNode` reuses a neighbor's midnode if one exists (:153-179). **Pyramid caveat** [✓ `pzrefpyram.h:27`, `.cpp:336-347`]: `NSubEl=10` = 6 pyramids + 4 tets — uniform refinement of pyramids introduces tetrahedra. +- `TPZRefPattern` (`Refine/TPZRefPattern.h:77`) *is* a small `TPZGeoMesh` (element 0 = father, rest = partition) + precomputed side transforms/permutations. `.rpt` format documented at `.h:37-72` (nodes block, elements block, father first). `TPZGeoElRefPattern::Divide` checks neighbor side-pattern compatibility before lazily adopting the uniform pattern (:369-408), delegates node creation to the pattern, and errors loudly on incompatibility (`CreateMidSideNodes` DebugStops if an existing neighbor midnode is >1e-2 off, `TPZRefPattern.cpp:648-674`). +- Matching tools (`Refine/TPZRefPatternTools.cpp`): `GetCompatibleRefPatterns` (:28), `PerfectMatchRefPattern` (:193,437) driven by `SidesToRefine` (:951-999), and `RefineDirectional` (:1001) — the driver wann and GFEM use for well-heel/crack-tip grading ([[app-wann]], [[app-gfem]]); MixedElasticity uses hand-built patterns as macro-element space constructors ([[app-mixed-elasticity]]). +- **Global state**: `gRefDBase` (`TPZRefPatternDataBase.cpp:31`) maps type→patterns and id→pattern; `.rpt` library loads from `PZ_REFPATTERN_DIR` (configure-baked path — see [[finding-build-config-gaps]] relocatability note). Deserializing a refined mesh **re-resolves pattern ids against the live DB** [✓ `tpzgeoelrefpattern.h.h:20-35`] — a saved mesh is unreadable without the same DB populated (persistence coupling, [[persistence]]). + +## 3. Genealogy → hanging nodes (the geometry/computation bridge) +`TPZInterpolatedElement::Divide` divides geometry first, then per new element `CreateMidSideConnect` (`pzintel.cpp:652`) asks `EqualLevelElementList` (share connect) or `LowerLevelElementList(1)` (:701,741) — the latter delegating to `TPZGeoElSide::LowerLevelCompElementList2` which **walks `Father2()/StrictFather()` ancestry** (`pzgeoelside.cpp:931`). When a coarser neighbor exists, `RestrainSide` builds the L2-projection dependency ([[TPZConnect]]); the only geometric input is `SideTransform3` (`pzgeoelside.cpp:682+`), which accumulates transforms up the refinement tree via `BuildTransform2`. + +## 4. Nonlinear & special maps (two mechanisms + inheritance under refinement) +- **Analytic maps** (`SpecialMaps/`): `TPZArc3D` (circle fit through 3 points, closed-form X/GradX), `TPZCylinderMap` (cylindrical corner coords + rotation), `TPZEllipse3D`, `TPZWavyLine`, tori/spheres. `IsLinearMapping()==false` routes construction to mapped/blend paths. +- **Isoparametric quadratics** (`TPZQuadraticTrig/Quad/…`): quadratic Lagrange shapes over stored midside nodes. +- **`TPZGeoBlend`** (`Geom/tpzgeoblend.{h,cpp}`): Gordon–Hall transfinite blending — linear map + Σ blendFactor·(curved-side map − chord) (`tpzgeoblend.cpp:518+`); discovers curved neighbors in `Initialize` via `SetNeighbourInfo` (`.cpp:71`). Copy ctor DebugStops (`.h:65-72`) — beware mesh-clone paths. +- **Children inherit exact maps** via `TPZGeoElMapped` (`Mesh/tpzgeoelmapped.h:29`): stores child corners **in the eldest ancestor's parametric space** [✓ intent comment `.h:24-27`] and composes `X = Xfather(KsiBar(ksi))` — "if the coarse grid map is consistent, then so will all refined meshes". Routing: `CreateGeoElement` dispatches nonlinear elements to `CreateGeoElementMapped` (`pzgeoelrefless.h.h:427-428`); `CreateBCGeoEl` falls back to blend BC elements on curved sides (:326-338). +- **`TPZChangeEl`** (`SpecialMaps/tpzchangeel.h`): in-place surgery — `ChangeToQuadratic/GeoBlend/Arc3D/Cylinder/QuarterPoint` (quarter-point = fracture singularity resolution; used downstream in [[app-error-estimation]], cylinder+blend in [[app-wann]]). + +## 5. Sides & neighbors +`TPZGeoElSide` (`pzgeoelside.h:86`) = (element, side); neighbors form **singly-linked circular lists** spliced by `SetConnectivity` (`pzgeoelside.cpp:441-488`); `BuildConnectivities` does bulk discovery. Side-to-side transforms: element-local `SideToSideTransform`, cross-element `NeighbourSideTransform`, tree-walking `SideTransform3` — the conformity substrate for restraints and interfaces. Caveat: `TPZGeoElSideIndex::operator bool()` returns true for an *invalid* side (`pzgeoelside.h:55-58`) — inverted-looking semantics. + +## 6. Mesh building (`Pre/`) +`TPZGenGrid2D/3D` (structured, `MMeshType` element choice), `TPZExtendGridDimension` (extrusion), `TPZGmshReader`: physical-name→matid maps per dimension (`TPZGmshReader.h:111-123`), optional tag remap, `InsertElement` constructs uniform or refpattern elements with the physical id as matid (`.cpp:580-649`); undefined-tag elements skipped unless opted in. + +Related: [[TPZGeoMesh]] · [[geometric-mappings]] · [[refinement-hanging-nodes]] · [[TPZConnect]] · [[topology-module]] · [[mesh-io-generators]] diff --git a/ai-analysis/wiki/code/material-system.md b/ai-analysis/wiki/code/material-system.md new file mode 100644 index 000000000..a72b29cd5 --- /dev/null +++ b/ai-analysis/wiki/code/material-system.md @@ -0,0 +1,45 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - material + - weak-form +--- + +# Material system — weak forms & constitutive models + +## Responsibility +A "material" is NeoPZ's unit of physics: it evaluates the weak form (`Contribute`: element matrix + rhs at an integration point), boundary conditions (`ContributeBC`), post-processing variables (`Solution`), and optionally exact-solution errors. Materials are keyed by material-id and attached to [[TPZCompMesh]]. + +## Architecture (verified [repo]) +Layered + variadic-mixin design: +- `Material/TPZMaterial.h` — type-agnostic root ("Actual materials should derive from TPZMatBase"). +- `Material/TPZMaterialT.h` — `TPZMaterialT` type-parametrized layer (STATE vs CSTATE). +- `Material/TPZMatBase.h:21-23` — `template class TPZMatBase : public TPZMaterialT, public virtual Interfaces...`. One mandatory space interface: `TPZMatSingleSpaceT` (one approximation space) or `TPZMatCombinedSpacesT` (multiphysics). Optional capability mixins: error computation (`TPZMatError*`), load cases, integration-point memory (`TPZMatWithMem`, plasticity/history), eigen problems, interface (DG) contributions. +- `Material/TPZBndCond(Base,T).h` — boundary conditions are themselves materials created via `TPZMatBase::CreateBC` (TPZMatBase.h:59-68) referencing the volumetric material. +- `Material/TPZMaterialData(T).h` — per-integration-point data carrier (shape values, gradients, axes, solution) passed into `Contribute` → [[assembly]]. + +## Physics families (dirs under `Material/`) [repo dirs; class lists agent-cited] +`Poisson/` (`TPZMatPoisson`), `DarcyFlow/` (`TPZDarcyFlow` primal, `TPZMixedDarcyFlow` H(div)×L², hybrid + fracture variants), `Elasticity/` (`TPZElasticity2D/3D`, `TPZMixedElasticityND`, `TPZHybridElasticity2D/3D` — the 2D hybrid one is in the 5-file develop delta, `TPZHybridMixedElasticityUP`), `Projection/` (L²/H(div)/H(curl) projections), `Electromagnetics/` (waveguides + PML), `Plasticity/` (~75 headers, `BUILD_PLASTICITY_MATERIALS`-gated), `ConsLaw/` (Euler), `BlackOil/`. +Glue materials: `TPZNullMaterial(CS)` (space placeholder), `TPZLagrangeMultiplier(CS)` (interface coupling in [[hybridization]]). + +## Breadth map (Session 2, agent-traced, key lines verified [✓]) +- **Compiled physics dirs** [✓ `Material/CMakeLists.txt` add_subdirectory list]: Plasticity (`BUILD_PLASTICITY_MATERIALS`-gated, double-only), Elasticity, ConsLaw (Euler), BlackOil, Projection, Poisson, Electromagnetics, DarcyFlow. +- **Galerkin vs mixed is visible in the Contribute signature**: single-space `Contribute(TPZMaterialDataT&, …)` (`TPZDarcyFlow`, NEvalErrors 3) vs combined `Contribute(TPZVec&, …)` (`TPZMixedDarcyFlow`, NEvalErrors 5). **datavec order = mesh-vector order** (resolved; `pzmultiphysicscompel.cpp:836-838` + [[multiphysics-composition]]). H1-hybrid materials sit astride both bases: `TPZHybridDarcyFlow : TPZDarcyFlow + TPZMatCombinedSpacesT + TPZMatErrorCombinedSpaces` [✓ `TPZHybridDarcyFlow.h:25`]; same pattern for `TPZHybridElasticity2D/3D`. +- **Scalar types**: `TVar`-templated with STATE+CSTATE instantiations (Poisson, projections, null/Lagrange materials); STATE-only (Darcy, Elasticity, ConsLaw, BlackOil); **CSTATE-only: all of Electromagnetics** [✓ `TPZWgma.h:20-23`] — waveguide modal analysis via eigen mixins `TPZMatGeneralisedEigenVal`/`TPZMatQuadraticEigenVal`, scattering + PML decorator `TPZMatPML`. The complex path is exercised by materials + `TPZEigenAnalysis`, not by any surveyed downstream app ([[apps-overview]]). +- **Post-processing protocol** (consumed by [[post-processing-vtk]]): `VariableIndex(name)` / `NSolutionVariables(var)` on `TPZMaterial` + typed `Solution(data, var, sol)`; `TPZVTKGenerator::InitFields` resolves names → indices through exactly these seams (`TPZVTKGenerator.cpp:299-321`). Error seam: `TPZMatError` holds `fExactSol` + `NEvalErrors/ErrorNames`; pure-virtual `Errors(...)` on the single/combined error interfaces; driven by `TPZInterpolationSpace::EvaluateErrorT` → `TPZAnalysis::PostProcessError`. +- **BC framework**: `TPZBndCond` (type int + material back-pointer) → `TPZBndCondT` (`fBCVal1` matrix, `fBCVal2` vector, `fForcingFunctionBC`) → variadic `TPZBndCondBase` stamped out by `TPZMatBase::CreateBC` (C++17 fold `SetMaterialImpl` fan-out). BC-type ints are **per-material conventions** (Darcy: 0=Dirichlet/1=Neumann/2=Robin; Elasticity2D adds 3=directional Dirichlet, 4=stress field). +- **TPZMatWithMem** (integration-point memory): `shared_ptr>` + `fUpdateMem`; index flows through `TPZMaterialData::intGlobPtIndex` [✓ `TPZMaterialData.h:141`], assigned by element loops, consumed via `MemItem(i)`. Live users: elastoplasticity (`TPZMatElastoPlastic(2D)`), EM sources (`TPZScatteringSrc`, `TPZPlanarWgScattSrc`). + +## Legacy layer — corrected (Session 2) +`Material/needrefactor/` = 19 top-level entries + `REAL/` with 108 files [repo count] — old-style pre-mixin materials (CFD/Euler+k-ε, multiphase/reservoir, visco/poro-elastic, plates/shells, biharmonic, Poisson variants…). **Correction C3: it is *not* compiled into `pz`** — no `add_subdirectory(needrefactor)` exists and `libpz.dylib` contains none of its symbols [✓ verified by nm]. Residual risk is include-path shadowing only (headers duplicate modern class names); out-of-library targets (`SubStruct`, PerfTests, Publications, one unit test) still include its headers. + +## Related +[[TPZCompMesh]] · [[assembly]] · [[mixed-methods]] · [[hybridization]] · [[approx-space-creators]] · [[error-estimation-convergence]] · [[multiphysics-composition]] · [[apps-overview]] + +## Open questions +- Virtual-inheritance diamond (`public virtual Interfaces...`) cost/complexity — Phase 5. diff --git a/ai-analysis/wiki/code/matrix-and-solvers.md b/ai-analysis/wiki/code/matrix-and-solvers.md new file mode 100644 index 000000000..ba7a8d4f0 --- /dev/null +++ b/ai-analysis/wiki/code/matrix-and-solvers.md @@ -0,0 +1,43 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - linear-algebra + - solvers +--- + +# Matrix/ + Solvers/ — storage & linear solvers + +## Responsibility +`Matrix/` is the storage zoo (all deriving from `TPZMatrix` over `TPZBaseMatrix`); `Solvers/` wraps direct and iterative solution strategies consumed by [[TPZAnalysis]]. + +## Matrix storage [repo paths; hierarchy details to verify Phase 5/6] +- `Matrix/pzmatrix.h` — abstract `TPZMatrix` (**in the 5-file develop delta** — the delta makes `MultiplyByScalar` virtual per commit messages; cross-check `git show develop:Matrix/pzmatrix.h` before citing internals). +- `Matrix/pzfmatrix.h` — `TPZFMatrix` dense column-major workhorse (also the RHS/solution container). +- `Matrix/pzskylmat.h` (`TPZSkylMatrix` symmetric skyline + in-house Cholesky/LDLt), `pzskylnsymmat.h` (nonsym skyline), `pzbndmat.h`/`pzsbndmat.h` (banded), `pzsfulmat.h` (sym full), `pzblock.h` (block indexing), `pzblockdiag.h` (block diagonal). +- Sparse: `TPZYSMPMatrix.h` (Yale/CSR nonsym), `TPZSYSMPMatrix.h` (sym CSR; **delta file**), Pardiso-backed variants (`TPZYSMPPardiso.h`, `TPZSYSMPPardiso.h`), MUMPS variants (`TPZSYSMPMumps.h` etc.), `TPZEigenSparseMatrix.h` (Eigen/Accelerate bridge) [agent]. +- `Matrix/TPZMatrixWindow.h` (windowed views), `TPZTensor.h` (plasticity tensors) [agent]. + +## Solvers [repo paths] +- `Solvers/TPZSolver.h` → `TPZMatrixSolver` (holds the matrix via [[TPZAutoPointer]]). +- `Solvers/pzstepsolver.h` — `TPZStepSolver`: SetDirect(ELU/ECholesky/ELDLt) or iterative CG/GMRES/Jacobi/SSOR with optional preconditioner (another `TPZMatrixSolver`); used everywhere downstream. +- `Solvers/TPZPardisoSolver.h` (MKL), `TPZMumpsSolver.h` (MUMPS) [agent]. +- Eigen stack (Session 2, verified [✓ `Solvers/EigenSolvers/` listing]): `TPZEigenSolver` base (targets, npairs, generalised-vs-standard) → `TPZLinearEigenSolver` (Ax=λx / Ax=λBx), `TPZLapackEigenSolver` (dense/banded LAPACK), `TPZKrylovEigenSolver(+Base)` (Arnoldi projection), `TPZQuadEigenSolver` (quadratic EVP via shift-invert Krylov), `TPZSpectralTransform` (shift / shift-and-invert), `TPZEigenSort`. Analysis drivers: `TPZEigenAnalysis` (A/B matrices ↔ `TPZMatGeneralisedEigenVal`), `TPZQuadEigenAnalysis` (K/L/M ↔ `TPZMatQuadraticEigenVal`) — STATE and CSTATE instantiated; primary consumers are the complex electromagnetics materials ([[material-system]]). Note [[sbfem]] bypasses this stack (direct `dgeev_`/blaze). +- Renumbering lives in `External/` (Sloan, Cuthill-McKee, METIS, Boost) selected via `RenumType` in [[TPZAnalysis]] (TPZAnalysis.h:48-54 [repo]). + +## TPZMatRed (verified [repo Matrix/pzmatred.h:23-79]) +2×2 block substructuring container `[K00 K01; K10 K11]`, side-matrix storage templated (`TPZFMatrix` or `TPZVerySparseMatrix`), holds a `TPZMatrixSolver` for K00, tracks `fK01IsComputed/fIsReduced` state, and is **rigid-body-mode aware** (`fMaxRigidBodyModes`, `fNumberRigidBodyModes`) — floating-subdomain support built into the reduction core (feeds [[static-condensation]] and [[mhm]]). Note: `CopyFrom` lacks the self-assignment guard (`if (from)` only, :66-79) that was added to `TPZSYsmpMatrix` post-pin — same latent-bug family as [[finding-hybridelasticity2d-missing-rhs-at-pin]] notes. + +## Decomposition state machine +`TPZMatrix` carries a decomposition flag (`ENoDecompose/ELU/ECholesky/ELDLt`) so repeated `Solve` reuses factors [pattern known from usage; verify]. In-house factorizations coexist with LAPACK/BLAS replacements when `USING_LAPACK` (README.md:38 [repo]). + +## Related +[[structural-matrices]] · [[TPZAnalysis]] · [[matrix-and-solvers]]-consumers: [[flow-iter-elast]] (`TPZMatRedSolver` app-side Schur), [[static-condensation]] (`TPZMatRed`, in Matrix/ [agent: `pzmatred.h`]) + +## Open questions +- `TPZMatRed` (library) vs divfreebubbles `TPZMatRedSolver`/`TPZSparseMatRed`: which reduction machinery is lib vs app? → Phase 4 (iter_elast slice). Established so far [repo]: `divfree/TPZMatRedSolver.h:15` enum `ProblemOrigin {EDarcyHDiv, EElasticityHDiv, EDarcyH1Hybrid, EElasticityH1Hybrid}` — no `EDefault`/`EMHMSparse` (older drivers still reference them → app-side drift, OQ6). +- Thread-safety of shared matrix objects across solver threads — Phase 5/6. diff --git a/ai-analysis/wiki/code/mesh-io-generators.md b/ai-analysis/wiki/code/mesh-io-generators.md new file mode 100644 index 000000000..776a537c2 --- /dev/null +++ b/ai-analysis/wiki/code/mesh-io-generators.md @@ -0,0 +1,31 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - neopz + - pre-processing + - mesh-io +--- + +# Pre/ — mesh input, generation & analytic solutions + +## Responsibility +Everything that happens *before* the computational mesh exists: import meshes, generate structured grids, provide analytic benchmark solutions; plus the [[approx-space-creators]] (own page) and [[mhm]] controllers. + +## Key files [repo paths] +- `Pre/TPZGmshReader.h` — **in-tree parser** of Gmsh `.msh` (v3/v4?) files with physical-group → material-id mapping; gmsh is *not* a linked dependency. Used by divfreebubbles (`main_1element.cpp`, `main_2fractures.cpp`). +- `Pre/TPZGenGrid2D.h`, `TPZGenGrid3D.h`, `TPZAcademicGeoMesh.h`, `Mesh/TPZGeoMeshTools.h` (`CreateGeoMeshOnGrid`, `CreateGeoMeshSingleEl` — used by iter_elast [repo]) — structured generators. +- `Pre/TPZReadGIDGrid.h`, `TPZGMSHReadMesh.h` — older importers [agent]. +- `Pre/TPZAnalyticSolution.h` — family of manufactured solutions: `TElasticity2DAnalytic` (used by iter_elast [repo:66]), `TElasticity3DAnalytic`, `TLaplaceExample1`, `TStokesAnalytic`… each provides exact solution + forcing consistent with a chosen problem type → backbone of convergence validation ([[error-estimation-convergence]]). +- `Pre/pzbuildmultiphysicsmesh.h` — utilities to combine/transfer atomic meshes ↔ multiphysics mesh (`TPZBuildMultiphysicsMesh::TransferFromMultiPhysics` etc.). +- Hybridization utilities + MHM controllers → [[approx-space-creators]], [[mhm]]. + +## Related +[[TPZGeoMesh]] · [[approx-space-creators]] · [[error-estimation-convergence]] · [[flow-dfreebubbles-1el]] · [[flow-mhm-hdivconstant]] + +## Open questions +- Which `.msh` format versions the reader supports (v2? v4?) and how robust it is — relevant to app-repo mesh assets (Phase 4). +- `TPZAnalyticSolution` uses FAD (auto-diff) to derive gradients/forcings? (README mentions forward AD [repo]; confirm mechanism.) diff --git a/ai-analysis/wiki/code/multiphysics-composition.md b/ai-analysis/wiki/code/multiphysics-composition.md new file mode 100644 index 000000000..156943bb7 --- /dev/null +++ b/ai-analysis/wiki/code/multiphysics-composition.md @@ -0,0 +1,36 @@ +--- +type: code +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - mesh + - multiphysics +--- + +# TPZMultiphysicsCompMesh — combining approximation spaces + +Session-2 deep dive (agent trace, load-bearing lines re-verified [✓]). The machinery that lets NeoPZ compose independent "atomic" meshes (flux, pressure, rotation, multipliers, …) into one coupled discretization — used by every mixed/hybrid path and, downstream, for 3–7-field couplings ([[app-mixed-elasticity]]) and same-physics background+enrichment composition ([[app-gfem]]). + +## Mesh level (`Mesh/TPZMultiphysicsCompMesh.{h,cpp}`) +- State: `m_active_approx_spaces` (0/1 flags) + `m_mesh_vector`, equal length enforced (`.h:22-25`, `.cpp:83-95`). Inactive spaces contribute data but no equations. +- `BuildMultiphysicsSpace` (`.cpp:75-101`): reset references → multiphysics create-functions → `AutoBuild` skeleton → `AddElements` → `AddConnects` → `LoadSolutionFromMeshes` → `ComputeNodElCon` → `CleanUpUnconnectedNodes`. +- `AddElements` (`.cpp:229-321`): per active space, attach the referred atomic element to each multiphysics element; if no same-level match it **walks the geometric ancestry** (:264-280) to accept a coarser atomic element — the hook MHM-style spaces rely on. +- `AddConnects` (`.cpp:323-421`): concatenates atomic connect vectors with per-space offsets `FirstConnect[i]`, and **re-offsets dependency master indices** [✓ :366-377] so hanging-node restraints survive the merge — an easy-to-break invariant for any new build path. + +## Element level (`Mesh/pzmultiphysicscompel.cpp`) +- `CalcStiffT` (:811-907) builds one `TPZMaterialDataT` per space (vector sized to `fElementVec`, :836-838); `InitMaterialDataT` (:667-723) marks `fActiveApproxSpace` and calls the material's `FillDataRequirements(dataVec)`; `ComputeRequiredData` (:498-533) evaluates all spaces at the shared integration point, reusing space 0's Jacobian (:514-517); the combined material's `Contribute(datavec, weight, ek, ef)` closes the loop — answering the old open question in [[material-system]]: **datavec order = mesh-vector order**. +- `InitializeElementMatrix` (:544-607) stacks per-space connect blocks; total nstate = sum over spaces. +- Interfaces: `TPZMultiphysicsElement::CreateInterfaces/CreateInterface/RemoveInterfaces` (`pzmultiphysicselement.h:130-138`) create `TPZMultiphysicsInterfaceElement` glue; `TPZBuildMultiphysicsMesh::AddWrap` builds hybridization wrapper stacks. + +## Solution transfer (two symmetric paths) +- Instance: `LoadSolutionFromMeshes` / `LoadSolutionFromMultiPhysics` (`.cpp:436-541`) — block copies via `FirstConnectIndex` offsets; the latter finishes with `LoadSolution` on each atomic mesh and skips `NElConnected()==0` connects. +- Static: `TPZBuildMultiphysicsMesh::TransferFromMeshes / TransferFromMultiPhysics` (`Pre/pzbuildmultiphysicsmesh.cpp:305-403/405+`) — map each multiphysics connect to its `(atomic mesh, connect)` pair; `TransferFromMeshes` **recurses into `TPZSubCompMesh` children** (:394-402), i.e. it understands substructured multiphysics meshes. + +## Notes +- The multiphysics mesh is itself subclassable downstream (`TPZMultiPhysicsMeshWindow` in [[app-error-estimation]]). +- Composition is not limited to different physics: same-space composition (background + enrichment H1) works because activity flags and connect offsets are per-mesh, not per-space-type ([[app-gfem]]). + +Related: [[TPZCompMesh]] · [[TPZConnect]] · [[mixed-methods]] · [[material-system]] · [[condensation-groups-submeshes]] · [[approx-space-creators]] diff --git a/ai-analysis/wiki/code/persistence.md b/ai-analysis/wiki/code/persistence.md new file mode 100644 index 000000000..c441c3ee1 --- /dev/null +++ b/ai-analysis/wiki/code/persistence.md @@ -0,0 +1,27 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - neopz + - persistence +--- + +# Save/ — persistence (object serialization) + +## Responsibility +Binary save/restore of NeoPZ object graphs (meshes, matrices, analyses): every serializable class derives from `TPZSavable`, has a registered `ClassId`, and implements `Read/Write` against a `TPZStream`. `TPZPersistenceManager` orchestrates whole-graph writes with pointer fixup; `TPZChunkTranslator`/`TPZChunkInTranslation` provide *versioned* backward-compatible reads [agent; core files verified to exist: `Save/TPZSavable.h`, `TPZStream.h`, `TPZPersistenceManager.h`]. + +## Notables +- MD5-checksum stream (`Save/pzmd5stream.h`, `USING_OPENSSL`) — also used by cmake regression file comparison [agent]. +- Coverage is thin: single unit test (`TestPersistence`, one `TPZFMatrix` round-trip) despite the elaborate translator machinery; **no gmesh/cmesh round-trip test** [agent] → Phase 7 gap. +- `ClassId` (`Hash/TPZHash` [repo include in TPZMatBase.h:13]) hashes class names for stable ids. + +## Related +[[TPZCompMesh]] · [[TPZGeoMesh]] · [[material-system]] · [[refinement-hanging-nodes]] (refpatterns are also persisted `.rpt` data) + +## Open questions +- Is mesh save/restore actually used in current workflows (LabMEC restarts?) or mostly legacy? +- Do all *new* classes (approx creators, VTK generator) implement persistence, or is coverage decaying? → Phase 5/7. diff --git a/ai-analysis/wiki/code/post-processing-vtk.md b/ai-analysis/wiki/code/post-processing-vtk.md new file mode 100644 index 000000000..3bfa535e7 --- /dev/null +++ b/ai-analysis/wiki/code/post-processing-vtk.md @@ -0,0 +1,31 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - neopz + - post-processing + - vtk +--- + +# Post/ — post-processing & VTK output + +## Responsibility +Turn FE solutions into visualization files. Two generations coexist: +1. **Legacy graph-mesh family** [agent]: `Post/pzgraphmesh.h` + per-format writers `pzvtkmesh.h` (VTK), `pzdxmesh.h` (OpenDX), `pzmvmesh.h` (MVGraphs), `pzv3dmesh.h`; graph elements subdivide each computational element for plotting; driven by `TPZAnalysis::DefineGraphMesh/PostProcess` with variable-name tables. +2. **Modern `TPZVTKGenerator`** (Post/TPZVTKGenerator.h [repo]): authored 2022, explicitly "Adapted from NGSolve's vtkoutput.hpp" (attribution in header, lines 1-6); writes legacy-format `.vtk` with cell types mapped in `TPZVTK::CellType` (point/line/tri/quad/tet/pyr/prism/hex, lines 30-56); resolution via uniform master-element subdivision (`vtkRes`). + +Also: `Post/TPZVTKGeoMesh.h` — dump geometric meshes (+partition/materials) to VTK for debugging; `Post/pzpostprocanalysis.h` — L² projection of solutions onto a post-processing mesh (used for plasticity/state vars) [agent]; `Post/pzgradientreconstruction.h`. + +## What the output means +Field names are resolved through the material's `VariableIndex/NSolutionVariables/Solution` interface ([[material-system]]) — i.e. output correctness depends on each material's `Solution()` implementation, per variable. → validation angle for Phase 7. + +## Related +[[TPZAnalysis]] · [[material-system]] · [[vtk-output]] · [[flow-dfreebubbles-1el]] + +## Open questions +- Legacy `.vtk` (ASCII legacy format) only, or also XML `.vtu`? (TPZVTKGenerator appears legacy-format; confirm + note ParaView implications in Phase 4.) +- How high-order fields are represented (subdivision only? no VTK Lagrange cells?) — matters for judging visualization fidelity of p>1 solutions. +- Pyramid handling in TPZVTKGenerator vs its `MAX_SUBEL{10}` comment (pyramid refinement) — check. diff --git a/ai-analysis/wiki/code/shape-functions.md b/ai-analysis/wiki/code/shape-functions.md new file mode 100644 index 000000000..fdf66b0a9 --- /dev/null +++ b/ai-analysis/wiki/code/shape-functions.md @@ -0,0 +1,35 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - neopz + - shape-functions +--- + +# Shape/ — shape-function engine + +## Responsibility +Computes hierarchical shape functions and their derivatives on master elements, for all supported topologies and space families (H1, H(div), H(curl), L²). Doxygen module note: implemented as **static classes with no virtual calls, for efficiency** [agent, consistent with headers]. + +## Key files [repo paths] +- H1 per topology: `Shape/pzshapelinear.h`, `pzshapequad.h`, `pzshapetriang.h`, `pzshapecube.h`, `pzshapetetra.h`, `pzshapeprism.h`, `pzshapepiram.h`, `pzshapepoint.h` (namespace `pzshape`). +- Newer unified drivers: `Shape/TPZShapeH1.h`, `TPZShapeHDiv.h`, `TPZShapeHDivConstant.h`, `TPZShapeHDivKernel2D.h`, `TPZShapeHCurl.h`, `TPZShapeHCurlNoGrads.h`, `TPZShapeDisc` (?), with `Shape/TPZShapeData.h` as the state carrier (orders, connect ids, precomputed side transforms). +- `Shape/pzgenericshape.h` — generic composition machinery. +- `Shape/TPZEnumApproxFamily.h` — family enums used by [[approx-space-creators]]. + +## Design notes (verified in Phase 4 for H(div)) +- Hierarchical (not Lagrangian-nodal) bases: connect-ordered blocks (vertex/edge/face/internal functions), enabling variable p per connect → hp machinery ([[refinement-hanging-nodes]], [[hp-adaptivity]]). +- Side shape functions restricted to sides support conformity checks (`sideshape_continuity` test [agent]). +- **Verified**: H(div) vector shapes = scalar H1 shape × constant master direction (`TPZShapeHDiv.cpp:345-355`), directions built by Topology (`ComputeHDivDirections`, cached in `TPZShapeData.fHDiv.fMasterDirections`); Shape layer outputs master-element values only — the Piola map lives in the element layer ([[piola-transformations]]). Exactly the published construction ([[devloo-group-shape-construction]]). +- **Verified**: `TPZShapeHDivConstant` derives from `TPZShapeHCurlNoGrads` — per facet one RT0 divergence carrier + divergence-free curls/rotated gradients (`TPZShapeHDivConstant.cpp:129-215`); known FAD-branch inconsistency → [[finding-hdivconstant-fad-index]]. +- Orientation: `fSideOrient` signs folded into master directions + facet permutation gather (`HDivPermutation`) — see [[TPZCompElHDiv]]. + +## Related +[[topology-module]] · [[TPZCompElHDiv]] · [[geometric-mappings]] · [[quadrature]] · [[h1-space]] · [[hdiv-space]] · [[hcurl-space]] + +## Open questions +- Where derivatives are mapped to physical space (axes/jacobian application) — shape layer or element layer? (`TPZMaterialData.axes` suggests element layer.) +- Legacy per-topology `Chebyshev`-based orthogonal polynomials vs newer `TPZShapeH1` path: which is live for which element class? diff --git a/ai-analysis/wiki/code/structural-matrices.md b/ai-analysis/wiki/code/structural-matrices.md new file mode 100644 index 000000000..1885ba588 --- /dev/null +++ b/ai-analysis/wiki/code/structural-matrices.md @@ -0,0 +1,39 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - assembly + - parallel +--- + +# StrMatrix/ — structural matrices (assembly strategies) + +## Responsibility +A `TPZStructMatrix` binds three choices: (1) which global matrix *storage* to create, (2) how to *assemble* it from element matrices (serial / threaded variants), (3) which equations enter (equation filter). [[TPZAnalysis]] delegates `Assemble()` to it → [[assembly]]. + +## Key files +- `StrMatrix/TPZStructMatrix.h` [repo]: type-agnostic base ("Describes the type-agnostic interface… `TPZStructMatrixT` is the one structural matrices should inherit from", lines 17-25); virtuals `Clone()` + `Create()`; ctors take `TPZCompMesh*` raw or `TPZAutoPointer` (lines 55-68); move ops deleted; destructor non-default due to incomplete-type deletion concerns (`@orlandini` comment, lines 30-46 — candid in-code engineering note). +- `StrMatrix/TPZStructMatrixT.h` — typed layer (`/`). +- `StrMatrix/TPZStrMatParInterface.h` — parallel-interface base (virtual base of `TPZStructMatrix` [repo:25]). +- Parallel assembly schemes [agent]: `pzstrmatrixor.h` (`TPZStructMatrixOR` — "owner rule"? classic thread-per-color?), `pzstrmatrixot.h` (`TPZStructMatrixOT`), `TPZStructMatrixOMPorTBB.h`, `pzstrmatrixflowtbb.h` (TBB flow-graph). Multiple coexisting strategies — inventory + benchmark relevance in Phases 5/6. +- Storage-specific concrete classes [agent]: `pzskylstrmatrix.h` (skyline), `TPZSpStructMatrix.h` / `TPZSSpStructMatrix.h` (sparse nonsym/sym; MKL Pardiso-backed variants; MUMPS variant `TPZSSpStructMatrixMumps` used by divfreebubbles `iter_elast.cpp:297`), `pzfstrmatrix.h` (full), `pzbstrmatrix.h` (band), `TPZFrontStructMatrix` (frontal), `pzbdstrmatrix.h` (block-diagonal, used for preconditioners). +- `StrMatrix/TPZEquationFilter.h` — restrict assembly/solution to an equation subset (used with iterative solvers and by `TPZMatRedSolver`-style reductions [agent]). + +## Validation signal +`UnitTest_PZ/TestStruct` + `TestMultithreading` assert parallel == serial matrices and known-matrix assembly [agent] → Phase 7. + +## Related +[[assembly]] · [[TPZAnalysis]] · [[matrix-and-solvers]] · [[TPZCompMesh]] · [[static-condensation]] + +## OR vs OT — RESOLVED (Phase 5 sweep [agent, structure spot-verified]) +- **OR** (`pzstrmatrixor.cpp`): producer/consumer. Workers pull elements one-by-one under a mutex (`NextElement`, :829-844), compute `CalcStiff` into fresh per-iteration `ek/ef`, hand results to a **single consumer thread** that alone writes the global matrix (:714) — no matrix locking needed, but the consumer serializes scatter. +- **OT** (`pzstrmatrixot.cpp`): **graph coloring**. Precomputed `fElSequenceColor`/`fElBlocked`; threads take work via `fCurrentIndex->fetch_add(1)` (:695), keep stack-local ek/ef, wait on a condition variable until their blocking predecessor completed (:821), then scatter **concurrently without atomics** — safe because coloring guarantees no DOF overlap (:848-872). +- Materials are shared mutable across threads in both → [[finding-thread-shared-materials]]. Parallel==serial equality unit-tested. + +## Open questions +- How equation filters interact with condensed meshes and connect sequence numbers. +- OMPorTBB/flow-TBB variants: maintained or experimental? (PerfTests stale; no benchmark evidence.) diff --git a/ai-analysis/wiki/code/topology-module.md b/ai-analysis/wiki/code/topology-module.md new file mode 100644 index 000000000..0fec3b62c --- /dev/null +++ b/ai-analysis/wiki/code/topology-module.md @@ -0,0 +1,32 @@ +--- +type: code +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - neopz + - topology +--- + +# Topology/ — master-element combinatorics + +## Responsibility +Defines the *combinatorial* structure of each reference element ("sides" = vertices, edges, faces, volume), side dimensions, side-to-side closure relations, parametric transforms between sides, and node/face permutation machinery. This layer underlies geometry ([[geometric-mappings]]), shape functions ([[shape-functions]]) and conformity of vector spaces ([[TPZCompElHDiv]]). + +## Key files [repo paths] +`Topology/tpzpoint.h`, `tpzline.h`, `tpztriangle.h`, `tpzquadrilateral.h`, `tpztetrahedron.h`, `tpzcube.h`, `tpzprism.h`, `tpzpyramid.h` (namespace `pztopology`), plus `TPZTopologyUtils.h`. + +## The "side" abstraction (NeoPZ-specific, load-bearing) +Every topological entity of an element is a numbered *side* (e.g. quadrilateral: 4 vertex sides + 4 edge sides + 1 face side = 9). Sides index: connects in [[TPZCompMesh]], neighbor lists in [[TPZGeoMesh]], side transforms (`TPZTransform`), side integration rules ([[quadrature]]), and restraint construction. Unit test `TestTopology` validates face-orientation data structures, transform projections, and constant div/curl reproduction per topology [agent]. + +## Notable +- Permutation tables for sides support orientation-independent conformity — validated by `drham_permute_check` style tests [agent]. +- The pyramid is present as a topology; its H(div)/shape support has historically been special (mixed families sometimes exclude it) — check which families support pyramids (Phase 4). + +## Related +[[shape-functions]] · [[geometric-mappings]] · [[TPZGeoMesh]] · [[quadrature]] · [[hdiv-space]] + +## Open questions +- Exact encoding of face orientations (local-to-global side permutation id) and where vector-shape sign flips are applied. +- `TPZTransform` side-to-side composition rules — read `TPZTopologyUtils` in Phase 4. diff --git a/ai-analysis/wiki/concepts/assembly.md b/ai-analysis/wiki/concepts/assembly.md new file mode 100644 index 000000000..833316282 --- /dev/null +++ b/ai-analysis/wiki/concepts/assembly.md @@ -0,0 +1,22 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz +--- + +# Assembly (element → global system) + +**Idea.** Loop elements; compute element stiffness `ek` and load `ef` by quadrature over material `Contribute`; scatter into the global matrix/rhs via connect → equation numbering; apply constraints (hanging nodes, condensation) on the way. + +**In NeoPZ.** Pipeline (to be traced precisely in Phase 2/4): +`TPZAnalysis::Assemble` → [[structural-matrices|TPZStructMatrix]]`::Assemble` → per-element `TPZCompEl::CalcStiff(ek,ef)` → `TPZInterpolatedElement` gathers [[shape-functions]] + [[geometric-mappings]] into `TPZMaterialData` → [[material-system|material]]`::Contribute` at each [[quadrature]] point → `ek/ef` constrained (connect dependencies, condensation wrappers) → scatter through `TPZConnect` sequence numbers + `TPZBlock` offsets into the chosen matrix storage ([[matrix-and-solvers]]). +Parallel variants (OR/OT/TBB-flow) partition the element loop; equality with serial assembly is unit-tested (`TestMultithreading` [agent]). + +**Invariants to check.** Constraint application order (dependencies before scatter); symmetric-storage assembly writes only one triangle (sym sparse `TPZSYSMPMatrix` — delta file caution); block offsets vs connect sequence renumbering ([[TPZAnalysis]] RenumType); thread-safety of shared `TPZMaterialData`/materials (materials are shared across threads — `Contribute` must be const/reentrant? → Phase 5). + +Related: [[structural-matrices]] · [[material-system]] · [[static-condensation]] · [[quadrature]] · [[TPZCompMesh]] diff --git a/ai-analysis/wiki/concepts/de-rham-complex.md b/ai-analysis/wiki/concepts/de-rham-complex.md new file mode 100644 index 000000000..2d75aa780 --- /dev/null +++ b/ai-analysis/wiki/concepts/de-rham-complex.md @@ -0,0 +1,22 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz +--- + +# De Rham complex (discrete exact sequence) + +**Idea.** The sequence H1 →grad→ H(curl) →curl→ H(div) →div→ L² with image(left op) = kernel(right op) (on contractible domains). Discrete spaces that reproduce this exactness inherit stability/consistency for mixed problems (FEEC viewpoint). + +**In NeoPZ (strong repo signal).** Dedicated test suite `UnitTest_PZ/TestDeRham/` compares "the dimension of the span of the differential operator of the left space against the kernel of the right space… rank(M_left) = ker(M_right)" via SVD, across pairs H1×HCurl, HCurl×HDiv, HDiv×L2 (needs LAPACK) [agent, header comment quoted]. Mesh-level checks: `TestMesh/TestHDiv.cpp` `CheckDRham(cel)` incl. under face permutations [agent]. Kernel-H(div) elements = explicit use of the complex (div-free fields as curls) → [[hdiv-space]], [[divfree-support-lib]]. + +**Why it matters for the review.** Exactness at the *basis* level is the library's own chosen correctness criterion for its space constructions — the assessment should trace exactly what property each test proves (rank equality ≠ full commuting-diagram property; clarify in Phase 3/4, mark what remains unproven, e.g. interpolation/commutativity, mesh-family uniformity). + +**Reference anchors.** Arnold–Falk–Winther (FEEC); Demkowicz (exact sequences, projection-based interpolation); Devloo-group papers on compatible spaces. + +Related: [[hdiv-space]] · [[hcurl-space]] · [[h1-space]] · [[mixed-methods]] · [[flow-unit-test-hdiv-creator]] diff --git a/ai-analysis/wiki/concepts/discontinuous-l2-dg.md b/ai-analysis/wiki/concepts/discontinuous-l2-dg.md new file mode 100644 index 000000000..491179a16 --- /dev/null +++ b/ai-analysis/wiki/concepts/discontinuous-l2-dg.md @@ -0,0 +1,28 @@ +--- +type: concept +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - discontinuous + - dg +--- + +# Discontinuous (L²) spaces & interface/DG machinery + +**Idea.** Piecewise-polynomial spaces with no inter-element continuity: the natural home of mixed-method pressures, multipliers/constants, and discontinuous-Galerkin primal fields. Coupling, where needed, is imposed weakly — via saddle-point structure or interface (jump/penalty) terms. + +**In NeoPZ — two distinct realizations** (Session 2, [[element-families]]): +1. **`TPZCompElDisc`** — a true discontinuous element: single connect for the whole element, modal/orthogonal basis about the element center, optional external (enrichment) shape functions, no restraint machinery. Used for order-0 pressure/constant spaces (always for `EHDivConstant`), rotation multipliers, distributed-flux/average spaces — the rigid-body enrichment meshes of [[static-condensation]] are built from it. +2. **Broken-H1** — the standard trick for p>0 L² fields: continuous factory + `CreateDisconnectedElements(true)`, disconnection achieved by resetting geometric references during build so connects are never shared. Local basis = H1 hierarchical basis; global space = L². This is what `TPZHDivApproxCreator::CreateL2Space` produces for p>0 pairs. + +**Interface/DG layer.** `TPZInterfaceElement` (single-space) and `TPZMultiphysicsInterfaceElement` (combined-spaces) assemble jump terms through the `TPZMatInterfaceSingleSpace`/`TPZMatInterfaceCombinedSpaces` material interfaces. DG is compositional: discontinuous space + `CreateInterfaceElements` + interface-capable material — there is no monolithic "DG creator". The same interface machinery is what [[hybridization]] uses for Lagrange-multiplier transmission (`TPZLagrangeMultiplier(CS)`), so DG and hybrid methods share one code path. + +**Downstream evidence.** Every surveyed mixed app builds discontinuous pressure/multiplier meshes ([[apps-overview]] §1); `TPZCompElDisc` is subclassed downstream for conditioning (`TPZCompElDiscScaled`, [[app-mixed-elasticity]]); interface elements couple 3D/2D/1D physics in [[app-wann]] and tangential tractions in [[app-iterative-saddle-point]]. + +**What is *not* in-tree.** No upwinding/numerical-flux library for hyperbolic DG in the modern layer (the old `ConsLaw`/`needrefactor` CFD materials carry their own); `TPZAgglomerateElement` (agglomerated DG coarsening) exists but was not on any analyzed path. + +Related: [[element-families]] · [[mixed-methods]] · [[hybridization]] · [[hdiv-space]] · [[static-condensation]] diff --git a/ai-analysis/wiki/concepts/error-estimation-convergence.md b/ai-analysis/wiki/concepts/error-estimation-convergence.md new file mode 100644 index 000000000..e33ff6473 --- /dev/null +++ b/ai-analysis/wiki/concepts/error-estimation-convergence.md @@ -0,0 +1,24 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - validation +--- + +# Error computation & convergence validation + +**Idea.** Manufactured/analytic solutions → compute norms of (u_h − u) per element and globally; convergence rate vs h (or p) validates implementation order. A posteriori estimators drive adaptivity. + +**In NeoPZ.** `TPZAnalysis::SetExact(...)` + `PostProcessError(errors,...)` computes per-material norms via `TPZMatError*::Errors` interfaces ([[material-system]]); `Pre/TPZAnalyticSolution.h` supplies exact solutions+forcings (`TElasticity2DAnalytic` etc. [repo, used in iter_elast]). Error vector convention: typically [0]=energy?, [1]=L2?, per material — **norm indices are material-specific; document per slice** (iter_elast prints error[0..4] [repo, commented block]). Convergence *rate* tests in-library: `TestSBFem` explicitly; most suites test exact-representation (polynomial reproduction) instead of rates [agent] → Phase 7 theme: reproduction-tests vs rate-tests. +A posteriori: gradient reconstruction (Post/), dedicated ErrorEstimation work **confirmed downstream (Session 2)**: the ErrorEstimation app implements four estimator families (HDiv potential reconstruction, hybrid-H1 H1/HDiv reconstructions, MHM, partition-of-unity patch solves) and closed h/hp-adaptive loops, entirely from library primitives — see [[app-error-estimation]]. wann adds a two-discretization (H1-vs-mixed) comparison estimator ([[app-wann]]). + +**Invariants to check.** Error integration order sufficiency; `ElementSolution` redim before PostProcessError (iter_elast commented code shows the required incantation [repo:391-401]); parallel post-process equality (tested [agent]). + +**Reference anchors.** Ainsworth–Oden (a posteriori); standard a priori theory (Ern–Guermond) for expected rates per space/order. + +Related: [[TPZAnalysis]] · [[material-system]] · [[mixed-methods]] · [[flow-dfreebubbles-1el]] diff --git a/ai-analysis/wiki/concepts/geometric-mappings.md b/ai-analysis/wiki/concepts/geometric-mappings.md new file mode 100644 index 000000000..52d4b8cce --- /dev/null +++ b/ai-analysis/wiki/concepts/geometric-mappings.md @@ -0,0 +1,24 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - geometry +--- + +# Geometric mappings (master → physical) + +**Idea.** Each element is the image of a reference (master) element under a map X(ξ); FE integrals are pulled back via the Jacobian. Linear/multilinear maps for straight elements; higher-order or exact maps for curved geometry. + +**In NeoPZ.** Per-topology map classes in `Geom/` (`pzgeom::TPZGeoQuad` etc.) plugged into element templates (`TPZGeoElRefLess`); *blend* maps `tpzgeoblend.h` (transfinite blending of curved boundary reps into element interiors); `SpecialMaps/` exact maps (arc, ellipse, sphere, torus, cylinder, NACA airfoil, quadratic elements). README headline: "non-linear geometrical mappings (curved elements with exact representation)" [repo:README.md:18]. `TPZGeoEl::Jacobian/GradX` deliver the metric; `TestGeometry` (`gradx_tests`) and `TestBlend` (semicircle comparisons) validate [agent]. + +**Traced (Session 2, [[geometry-refinement-maps]]).** `Jacobian` QR-factors GradX into square `jac` + orthonormal `axes` in the *base class* (non-virtual) — the 2D-in-3D mechanism. Blend maps discover curved neighbors at `Initialize` and add Gordon–Hall deviations weighted by per-topology blend factors; BC elements on curved sides automatically become blend elements. **Children inherit exact maps**: `TPZGeoElMapped` stores child corners in the eldest ancestor's parametric space and composes through it ("if the coarse grid map is consistent, then so will all refined meshes"). `TPZChangeEl` retrofits curvature onto imported meshes (`ChangeToCylinder/Arc3D/GeoBlend/QuarterPoint`) — the workflow wann uses on gmsh wells ([[app-wann]]) and ErrorEstimation on NACA profiles ([[app-error-estimation]], custom `TPZBlendNACA` subclass). +**Still open.** Integration-order adequacy for curved maps ([[quadrature]]); curved × vector-space validation ([[piola-transformations]], Phase-7 gap). + +**Reference anchors.** Gordon–Hall blending; Devloo-group curved H(div) paper (hdivCurvedJCompAppMath); Ern–Guermond ch. on geometry. + +Related: [[TPZGeoMesh]] · [[topology-module]] · [[piola-transformations]] · [[quadrature]] diff --git a/ai-analysis/wiki/concepts/h1-space.md b/ai-analysis/wiki/concepts/h1-space.md new file mode 100644 index 000000000..ef4505dfa --- /dev/null +++ b/ai-analysis/wiki/concepts/h1-space.md @@ -0,0 +1,26 @@ +--- +type: concept +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz +--- + +# H1-conforming spaces + +**Idea.** Piecewise-polynomial spaces continuous across element boundaries; the natural home of primal formulations (Poisson, elasticity displacement). Conformity requirement: function traces match on shared faces/edges/vertices. + +**In NeoPZ (Session-2 trace, [[element-families]]).** `TPZCompElH1 : TPZIntelGen : TPZInterpolatedElement`; continuity by *shared connects*: one connect per topological side including corners; corner connects clamped to order 1, side/internal orders per connect (hierarchical `TPZShapeH1` basis) → native p-adaptivity. `EffectiveSideOrder` = max over contained sub-sides (face ≥ edge order rule). Hanging nodes fully supported through the generic scalar `RestrainSide` L2 projection ([[TPZConnect]]). +**H1Family resolved**: `{EH1Standard, EH1WidePrism}` — the family only matters for prisms and only at element creation (template argument `TPZShapeWidePrism` vs `TPZShapePrism`, `pzcreateapproxspace.cpp:111-121`); the stored `fh1fam` is never branched on at runtime. +Creators: `SetAllCreateFunctionsContinuous` (+`WithMem`), problem-level `TPZH1ApproxCreator` (hybrid variants, [[hybridization]]). Broken-H1 (disconnected build) doubles as the p>0 L² realization ([[discontinuous-l2-dg]]). + +**Downstream evidence.** H1 is a primary research surface, not a baseline: GFEM builds enriched fracture spaces by subclassing `TPZCompElH1` ([[app-gfem]]); ErrorEstimation reconstructs conforming potentials in H1 ([[app-error-estimation]]); wann uses H1 companion meshes as error references ([[app-wann]]). + +**Validated in-tree.** `TestH1ApproxSpaceCreator` (constant/linear exact representation), De Rham pairs H1→HCurl ([[de-rham-complex]]), hanging-node suites. Gap (Phase 7): no convergence-*rate* tests. + +**Reference anchors.** Devloo–Bravo–Rylo 2009 (systematic shape construction); Szabó–Babuška (p-version); Ern–Guermond. + +Related: [[element-families]] · [[shape-functions]] · [[hybridization]] · [[de-rham-complex]] · [[TPZConnect]] diff --git a/ai-analysis/wiki/concepts/hcurl-space.md b/ai-analysis/wiki/concepts/hcurl-space.md new file mode 100644 index 000000000..e7831702a --- /dev/null +++ b/ai-analysis/wiki/concepts/hcurl-space.md @@ -0,0 +1,26 @@ +--- +type: concept +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - hcurl +--- + +# H(curl)-conforming spaces + +**Idea.** Vector fields with curl in L²; conformity = continuity of *tangential* components across faces/edges. Standard for electromagnetics (edge/Nédélec elements). + +**In NeoPZ (Session-2 trace, [[element-families]]).** `TPZCompElHCurl : TPZIntelGen` with **no vertex connects** (one connect per non-vertex side); shapes `TPZShapeHCurl` / `TPZShapeHCurlNoGrads`. `HCurlFamily {EHCurlStandard, EHCurlNoGrads}` is a **live runtime switch** (unlike H1Family): `NConnectShapeF`/`InitMaterialData`/`ComputeShape` branch per family; NoGrads filters gradient fields from the standard basis (kernel-oriented; reused by `TPZShapeHDivConstant`, [[hdiv-space]]). +**Covariant Piola confirmed structurally**: `TransformShape` applies `phi = axesᵀ·J⁻ᵀ·phî` (comment "applies covariant piola transform", `TPZCompElHCurl.cpp:564-578`); curl mapped separately (3D `J·curl̂/detJ`, 2D `curl̂/detJ`) — the counterpart of the contravariant trace in [[piola-transformations]]. +**Orientation protocol differs from HDiv**: implicit, via corner-node-id transform ids parameterizing `ComputeHCurlDirections` — no explicit sign array (HDiv uses `fSideOrient`). Hanging nodes: dedicated vector-valued `RestrainSideT` (L2 trace projection; DebugStops when small-side order < large-side order). +**Boundaries of support**: pyramid and point elements unavailable (`HCURL_EL_NOT_AVAILABLE` → DebugStop); effective HCurl order can exceed the nominal order on quad-type sides (`MaxOrder` override). Materials: `Material/Electromagnetics/` — all **CSTATE** (complex): `TPZWgma`/`TPZAnisoWgma`/`TPZPeriodicWgma` (waveguide modal analysis via the generalised/quadratic eigen mixins), `TPZScattering(+Src)`, PML decorators `TPZMatPML` ([[material-system]]). + +**Usage note (Session 2).** None of the five surveyed downstream apps uses H(curl) ([[apps-overview]] §1) — in-tree users are the electromagnetics materials + `TestHCurl`/`TestDeRham`; downstream H(curl) work lives in older lines (WGMAResearch). Coverage claims about H(curl) should lean on the unit suites, not application evidence. + +**Reference anchors.** De Siqueira–Devloo–Gomes (construction); Nédélec families via Boffi–Brezzi–Fortin / Monk. + +Related: [[element-families]] · [[hdiv-space]] · [[de-rham-complex]] · [[shape-functions]] · [[topology-module]] · [[piola-transformations]] diff --git a/ai-analysis/wiki/concepts/hdiv-space.md b/ai-analysis/wiki/concepts/hdiv-space.md new file mode 100644 index 000000000..2805403f6 --- /dev/null +++ b/ai-analysis/wiki/concepts/hdiv-space.md @@ -0,0 +1,27 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - hdiv +--- + +# H(div)-conforming spaces + +**Idea.** Vector fields whose divergence is in L²; conformity = continuity of the *normal component* across faces. Used for fluxes in mixed formulations (Darcy, mixed elasticity) with local conservation properties. Classic families: Raviart–Thomas, BDM; NeoPZ builds its own hierarchical family. + +**In NeoPZ.** Elements [[TPZCompElHDiv]] (+Bound/Collapsed/DuplConnects/Kernel variants); shapes `Shape/TPZShapeHDiv*`; flavors `HDivFamily {EHDivStandard, EHDivConstant, EHDivKernel, EHDivOptimized}` (Shape/TPZEnumApproxFamily.h:5 [repo], default EHDivStandard) selected via [[approx-space-creators]]; `fExtraInternalPOrder` gives hdiv+/hdiv++ enriched internal order (TPZApproxCreator.h:58-59 [repo]). +- *EHDivStandard*: full hierarchical H(div) family (Devloo-group construction). +- *EHDivConstant*: flavor with constant divergence per element (supports rigid-body-mode condensation; related to recent Devloo et al. papers) — hypothesis, verify Phase 3/4. +- *EHDivKernel*: divergence-free subspace (curl of potentials) — the divfreebubbles topic. +- *EHDivOptimized*: unknown semantics — appears in `TestHDivApproxSpaceCreator` GENERATE grid [repo:155]; research Phase 3/4. + +**Invariants to check (Phase 4).** Normal-trace continuity incl. orientation sign consistency under face permutations (`drham_permute_check` tests exist [agent]); div maps onto the pressure space exactly ([[de-rham-complex]]); mapping to physical elements (contravariant [[piola-transformations]] or NeoPZ variant); inf-sup stability of chosen flux×pressure pairs ([[mixed-methods]]). + +**Reference evidence (Phase 3).** Construction: [[devloo-group-shape-construction]] (JCAM 2013 — geometry-based vectors × hierarchical H1 scalars ⇒ conforming traces by construction). Conformity/inf-sup/Piola expectations: [[boffi-brezzi-fortin-2013]]. Flavors & divergence-order variants are published research ([[devloo-hdiv-variants-accuracy]]); semi-hybrid use: [[carvalho-2024-semi-hybrid-stokes]]. + +Related: [[TPZCompElHDiv]] · [[mixed-methods]] · [[de-rham-complex]] · [[piola-transformations]] · [[hybridization]] · [[flow-dupl-connects]] diff --git a/ai-analysis/wiki/concepts/hp-adaptivity.md b/ai-analysis/wiki/concepts/hp-adaptivity.md new file mode 100644 index 000000000..0cc08ed99 --- /dev/null +++ b/ai-analysis/wiki/concepts/hp-adaptivity.md @@ -0,0 +1,25 @@ +--- +type: concept +status: reviewed +updated: 2026-07-06 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - adaptivity +--- + +# hp-adaptivity + +**Idea.** Combine local mesh refinement (h) with local polynomial-order enrichment (p); with the right strategy gives exponential convergence for elliptic problems with singularities. + +**In NeoPZ.** The *mechanisms* are all in-library: per-connect orders (hierarchical [[shape-functions]]), `TPZInterpolatedElement::PRefine`, refinement patterns + directional refinement ([[refinement-hanging-nodes]], [[geometry-refinement-maps]]), side-order compatibility rules ([[element-families]]), and hanging-node restraints resolved at assembly ([[TPZConnect]]). + +**The adaptive *drivers* live downstream — confirmed (Session 2).** The ErrorEstimation app closes the loop: estimator → per-element refinement indicator → `Hrefinement`/`HPrefinement` (h vs hp selection per element, `ErrorNaca.cpp:487-489`) → re-solve, iterated (13-step NACA studies); helpers `Tools::hAdaptivity`, `RandomRefinement` ([[app-error-estimation]]). wann runs estimator-driven adaptive `Divide` loops with an H1-vs-mixed comparison estimator ([[app-wann]]). In-library remains: mechanisms + `pzmganalysis`/gradient reconstruction; no in-tree marking strategy. + +**Invariants (unchanged).** Min/max order rules on shared sides; order propagation after PRefine; p-enrichment × H(div) flavors (`fExtraInternalPOrder`); H(div)/H(curl) restraints under nonuniform refinement remain the thin test area (Phase 7 gap). + +**Reference anchors.** Devloo–Oden hp work; Szabó–Babuška; Demkowicz. + +Related: [[refinement-hanging-nodes]] · [[error-estimation-convergence]] · [[shape-functions]] · [[app-error-estimation]] diff --git a/ai-analysis/wiki/concepts/hybridization.md b/ai-analysis/wiki/concepts/hybridization.md new file mode 100644 index 000000000..4da7b7e33 --- /dev/null +++ b/ai-analysis/wiki/concepts/hybridization.md @@ -0,0 +1,29 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - hybridization +--- + +# Hybridization (standard / "squared" / semi) + +**Idea.** Break inter-element continuity of a space and reimpose it weakly via Lagrange multipliers living on the mesh skeleton. Benefits: block-diagonal element problems → [[static-condensation]] to a skeleton system; multipliers often have physical meaning (trace pressure / displacement). Classic theory: Cockburn–Gopalakrishnan–Lazarov unified hybridization; HDG as descendant. + +**In NeoPZ (Phase 4, traced & verified).** First-class citizen: `HybridizationType {ENone, EStandard, EStandardSquared, ESemi}` (Pre/TPZApproxCreator.h:15 [repo]); `HybridizationData` manages wrap/interface/Lagrange matids (allocated in strides above max mesh matid, `TPZApproxCreator.cpp:38-58`) and multiplier signs `fMultipliers{left,right,2nd-left,2nd-right}`: H1 path Darcy {1,1,1,−1}, Elastic {−1,−1,−1,1} (`TPZApproxCreator.cpp:780-795` [repo, read]); HDiv path branches per type, e.g. Darcy+ESemi {1,−1,1,−1} (`:798-830` [agent]). Geometry: wrap geoels on every interior facet + interface geoels + Lagrange geoels registered in `fInterfaces` (`AddHybridizationGeoElements`, `TPZApproxCreator.cpp:60-263`); glue = `TPZMultiphysicsInterfaceElement` + `TPZLagrangeMultiplierCS` (`:337-368`). + +Verified semantics per type [agent traces, key lines spot-verified]: +- **EStandard (H1)**: broken H1 volume + wrap comp-els *sharing volume connects* + skeleton flux space (HDivStandard on `fLagrangeMatId`, order = default) — one multiplier level; `EAvSol`-level connects explicitly kept out of condensation (`develop:TPZH1ApproxCreator.cpp:758-767`). +- **EStandardSquared (H1, iter_elast)**: literally hybridization², via `AddHybridSquareGeoElements` (`TPZApproxCreator.cpp:578-777`): second interface pair + second Lagrange layer; second-level *primal* multiplier space built inside the L2/H1 atomic mesh (`develop:TPZH1ApproxCreator.cpp:309-332`, Lagrange level `EHybFlux`); condensation groups then absorb the first-level flux+Lagrange DOFs into volume groups (`AssociateElements` numloops=2 + interface-connect propagation, `develop:…:816-881`) — **only the second-level skeleton stays global**. Matches the "double-hybrid" concept of [[avancini-2025-double-hybrid-elasticity]]. +- **ESemi (HDiv, dupl_connects)**: requires `EHDivConstant/EHDivOptimized` (`TPZHDivApproxCreator.cpp:80-83`); flux mesh built with `TPZCompElHDivDuplConnects*` (each facet connect split into even=constant-flux + odd=higher-order); `SemiHybridizeDuplConnects` (`:1239-1299`) rebinds **only the even/constant connect, on the sideOrient==−1 side of each interior facet**, to the wrap element — higher-order facet functions remain strongly continuous; multiplier submesh order 0. Matches the semi-hybridization of [[carvalho-2024-semi-hybrid-stokes]] structurally (which trace continuity is weakened differs: here it's the *constant normal flux* that becomes multiplier-mediated — variant, not textbook copy). +- Elasticity-in-HDiv needs a rotation space for weak symmetry (scalar in 2D / 3-vector in 3D, `TPZHDivApproxCreator.cpp:603-606`); condensed HDivConstant elasticity is guarded (`:85-89` — "singular K00" comment) unless ESemi or rigid-body spaces supply the missing constant modes. + +**Invariants to check.** Multiplier space order vs trace order (matching for stability); transmission conditions assemble with correct signs (left/right interface materials); condensed skeleton system SPD-ness (iter_elast solves it with LDLt/Schur-CG [repo]). + +**Reference evidence (Phase 3).** Frame: [[cockburn-2009-unified-hybridization]] (multiplier = trace unknown; condensed SPD skeleton system; variants are legitimate design choices). `EStandardSquared` ↔ primal *double-hybrid* elasticity with H(div)–L² pair and weak tangential continuity via shear-traction multipliers ([[avancini-2025-double-hybrid-elasticity]], CMAME 2025 — mapping hypothesis-level until Phase 4). `ESemi` ↔ *semi-hybridization*: strong normal continuity kept, tangential/partial coupling weak via traction multiplier, realized with duplicated connects ([[carvalho-2024-semi-hybrid-stokes]], IJNME 2024). + +Related: [[static-condensation]] · [[mixed-methods]] · [[approx-space-creators]] · [[flow-iter-elast]] · [[mhm]] diff --git a/ai-analysis/wiki/concepts/mhm.md b/ai-analysis/wiki/concepts/mhm.md new file mode 100644 index 000000000..867a9fa6e --- /dev/null +++ b/ai-analysis/wiki/concepts/mhm.md @@ -0,0 +1,23 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: low +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - multiscale +--- + +# MHM — Multiscale Hybrid-Mixed method + +**Idea.** Multiscale method: hybridize on a coarse skeleton; solve local (fine-mesh) problems per coarse cell that upscale fine-scale behavior into the coarse system. Developed in the Brazilian FEM community (Harder–Paredes–Valentin line; Devloo-group implementations/extensions). + +**In NeoPZ.** `Pre/TPZMHMeshControl.h`, `TPZMHMixedMeshControl.h`, `TPZMHMixedHybridMeshControl.h` (controller generation), `Pre/TPZMHMHDivApproxCreator.h`/`TPZMHMH1ApproxCreator.h` (creator generation) [agent]; substructuring via `TPZSubCompMesh` ([[static-condensation]]). App-side: `TPZMHMGeoMeshCreator` + `TPZMHMHDivApproxCreator` in [[divfree-support-lib]], exercised by [[flow-mhm-hdivconstant]] (polygonal coarse cells from quadtree import, `EHDivConstant` family, rigid-body spaces, `PutinSubstructures`/`CondenseElements`, `EMHMSparse` Schur solver) [agent/repo pending trace]. + +**Invariants to check (Phase 4).** Coarse-skeleton flux continuity; local-problem well-posedness (constant/rigid-body handling per subdomain); upscaled system SPD-ness; consistency between the two generations (controllers vs creators — duplication?). + +**Reference evidence (Phase 3).** Origin: [[araya-2013-mhm]] (SINUM 2013) — coarse-skeleton multipliers, independent local problems, locally conservative dual, subdomain constant/rigid-body kernels as coarse unknowns (explains `IsRigidBodySpaces()=true` in the slice). Group variant for elasticity on polygonal meshes: [[devloo-mhm-elasticity-polygonal]] (displacement & stress-divergence superconvergence). + +Related: [[hybridization]] · [[static-condensation]] · [[hdiv-space]] · [[flow-mhm-hdivconstant]] diff --git a/ai-analysis/wiki/concepts/mixed-methods.md b/ai-analysis/wiki/concepts/mixed-methods.md new file mode 100644 index 000000000..fe5d6c6e9 --- /dev/null +++ b/ai-analysis/wiki/concepts/mixed-methods.md @@ -0,0 +1,23 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz +--- + +# Mixed methods (saddle-point formulations) + +**Idea.** Approximate two fields simultaneously (e.g. Darcy: flux σ ∈ H(div) and pressure p ∈ L²) yielding a saddle-point system; stability requires inf-sup-compatible space pairs; payoff = locally conservative fluxes / direct stress approximation. + +**In NeoPZ.** Multiphysics machinery: atomic cmeshes per field combined in `TPZMultiphysicsCompMesh` ([[TPZCompMesh]]); combined-space materials (`TPZMatCombinedSpacesT`): `DarcyFlow/TPZMixedDarcyFlow`, `Elasticity/TPZMixedElasticityND`, `TPZHybridMixedElasticityUP` ([[material-system]]); spaces built by `TPZHDivApproxCreator` with `ProblemType::{EDarcy,EElastic}` ([[approx-space-creators]]); Lagrange-multiplier levels on connects order the condensation. App-side slices: [[flow-dupl-connects]], [[flow-dfreebubbles-1el]], hpc4 (3D mixed elasticity, SPE10-like). + +**Resolved (Sessions 1–2).** Mixed elasticity symmetry = **weak symmetry with a rotation/skew multiplier space** (scalar 2D / 3-vector 3D), confirmed both in the creator (`TPZHDivApproxCreator.cpp:603-606`, Session 1) and at scale downstream: [[app-mixed-elasticity]] runs 3-, 5- and 7-field Hellinger–Reissner couplings (stress rows as H(div) vectors with `NStateVariables=dim`, plus rigid-body multiplier spaces), and also builds *strongly*-symmetric Johnson–Mercier tensors at app level. The p>0 L² pressure realization is broken-H1, p=0 is `TPZCompElDisc` ([[discontinuous-l2-dg]]). Combined-space `Contribute` receives datavec in mesh-vector order ([[multiphysics-composition]]). +**Still open.** Flux×pressure order pairing per `HDivFamily` (RT-like vs BDM-like classification); local conservation not directly unit-tested. + +**Reference anchors.** Boffi–Brezzi–Fortin (canonical); Devloo et al. mixed-elasticity papers (multiphysics + weak symmetry); Arnold's stress-element literature as contrast. + +Related: [[hdiv-space]] · [[hybridization]] · [[static-condensation]] · [[de-rham-complex]] · [[error-estimation-convergence]] diff --git a/ai-analysis/wiki/concepts/piola-transformations.md b/ai-analysis/wiki/concepts/piola-transformations.md new file mode 100644 index 000000000..f64b88116 --- /dev/null +++ b/ai-analysis/wiki/concepts/piola-transformations.md @@ -0,0 +1,33 @@ +--- +type: concept +status: reviewed +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - hdiv + - hcurl +--- + +# Piola transformations (vector-basis mapping) — RESOLVED for H(div) + +**Idea (reference).** Mapping vector shape functions master→physical must preserve the conforming trace: H(div) uses the *contravariant* Piola map σ_phys = (1/detJ)·J·σ̂ (preserves normal traces & divergence pairing); H(curl) the *covariant* map ([[boffi-brezzi-fortin-2013]] Ch.2). + +## What NeoPZ actually does (verified, Phase 4) +The H(div) pipeline **implements the contravariant Piola transform in a split factorization** [repo, verified first-hand]: +1. **Shape layer emits master-element quantities only**: each vector shape = scalar H1 shape × constant master direction vector (`TPZShapeHDiv.cpp:345-355` — `phi = φ_H1·v̂`, `div = ∇̂φ_H1·v̂`); master directions come from Topology with identity gradx (`TPZShapeHDiv.cpp:83-92`), where the topology routine is itself commented "contravariant piola mapping" (`tpztriangle.cpp:1064-1068`) [agent, spot-verified]. +2. **Element layer applies the map pointwise**: `gradx.MultAdd(phiMaster, fDeformedDirections, …, 1./fabs(detjac))` and `divphi *= 1/fabs(detjac)` (`Mesh/pzelchdiv.cpp:1032-1033` [repo, read]) — i.e. σ_phys = (1/|detJ|)·J·σ̂, div_phys = div̂/|detJ|. +3. **Sign convention — NeoPZ variant**: uses **|detJ|**, delegating orientation signs to `fSideOrient` (from `TPZGeoEl::NormalOrientation`, `pzelchdiv.cpp:49-53`) folded into the master directions (`TPZShapeHDiv.cpp:104`); facet-DOF neighbor compatibility via topology permutation gather (`HDivPermutation`, `TPZShapeHDiv.cpp:407-459`) [agent, lines cited]. +4. **Curved elements**: gradx/detjac evaluated pointwise (no affine shortcut); optional **FAD branch** (`fNeedsDeformedDirectionsFad`, `pzelchdiv.cpp:979-1031` [repo:1026-1030 read]) seeds ∂/∂x via jacinv and re-applies the same Piola map to get exact physical-space derivatives of the mapped basis. Algebraic div scaling is exact for general smooth maps (Piola identity), so no hidden affine assumption [agent derivation note]. + +`TPZShapeHDivConstant` (constant-divergence family): per facet one RT0 function carries the (constant) divergence; all other functions are divergence-free curls from `TPZShapeHCurlNoGrads` / rotated H1 gradients (`TPZShapeHDivConstant.cpp:129-215`) — matches the flavor semantics hypothesized in [[hdiv-space]]. + +## Residual expert-validation items (kept open deliberately) +- |detJ| ⊕ `fSideOrient` composition on *all* refinement/orientation configurations (the `NormalOrientation` father-walk was not exhaustively traced) — derivation or targeted test would close it. +- Intentionality of using algebraic divergence (not the computed-but-unused `divphiFad`) on curved elements — maintainer confirmation. +- H(curl) covariant map: **structurally confirmed in Session 2** — `TPZCompElHCurl::TransformShape` applies `phi = axesᵀ·J⁻ᵀ·phî` ("applies covariant piola transform", `TPZCompElHCurl.cpp:564-578`), curl mapped separately (3D `J·curl̂/detJ`); orientation is implicit via node-id transform ids (no `fSideOrient` analog) — see [[element-families]]. Sign-composition scrutiny at HDiv depth remains open. +- Related finding: [[finding-hdivconstant-fad-index]] (FAD branch facet-count inconsistency). + +Related: [[hdiv-space]] · [[TPZCompElHDiv]] · [[shape-functions]] · [[geometric-mappings]] · [[devloo-hdiv-variants-accuracy]] diff --git a/ai-analysis/wiki/concepts/quadrature.md b/ai-analysis/wiki/concepts/quadrature.md new file mode 100644 index 000000000..9f68808e0 --- /dev/null +++ b/ai-analysis/wiki/concepts/quadrature.md @@ -0,0 +1,22 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz +--- + +# Numerical integration (quadrature) + +**Idea.** Element integrals evaluated by quadrature on the master element; rule order must cover integrand order (2p + geometry effects), with special handling for singular integrands. + +**In NeoPZ.** `Integral/` module: abstract `tpzintpoints.h`, Gauss rules `tpzgaussrule.h`, per-topology rules (`pzquad.h`: `TPZInt{Quad,Triang,Cube,Tetra3D,Pyram3D,Prism3D}`), tensor & collapsed constructions, `TPZIntQuadQuarterPoint` (singular quarter-point rule), adaptive `adapt.h`. Doxygen note: computations use/return **long double** internally [agent] — precision-vs-cost choice worth noting. Element integration order = f(connect orders) with user override (`SetIntegrationRule`); materials can request order bumps (`IntegrationRuleOrder`) [pattern; verify sites Phase 4]. `TestIntegNum` validates polynomial exactness per topology, but several cases commented out (2D quad, 3D cube/tetra/pyramid) [agent] → Phase 7 note. + +**Invariants to check.** Order sufficiency for: nonconstant Jacobians (curved els), material coefficients, `fExtraInternalPOrder`-enriched spaces, and error integration (`SetExact` order param, e.g. iter_elast passes `solOrder=4` [repo:iter_elast.cpp:87,275]). + +**Reference anchors.** Standard texts (Ern–Guermond); rule tables (Dunavant etc.) as needed only. + +Related: [[assembly]] · [[geometric-mappings]] · [[shape-functions]] diff --git a/ai-analysis/wiki/concepts/refinement-hanging-nodes.md b/ai-analysis/wiki/concepts/refinement-hanging-nodes.md new file mode 100644 index 000000000..fc92c965c --- /dev/null +++ b/ai-analysis/wiki/concepts/refinement-hanging-nodes.md @@ -0,0 +1,24 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - adaptivity +--- + +# h-refinement, refinement patterns & hanging nodes + +**Idea.** Subdivide elements (h-refinement) possibly non-uniformly → "hanging" nodes on interfaces between refinement levels; conformity restored by constraining hanging DOFs to coarse-side DOFs (dependency/constraint matrices), or by pattern-conforming closures. + +**In NeoPZ (distinctive design).** *Runtime-defined refinement patterns*: `Refine/TPZRefPattern.h` + `TPZRefPatternDataBase` + 71 `.rpt` data files (`Refine/RefPatterns/`) describe father→sons subdivisions as little meshes; `TPZGeoElRefPattern` applies them ([[TPZGeoMesh]]). Uniform refinement via per-topology `TPZRef*` classes. Hanging-node constraints live on connects: `TPZConnect` dependency matrices ([[TPZCompMesh]]), built by `TPZInterpolatedElement` restraint logic; validated by `TestHangingNode`, `TestCondensedSpace` ("Constrained Space"), and a refinement suite [agent]. README claims hp-adaptivity + hanging-node support as headline features [repo:README.md:16-19]. + +**Traced (Session 2, [[geometry-refinement-maps]] §3 + [[TPZConnect]]).** The full path is now line-cited: geometric `Divide` → `CreateMidSideConnect` consults `LowerLevelElementList` (ancestor walk) → `RestrainSide` builds the L2 projection of the coarse trace through `SideTransform3` → `TPZConnect::AddDependency`; constraints resolve per element in `ApplyConstraints` (complex-correct congruence transform), topologically ordered. H(div)/H(curl) have their **own** `RestrainSide` overrides (HCurl DebugStops when small-side order < large order). Dependency closure enforced by `BuildDependencyOrder` fixpoint. Pattern compatibility fails loudly (midnode mismatch DebugStop). Downstream: directional refinement to wells/crack tips ([[app-wann]], [[app-gfem]]); custom patterns as macro-element constructors ([[app-mixed-elasticity]]); hand-built `AddDependency` for cross-dimensional coupling ([[app-wann]]). +**Remaining Phase-7 gap.** Constrained H(div)/H(curl) under nonuniform refinement is still the thin *test* area (the code paths exist). + +**Reference anchors.** Devloo's early adaptivity papers (Devloo–Oden 1987-89 line); Demkowicz hp book (constrained approximation); Šolín et al. as contrast. + +Related: [[TPZGeoMesh]] · [[TPZCompMesh]] · [[shape-functions]] · [[hp-adaptivity]] diff --git a/ai-analysis/wiki/concepts/sbfem.md b/ai-analysis/wiki/concepts/sbfem.md new file mode 100644 index 000000000..daeb605f6 --- /dev/null +++ b/ai-analysis/wiki/concepts/sbfem.md @@ -0,0 +1,24 @@ +--- +type: concept +status: reviewed +updated: 2026-07-06 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz +--- + +# SBFem — Scaled Boundary FEM + +**Idea.** Semi-analytical method: discretize only the boundary of star-shaped subdomains; the radial direction is handled analytically via an eigenvalue problem (good for singularities/unbounded domains). + +**In NeoPZ (Session-2 deep dive, agent-traced).** Classes: `Mesh/TPZSBFemElementGroup` (the eigenproblem owner — a [[condensation-groups-submeshes|TPZElementGroup]] subclass), `TPZSBFemVolume` (per-volume element carrying the eigen-basis), HDiv/L2/multiphysics variants (`TPZSBFemVolumeHdiv/L2/Multiphysics`, `TPZSBFemMultiphysicsElGroup`, `TPZCompElHDivSBFem`); builders `Pre/TPZBuildSBFem(Multiphysics)` (partition + per-partition center nodes + matid translation map). +**Eigen construction** (`TPZSBFemElementGroup.cpp`): assemble coefficient matrices E0,E1,E2 (+mass M0) from skeleton elements (`ComputeMatrices` :87-181); form the 2n×2n block **Hamiltonian** `[[E0⁻¹E1ᵀ, −E0⁻¹],[E1E0⁻¹E1ᵀ−E2, −E1E0⁻¹]]` with a ±(dim−2)/2 diagonal shift (:703-744); solve the **non-symmetric** eigenproblem — directly via LAPACK `dgeev_` (:1845-1864, verified) or an alternative blaze-lib path (`CalcStiffBlaze` :189-276); select modes with Re(λ)<0 as the radial basis; eigenpairs are `std::complex` throughout; bubble modes get a second eigenproblem. Note it **bypasses** the library's `TPZEigenSolver` stack and calls LAPACK/blaze directly. +**Validation**: `TestSBFem`/`TestSBFemHdiv` — the only in-tree suites asserting actual **convergence rates** (Darcy + 3D elasticity). + +**Downstream evidence (Session 2).** SBFem is alive as a *tool*, not just a method: GFEM extracts crack-tip singular enrichment modes from `TPZSBFemElementGroup::EigenValues()/LoadEigenVector()` ([[app-gfem]]); ErrorEstimation subclasses the builders/groups (`TPZBuildSBFemHybrid`, `TPZSBFemElementGroupPostProcess`) and offers SBFem as one of four mesh styles around singularities ([[app-error-estimation]]). + +**Reference anchors.** Song & Wolf (SBFem origin); Devloo-group SBFem papers (sbfempaper branch exists [repo branch list]). + +Related: [[hdiv-space]] · [[matrix-and-solvers]] · [[condensation-groups-submeshes]] · [[app-gfem]] · [[app-error-estimation]] diff --git a/ai-analysis/wiki/concepts/static-condensation.md b/ai-analysis/wiki/concepts/static-condensation.md new file mode 100644 index 000000000..d7c76b776 --- /dev/null +++ b/ai-analysis/wiki/concepts/static-condensation.md @@ -0,0 +1,23 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz +--- + +# Static condensation + +**Idea.** Eliminate element-interior DOFs at element level (Schur complement of the interior block) so the global solve only sees interface/skeleton unknowns; recover interior afterwards. + +**In NeoPZ.** `Mesh/pzcondensedcompel.h` (`TPZCondensedCompEl`) is a decorator over `fReferenceCompEl` exposing only `fActiveConnectIndexes` (NConnects/ConnectIndex overridden; condensed connects listed separately; `Unwrap()` reverses; internal Schur container = library `TPZMatRed` via `pzmatred.h` include; `fKeepMatrix` flag controls memory retention) — verified [repo pzcondensedcompel.h:20-110]. It wraps an element/group; `Mesh/pzelementgroup.h` groups elements pre-condensation; connect "Lagrange levels" order which DOFs are condensable (e.g. keep one pressure per element for zero-mean constraints — rigid-body spaces `fIsRBSpaces` in [[approx-space-creators]] exist exactly to make internal blocks invertible [repo:TPZApproxCreator.h:67-68]). `TPZSubCompMesh` provides the coarser-grained variant (whole submesh condensed) used by [[mhm]]. Matrix-side: `Matrix/pzmatred.h` `TPZMatRed` (K11/K01 reduction container) [agent]; app-side `TPZMatRedSolver` drives reductions iteratively ([[divfree-support-lib]]). +`TPZCompMesh::NEquations()` (condensed) vs `Solution().Rows()` (full) — observed in iter_elast [repo:257-272]. + +**Invariants to check (Phase 4).** Invertibility of condensed blocks (pivoting? symmetric LDLt assumptions); consistency of recovery step (`LoadSolution` path through condensed wrappers); interaction with equation filters and renumbering; correctness under `SetShouldCondense(false)` + later `GroupAndCondenseElements` (iter_elast does exactly this sequence [repo:224-233]). + +**Session 2:** full code-level trace (Resequence partition rules, K11Reduced/UGlobal round trip, SetKeepMatrix memory mode, submesh Schur exposure, ordering constraints) now in [[condensation-groups-submeshes]]; connect-level mechanics in [[TPZConnect]]. Downstream: manual group+condense in [[app-iterative-saddle-point]] and [[app-mixed-elasticity]]. + +Related: [[hybridization]] · [[mixed-methods]] · [[structural-matrices]] · [[mhm]] · [[flow-iter-elast]] · [[condensation-groups-submeshes]] diff --git a/ai-analysis/wiki/concepts/vtk-output.md b/ai-analysis/wiki/concepts/vtk-output.md new file mode 100644 index 000000000..503ea05bc --- /dev/null +++ b/ai-analysis/wiki/concepts/vtk-output.md @@ -0,0 +1,23 @@ +--- +type: concept +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - fem + - neopz + - visualization +--- + +# VTK output model + +**Idea.** Visualization files for ParaView: legacy `.vtk` (ASCII, simple) vs XML `.vtu` (binary/appended, richer). High-order FE fields must either be subdivided into linear cells or use VTK high-order (Lagrange) cells. + +**In NeoPZ.** Modern path: `TPZVTKGenerator` writes legacy-format `.vtk`; each computational element subdivided per `vtkRes` into linear cells (`TPZVTK::CellType` map: point/line/tri/quad/tet/pyr/prism/hex [repo:Post/TPZVTKGenerator.h:30-56]); fields = material `Solution()` variables by name. Legacy path: graph meshes (`pzvtkmesh` and other formats). Geometric-mesh dumps: `TPZVTKGeoMesh` (used for debugging, e.g. the 71MB `GeoMeshHybrid.vtk` in divfreebubbles build dir [repo ls]). Output *meaning*: pointwise evaluations of the FE solution at subdivision nodes — no projection/smoothing (verify), duplicated points across elements allow discontinuous fields (verify representation). + +**Invariants to check (Phase 4).** Node ordering per VTK cell type; sub-element node placement for vtkRes>0; scalar/vector/tensor component conventions (ParaView expects 3-vectors); whether discontinuities across element boundaries are representable (point duplication) — matters for L² pressure fields in mixed methods. + +**Reference anchors.** VTK legacy file-format spec (Kitware); NGSolve vtkoutput (declared origin of the adaptation [repo header]). + +Related: [[post-processing-vtk]] · [[material-system]] · [[flow-dfreebubbles-1el]] · [[flow-mhm-hdivconstant]] diff --git a/ai-analysis/wiki/devloo-1997-pz-environment.md b/ai-analysis/wiki/devloo-1997-pz-environment.md new file mode 100644 index 000000000..0092b9614 --- /dev/null +++ b/ai-analysis/wiki/devloo-1997-pz-environment.md @@ -0,0 +1,2 @@ +# devloo-1997-pz-environment + diff --git a/ai-analysis/wiki/devloo-group-shape-construction.md b/ai-analysis/wiki/devloo-group-shape-construction.md new file mode 100644 index 000000000..3b41a163e --- /dev/null +++ b/ai-analysis/wiki/devloo-group-shape-construction.md @@ -0,0 +1,2 @@ +# devloo-group-shape-construction + diff --git a/ai-analysis/wiki/finding-debugstop-throws-release.md b/ai-analysis/wiki/finding-debugstop-throws-release.md new file mode 100644 index 000000000..6718459e2 --- /dev/null +++ b/ai-analysis/wiki/finding-debugstop-throws-release.md @@ -0,0 +1,2 @@ +# finding-debugstop-throws-release + diff --git a/ai-analysis/wiki/findings/finding-approx-creator-hygiene.md b/ai-analysis/wiki/findings/finding-approx-creator-hygiene.md new file mode 100644 index 000000000..b7eb4c6b9 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-approx-creator-hygiene.md @@ -0,0 +1,38 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: minor +evidence-commit: 6ffd38b12 +tags: + - neopz + - approx-creators + - cpp +--- + +# Approx-creator hygiene cluster: dead guards, mis-scoped if, stubs, dead machinery + +Small verified defects in the space-creator layer. None mis-computes on today's live paths; each is a trap for the next maintainer. Grouped because a single review/PR could clear them. + +## Verified items (first-hand [repo], develop pin) +1. **Tautological guard, dead DebugStop** — `develop:Pre/TPZH1ApproxCreator.cpp` (`CreateBoundaryHDivSpace`): `if (fHybridType != EStandard || fHybridType != EStandardSquared) {…} else DebugStop();` — the `||` makes the condition always true; intended `&&`. Read via `git show develop:` (≈:642). +2. **Mis-scoped if (missing braces)** — same file, `CreateAtomicMeshes` (≈:104-106): `if(HybridType() != ENone)` guards only `meshvec[0]=CreateBoundaryHDivSpace();` — the equally-indented `meshvec[1]=CreateL2Space();` runs unconditionally. Benign today (ENone DebugStops earlier), latent under-fill of `meshvec` for any future non-hybrid path. +3. **Stub method** — `develop:Pre/TPZH1ApproxCreator.h:99-102`: `CreateRotationSpace` is a `DebugStop()` stub; elastic rotational modes are folded into `CreateConstantSpace` state counts instead [agent, consistent with :224-254]. +4. **Stored-but-unused config** — `fH1Fam` (`develop:Pre/TPZH1ApproxCreator.h:19`) is never branched on in the build path [agent grep]. +5. **Dead interface machinery (HDiv creator)** — `AddInterfaceComputationalElementsBackup` (`Pre/TPZHDivApproxCreator.cpp:844-928`) and the purpose-built `TPZCompElUnitaryLagrange` element are uncalled; the live path uses the generic `TPZMultiphysicsInterfaceElement` (`:568,800`) [agent, caller-grep]. Header comment "Check with Jeferson if this variable is indeed necessary" (`Mesh/TPZCompElHDivDuplConnects.h:19`) marks known uncertainty around `fConnDuplicated` lifetime. +6. (Cross-ref) copy-op member omission in the layer-1 factory: [[finding-approxspace-copy-drops-families]]. + +## Why it matters +The creator layer is the library's *current* front door (unit tests + app repos build through it). Dead guards and unbraced ifs in exactly the methods being actively refactored (the develop→HEAD delta moves code between `GroupElements`/`CondenseElements` here) raise the odds that a future edit activates a latent path. Essential-vs-accidental: **accidental complexity** — none of these is FEM-driven. + +## Suggested improvement (low risk) +`&&` fix + braces + delete-or-wire the Backup/UnitaryLagrange pair + remove or use `fH1Fam` + either implement or remove the rotation stub; all under existing unit-test cover (`TestH1ApproxSpaceCreator`, `TestHDivApproxSpaceCreator`). + +## Open questions +- EStandardSquared: what keeps `EAvSol`-level connects globally coupled (the explicit `IncrementElConnected` runs only for EStandard, `develop:…:758-767`)? Works today per tests; mechanism unclear → expert Q (§10 of final report). +- Elastic multiplier asymmetry: only the right interface is reset to +1 (`develop:…:210-212`) vs Darcy resetting both — physical intent not determinable from code alone → expert Q. + +## Related +[[approx-space-creators]] · [[hybridization]] · [[flow-iter-elast]] · [[flow-dupl-connects]] diff --git a/ai-analysis/wiki/findings/finding-approxspace-copy-drops-families.md b/ai-analysis/wiki/findings/finding-approxspace-copy-drops-families.md new file mode 100644 index 000000000..b5c993d5b --- /dev/null +++ b/ai-analysis/wiki/findings/finding-approxspace-copy-drops-families.md @@ -0,0 +1,33 @@ +--- +type: finding +status: draft +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: minor +evidence-commit: 6ffd38b12 +tags: + - neopz + - approximation + - cpp +--- + +# TPZCreateApproximationSpace copy operations silently drop the space-family flags + +## Repository evidence +`Pre/pzcreateapproxspace.h` [repo]: members include `HDivFamily fhdivfam`, `H1Family fh1fam`, `HCurlFamily fhcurlfam` (:44-46) and `MApproximationStyle fStyle` (:53). The copy constructor (:63-69) copies only `fp[8]` + `fCreateHybridMesh` + `fCreateLagrangeMultiplier` + `fCreateWithMemory`; `operator=` (:71-80) the same. **Family flags and style are not copied** → they reset to `DefaultFamily::…` (EHDivStandard/EH1Standard/EHCurlStandard) on the copy while the creation function pointers still reflect the source configuration. + +## Failure scenario (mechanism-level) +Any path that copies a configured `TPZCompMesh::ApproxSpace()` (mesh clone/copy, or user code assigning one approx space from another) after `SetHDivFamily(EHDivConstant)`-style configuration yields a factory in a mixed state: fp[] creates H(div) elements, but elements consult the (now default) family flag → silently different space than intended (e.g. EHDivStandard instead of EHDivConstant), with no error. + +## Impact qualifier (why severity is only *minor* pending Phase 5) +Impact depends on real call sites of the copy ops (TPZCompMesh copy ctor / Clone / persistence Read all candidates). If no live path copies a *family-configured* space, this stays a latent trap. → Phase 5: enumerate call sites; upgrade severity if a clone path is live in creators/tests. + +## Adjacent hygiene (same header) +`const void SetHDivFamily(...)` etc. — `const void` return type; duplicated const/non-const getters both returning `const&` (:98-108). Cosmetic, but signals missing review on this header. + +## Suggested improvement +Default the copy operations (`= default`) — all members are copyable — or copy the missing members explicitly; add a unit test cloning a `EHDivConstant`-configured mesh. + +## Related +[[approx-space-creators]] · [[TPZCompMesh]] · [[hdiv-space]] diff --git a/ai-analysis/wiki/findings/finding-build-config-gaps.md b/ai-analysis/wiki/findings/finding-build-config-gaps.md new file mode 100644 index 000000000..bd6276f29 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-build-config-gaps.md @@ -0,0 +1,29 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: major +evidence-commit: 6ffd38b12 +tags: + - neopz + - build + - cpp +--- + +# Build-configuration gaps: default build gets neither debug checks nor release paths; 14 dead DEBUG blocks; warnings off + +## Repository evidence (verified first-hand) +1. `CMakeLists.txt:82-87`: `PZNODEBUG` only under `$`, `PZDEBUG` only under `$` (plus RELEASE-only `ZERO_INTERNAL_RESIDU`/`MAKEINTERNAL`). The **default build type is RelWithDebInfo** (`cmake/StandardPZSettings.cmake:1-14` [agent, consistent with observed builds]) — it matches neither generator expression ⇒ the recommended default compiles with **no `PZDEBUG` assertions and no `PZNODEBUG`/release fast-paths**; 142 headers gate on PZDEBUG [agent count]. (Observed: the user's own `NeoPZ_divfree_build` is RelWithDebInfo.) +2. **14 dead `#ifdef DEBUG` blocks** (macro never defined by the build — project macro is `PZDEBUG`): verified sample `Mesh/TPZCompElHDivDuplConnects.cpp:62-66` (a bounds check + DebugStop that never compiles); count verified via grep across Mesh/Shape/Material. Includes checks in `pzelchdiv.cpp`, `pzelchdivbound2.cpp`, `TPZMixedElasticityND.cpp`, `TPZShapeHDivOptimized.cpp` [agent]. +3. **Warnings effectively off**: zero `-Wall/-Wextra/-Werror` in the build (verified grep); only `-Wsuggest-override`, `-Wno-narrowing`, `-Wno-alloc-size-larger-than`; and on Apple, `XCODE_ATTRIBUTE_WARNING_CFLAGS ""` explicitly silences Xcode warnings (`CMakeLists.txt:88-90`, verified). + +## Why it matters +These three interact: the checks that would catch defects (PZDEBUG guards, dead DEBUG guards, compiler warnings) are all disabled in the configuration users actually build. Several defects found in this assessment (dead guards around exactly the duplicated-connect code; narrowing suppressions) would likely have surfaced earlier with `-Wall` + working assert config. + +## Classification +**Confirmed defects (accidental)** — none is a domain tradeoff; all are hours-scale fixes: add a RelWithDebInfo case (or key on `NDEBUG`), global `DEBUG`→`PZDEBUG` rename, `-Wall -Wextra` at least in CI. + +## Related +[[finding-debugstop-throws-release]] · [[finding-approx-creator-hygiene]] · CPP_TECHNICAL_REVIEW §2-H5 · TESTING_AND_VALIDATION_REVIEW (CI angle) diff --git a/ai-analysis/wiki/findings/finding-debugstop-throws-release.md b/ai-analysis/wiki/findings/finding-debugstop-throws-release.md new file mode 100644 index 000000000..0d982bdf3 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-debugstop-throws-release.md @@ -0,0 +1,32 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: major +evidence-commit: 6ffd38b12 +tags: + - neopz + - cpp + - error-handling +--- + +# DebugStop() throws a messageless std::bad_exception unconditionally — including Release builds + +## Repository evidence (verified first-hand) +`Common/pzerror.cpp:10-29`: `DebugStopImpl` prints "Your chance to put a breakpoint at file:line" to `PZError` and then `throw std::bad_exception();` — the `#ifdef PZDEBUG` guards are **commented out** (:15,:17), so this runs in every configuration. Call-site scale: ~3,029 `DebugStop()` occurrences vs ~51 `throw` and ~9 `catch` library-wide [agent counts]. + +## Why it matters +- The library's universal assertion mechanism behaves as an unrecoverable, message-free exception in production: uncaught (9 catches for 3k sites), it terminates with no file:line in the exception object (only on cerr, which GUIs/batch systems may swallow). +- `std::bad_exception` is semantically wrong (it exists for exception-specification violations), and carrying no payload makes programmatic handling impossible — downstream apps (e.g. divfreebubbles) cannot distinguish "hanging-node unsupported here" from "matrix singular". +- Interacts with [[finding-build-config-gaps]]: in the default RelWithDebInfo build, the `#ifdef PZDEBUG` *pre-checks* are compiled out while unguarded `DebugStop()`s still throw — an inconsistent middle state. + +## Classification +**Confirmed defect (accidental complexity)** — not a domain requirement. The commented-out guard shows the release behavior is unintentional or at least unreviewed. + +## Suggested improvement / risk +Introduce a typed `TPZFatalError{file,line,msg}` (or abort in debug, throw typed in release); mechanical sed-scale replacement, low risk; enables meaningful catches at analysis boundaries. Consider keeping `DebugStop` name as macro alias for compatibility. + +## Related +[[finding-build-config-gaps]] · [[material-system]] · CPP_TECHNICAL_REVIEW §2-H1 diff --git a/ai-analysis/wiki/findings/finding-global-state-cluster.md b/ai-analysis/wiki/findings/finding-global-state-cluster.md new file mode 100644 index 000000000..b6d85cb50 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-global-state-cluster.md @@ -0,0 +1,33 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: major +evidence-commit: 6ffd38b12 +tags: + - neopz + - cpp + - thread-safety +--- + +# Global mutable state cluster: per-TU gTolerance (broken setter), gRefDBase, legacy statics + +## 1. `pztopology::gTolerance` — header-scope `static` ⇒ per-TU copies (verified first-hand) +`Topology/TPZTopologyUtils.h:23`: `static REAL gTolerance = pow(10, …);` at namespace scope in a header — internal linkage, one copy per translation unit. `SetTolerance/GetTolerance` are defined in `TPZTopologyUtils.cpp:13-16` and touch **only that TU's copy** [agent]; other readers (`tpzprism.cpp:990`, header default arguments in `tpzline.h:126,129`) each see their own copy. **`SetTolerance()` is a de-facto no-op for most of the library.** A commented-out `Settings` singleton sits directly above (:14-21, visible in the verified read) — the intended fix was known. Fix: C++17 `inline` variable or the singleton; trivial, low risk. +Classification: **confirmed bug** (silent misbehavior of a public API). + +## 2. `gRefDBase` — global mutable refinement-pattern database +`Refine/TPZRefPatternDataBase.h:101` `extern TPZRefPatternDataBase gRefDBase`, mutated at runtime by `InitializeUniformRefPattern/InitializeAllUniformRefPatterns/InsertRefPattern/ReadRefPatternDBase/clear` [agent]. Read on the refinement path ⇒ concurrent adaptivity + any mutation is unsynchronized; tests become order-dependent through shared state. Classification: **essential-ish concept (pattern cache), accidental realization** — should be injectable/owned or internally synchronized. Severity M. + +## 3. Legacy statics (contained in `needrefactor/`) +Non-reentrant `TPZCoupledTransportDarcy::gCurrentEq` (set via `SetCurrentMaterial`), `TPZBurger::gStabilizationScheme`, biharmonic coefficient globals [agent]. Prevent two problem instances coexisting; already self-labeled as refactor debt by directory name. Severity L (quarantined but still compiled into `pz`). + +Also: `gSinglePointMemory` (`Mesh/pzcompelwithmem.h:36`) flips element memory allocation globally [agent]; `gPrintLevel` (`Common/pzreal.h:170`). + +## Why it matters +These are the classic blockers for (a) thread-safe adaptive refinement, (b) reproducible test isolation, (c) two meshes/problems with different tolerances/settings in one process. The tolerance item is the sharpest: a *public setter that silently does nothing* for most consumers. + +## Related +[[topology-module]] · [[refinement-hanging-nodes]] · [[finding-thread-shared-materials]] · CPP_TECHNICAL_REVIEW §2-H2/§3-M5 diff --git a/ai-analysis/wiki/findings/finding-hdivconstant-fad-index.md b/ai-analysis/wiki/findings/finding-hdivconstant-fad-index.md new file mode 100644 index 000000000..6f11eefb3 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-hdivconstant-fad-index.md @@ -0,0 +1,30 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: minor +evidence-commit: 6ffd38b12 +tags: + - neopz + - hdiv + - shape-functions +--- + +# TPZShapeHDivConstant: FAD branch indexes facet kernel-function counts inconsistently with the REAL branch + +## Repository evidence (verified first-hand) +`Shape/TPZShapeHDivConstant.cpp` 3D `Shape(...)`: the REAL branch iterates per facet `i` with `data.fHCurl.fNumConnectShape[nedges + i]` kernel functions (:191); the FAD overload uses `data.fHCurl.fNumConnectShape[nedges]` for **every** facet (:304) — facet 0's count applied to all facets. + +## Failure scenario +Trigger requires all of: 3D element, `HDivFamily::EHDivConstant`, the FAD path (`fNeedsDeformedDirectionsFad`, i.e. typically curved/nonlinear geometry), **and per-facet kernel counts that differ** (variable face orders — hp settings). Then the FAD shape tensor mis-partitions functions across facets (wrong count per facet ⇒ shifted `countKernel` association); totals may still hit `count == nshape` only if the sum coincidentally matches, otherwise `DebugStop()` (:211-212 analogue in FAD tail). With uniform face orders the two expressions coincide → benign in all uniform-p runs, which is why tests pass. + +## Classification & severity +**Confirmed code inconsistency** (two branches computing the same partition differently — one must be wrong); practical severity *minor* because the triggering combination (curved × EHDivConstant × non-uniform face order × FAD) appears unexercised in-tree (no unit test combines them — Phase 7 gap). Mathematically it is a latent wrong-derivatives bug, not a stability subtlety. + +## What would resolve +Unit test: 3D HDivConstant element with mixed face orders + `fNeedsDeformedDirectionsFad=true`, compare FAD shape values against REAL branch / finite differences. Fix is one token (`[nedges]` → `[nedges + i]`) pending maintainer confirmation of intent. + +## Related +[[piola-transformations]] · [[hdiv-space]] · [[shape-functions]] · [[TPZCompElHDiv]] diff --git a/ai-analysis/wiki/findings/finding-hybridelasticity2d-missing-rhs-at-pin.md b/ai-analysis/wiki/findings/finding-hybridelasticity2d-missing-rhs-at-pin.md new file mode 100644 index 000000000..a832186d7 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-hybridelasticity2d-missing-rhs-at-pin.md @@ -0,0 +1,32 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: major +evidence-commit: 6ffd38b12 +tags: + - neopz + - material + - elasticity +--- + +# At pinned develop, TPZHybridElasticity2D::Contribute omits the body-force RHS + +## Repository evidence +`git diff develop HEAD -- Material/Elasticity/TPZHybridElasticity2D.cpp` [repo]: the working tree **adds** (i.e., develop @ 6ffd38b12 **lacks**) the entire forcing-function contribution to `ef` in `Contribute(...)` — evaluation of `fForcingFunction`/`fAnisotropicForcingFunction` at `datavec[0].x` and the `ef(2*in,col) += weight*(floc[0]*phi(in,0) - …fPreStress…)` loops. Commit history: fix landed as `2f6f7982d` "Added the RHS computation" (between develop tip and origin/develop `852a5116c`). + +## Reference evidence +Weak form of elasticity requires ∫ f·v on the RHS; omitting it makes any problem with nonzero body force silently wrong (solution of the homogeneous equation with the given BCs). No reference dispute — this is arithmetic completeness, not a modeling choice. + +## Assessment +- **Classification: confirmed implementation bug at the pinned commit — already fixed upstream** (origin/develop ≥ `2f6f7982d`). Not a live defect for users tracking origin/develop; a real defect for anyone pinned at/before `6ffd38b12`. +- Blast radius: only `TPZHybridElasticity2D` (hybrid 2D elasticity); problems with zero body force (e.g. iter_elast's homogeneous case if its ForceFunc ≡ 0) produce correct-looking results, which is exactly why it could slip in — no in-tree test exercises this material with nonzero f (→ Phase 7 gap: [[error-estimation-convergence]]). +- Also in the same delta: `TPZMatrix::MultiplyByScalar` made virtual (pzmatrix.h:190→193) and a **self-assignment guard** added to `TPZSYsmpMatrix::CopyFrom` (`from && from != this`, TPZSYSMPMatrix.h:42-45) — the guard implies a real self-copy path existed at the pin (candidate minor finding; verify caller in Phase 5). + +## What would resolve/validate +A regression test: hybrid elasticity 2D with manufactured solution having nonzero body force, asserting convergence — none exists at the pin. Recommend in Phase 7. + +## Related +[[material-system]] · [[flow-iter-elast]] · [[hybridization]] · [[error-estimation-convergence]] diff --git a/ai-analysis/wiki/findings/finding-local-test-crashes-workingtree.md b/ai-analysis/wiki/findings/finding-local-test-crashes-workingtree.md new file mode 100644 index 000000000..5fc837183 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-local-test-crashes-workingtree.md @@ -0,0 +1,33 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: insufficient-evidence +severity: major +evidence-commit: 6ffd38b12 +tags: + - neopz + - testing + - working-tree +--- + +# 5 of 40 unit-test suites crash in the local working-tree build (pin itself is CI-green) + +## Runtime evidence [run, 2026-07-02, ctest on `NeoPZ_divfree/build` (Release, BUILD_UNITTESTING=ON)] +`ctest -j3`: 35/40 pass in 16.6 s; **failures**: `TestCondensedHangingNodes` (SIGTRAP — reaches "Testing Hanging Nodes… test 0 EH1", then traps ⇒ consistent with a `DebugStop`), `TestReduced`, `TestErrorAnalysis`, `TestHangingNode`, `TestSBFem` (all Bus error). Full log: job tmp `ctest-run.log`. + +## Attribution analysis +- Stale-ABI hypothesis **eliminated**: all failing binaries timestamp Jun 30 16:29, same session as `libpz.dylib` (16:28) [repo ls]. +- Build identity: stamped `PZ_REVISION "852a5116c"`; built at 16:28, i.e. **before** HEAD commit `4de234fae` (16:47) — the build = 852a5116c + then-uncommitted working-tree edits (which became the MultiplyByScalar-virtual commit). +- **Upstream GitHub Actions "Run Unit Tests" is `success` on develop at both `6ffd38b` (the analysis pin) and `852a511`** [web: api.github.com runs list]. So the pinned develop is green in CI; the crashes belong to the *local working-tree state and/or this machine's configuration*. +- Suggestive pattern: 4 of 5 failing suites exercise condensation / hanging-node constraints / reduced spaces — the exact area refactored by the recent commits (`GroupElements`/`CondenseElements` split, virtual changes) — [inference, not proof]. + +## Classification +**Insufficient evidence / requires a rebuild to attribute** (options: (a) uncommitted-edit breakage now embodied in `4de234fae`, (b) machine/config-specific (Release+macOS+Accelerate vs CI images), (c) flaky memory bug surfacing locally). *Not* counted against the pinned develop, which is CI-green. Severity major because a current-branch user sees 12.5% of suites crashing. + +## What would resolve +Rebuild the build tree at `4de234fae` (or current HEAD) and rerun the 5 suites; if still crashing, bisect the 3-commit delta; run one suite under lldb to get the trap site. (Fresh builds were out of this engagement's authorized scope.) + +## Related +[[refinement-hanging-nodes]] · [[static-condensation]] · [[error-estimation-convergence]] · [[finding-hybridelasticity2d-missing-rhs-at-pin]] (same delta window) diff --git a/ai-analysis/wiki/findings/finding-matred-solver-mode-mislabel.md b/ai-analysis/wiki/findings/finding-matred-solver-mode-mislabel.md new file mode 100644 index 000000000..c1fa198ca --- /dev/null +++ b/ai-analysis/wiki/findings/finding-matred-solver-mode-mislabel.md @@ -0,0 +1,32 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: minor +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - solver + - benchmarking +--- + +# App repo: iter_elast benchmarks elasticity with the Darcy-shaped preconditioner (mode mislabel with measurable effect) + +## Repository evidence [agent trace, spot-checkable] +- `targets/iter_elast.cpp:287` passes `TPZMatRedSolver::EDarcyH1Hybrid` for a 2D elasticity problem; `EElasticityH1Hybrid` exists (`divfree/TPZMatRedSolver.h:15`). +- `fProblemOrigin` is consulted in 4 places (`divfree/TPZMatRedSolver.cpp:102,125,130,140`): the H1-hybrid **sign-flip branch treats both modes identically** (:102-109 — pure label there), but the **preconditioner block size differs**: Darcy `bsize = ord`, elasticity `bsize = 2*(ord+1)-3` (:123-134) feeding the `TPZBlockDiagonal` CG preconditioner (:148-151). `nstate` is set but never used (dead). +- 3D path allows only `EDarcyHDiv`; anything else `DebugStop()`s (:140-146). + +## Runtime relevance +[run @ 852a5116c(+)]: the observed mesh-independent 19-iteration CG counts were obtained with the Darcy blocking (bsize=1·ord at p=1). The benchmark's `t2` column *is* the quantity this mislabel perturbs; solution correctness is unaffected (any SPD preconditioner leaves the CG fixed point unchanged). + +## Assessment +Classification: **confirmed bug — application repo**, consequential for *measurements* (preconditioner-shape mismatch in a solver benchmark), not for correctness. Severity minor. Caveat: switching to the elastic `bsize=3` requires `bsize | nEqHigh` in `TPZBlockDiagonal::Initialize` — worth checking divisibility before the one-line fix. + +## What would resolve +Re-run the sweep with `EElasticityH1Hybrid` and compare iteration counts/`t2`. One-line change at `iter_elast.cpp:287`. + +## Related +[[flow-iter-elast]] · [[matrix-and-solvers]] · [[divfree-support-lib]] · [[finding-rusage-memory-units]] (same benchmark's memory column) diff --git a/ai-analysis/wiki/findings/finding-mesh-lifetime-ownership.md b/ai-analysis/wiki/findings/finding-mesh-lifetime-ownership.md new file mode 100644 index 000000000..e9f64c472 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-mesh-lifetime-ownership.md @@ -0,0 +1,34 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: major +evidence-commit: 6ffd38b12 +tags: + - neopz + - cpp + - ownership +--- + +# Mesh lifetime: asymmetric dangling protection gmesh↔cmesh; raw-owner copy hazards + +## Repository evidence (verified first-hand) +- `TPZCompMesh::~TPZCompMesh` (`Mesh/pzcmesh.cpp:178-187`) clears the geometric mesh's back-pointer if it points to `this` (`ref->ResetReference()`). +- `TPZGeoMesh::~TPZGeoMesh` (`Mesh/pzgmesh.cpp:97-103`) only runs `CleanUp()` — it **never nulls a surviving TPZCompMesh's `fReference`**, leaving the cmesh (and its whole `TPZGeoEl*` reference graph) dangling if the gmesh dies first. +- The co-ownership escape hatch exists but is opt-in and self-cancelling: `TPZCompMesh::SetReference(TPZGeoMesh*)` explicitly drops the owning `fGMesh` autopointer (`pzcmesh.h:772-773`) [agent, consistent with the dual-member design verified at pzcmesh.h:49-54]. +- Ownership facts (verified/agent): gmesh deletes its `TPZGeoEl*`s (`pzgmesh.cpp:106-123`); cmesh deletes elements in a multi-pass dynamic_cast order (submesh→condensed→groups→interfaces→rest) *and* deletes materials (`pzcmesh.cpp:189-257`) — materials are mesh-owned raw pointers. +- Related copy hazard: `TPZAnalysis` owns raw `fSolver` (deleted in CleanUp) but declares no copy/move control ⇒ implicit copy double-deletes [agent: TPZAnalysis.h:73,111; TPZAnalysis.cpp:262-264]; contrast `fStructMatrix` (already `TPZAutoPointer`). + +## Why it matters +Destruction order and no-copy rules are enforced only by convention. Downstream code (incl. divfreebubbles drivers, which routinely `new TPZGeoMesh` and hand raw pointers around, sometimes never deleting the analysis) relies on stack discipline to avoid UB. The multi-pass CleanUp shows real aggregation complexity handled manually — workable, but fragile against new element wrapper types. + +## Classification +**Confirmed hazardous pattern (accidental)** — no observed crash traced to it in this engagement, but the asymmetry is objective and the double-delete path is reachable by a one-line user mistake. + +## Suggested improvement / risk +(1) `~TPZGeoMesh` nulls the peer like the cmesh side already does — 3 lines, low risk. (2) Delete `TPZAnalysis` copy ops — trivial. (3) Longer term: prefer the autopointer `SetReference` overload / migrate unique ownership to `unique_ptr` gradually (963 raw `new TPZ*` sites, 0 unique_ptr today [agent counts]). + +## Related +[[TPZGeoMesh]] · [[TPZCompMesh]] · [[TPZAnalysis]] · [[TPZAutoPointer]] · CPP_TECHNICAL_REVIEW §2-H3/§3-M2/M3 diff --git a/ai-analysis/wiki/findings/finding-mhm-target-uncompilable.md b/ai-analysis/wiki/findings/finding-mhm-target-uncompilable.md new file mode 100644 index 000000000..5ae3b8224 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-mhm-target-uncompilable.md @@ -0,0 +1,31 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: minor +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - application + - build +--- + +# App repo: MHM_HDivConstant target no longer compiles (enum + constructor removed at HEAD) + +## Repository evidence [agent trace + first-hand grep] +- `targets/CMakeLists.txt:7-8` still registers `MHM_HDivConstant` [agent]. +- `targets/main_MHM_HDivConstant.cpp:184` (live, compiled branch inside a runtime `if`) constructs `TPZMatRedSolver(*Analysis, matBCAll, TPZMatRedSolver::EMHMSparse)`. +- `divfree/TPZMatRedSolver.h` at HEAD `fbe9696` has neither `EMHMSparse` (enum now `ProblemOrigin{EDarcyHDiv,EElasticityHDiv,EDarcyH1Hybrid,EElasticityH1Hybrid}` — verified first-hand :15) nor any 3-argument constructor (only default + `(TPZLinearAnalysis&, ProblemOrigin)`, .h:17-19) [agent]. +- Enum history (`git log -L`): `EDefault/ESparse` (ccd781c) → +`EMHMSparse` (6c74e3b) → replaced entirely at HEAD `fbe9696` ("Extending the functionality of the iterative solver to the 2d elastic equations") [agent]. +- The existing binary predates the change (Mar 27 vs solver rework); other registered targets remain valid (iter_elast, dupl_connects2 use the 2-arg ctor; others only include the header) [agent]. + +## Assessment +**Confirmed bug — application repo build drift** (a registered target that cannot build at HEAD). Severity minor per target, but it is the third independent instance of the same systemic theme (with [[finding-voronoi-null-ganalytic]] and the stale README): **no CI/compile gate on the app repo**, so drivers rot silently as the shared `divfree/` library evolves. Feeds the Phase 7 recommendation: a build-all-targets CI job (mirroring NeoPZ's own `compile_externalprojects.yml` pattern) would catch all three classes of drift. + +## What would resolve +`cmake --build` of the target (out of authorized scope) or user confirmation; fix = port the call to the 2-arg ctor with an appropriate mode or gate the ESemi branch out. + +## Related +[[flow-mhm-hdivconstant]] · [[divfree-support-lib]] · [[finding-voronoi-null-ganalytic]] diff --git a/ai-analysis/wiki/findings/finding-rusage-memory-units.md b/ai-analysis/wiki/findings/finding-rusage-memory-units.md new file mode 100644 index 000000000..320d136c0 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-rusage-memory-units.md @@ -0,0 +1,30 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: minor +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - application + - benchmarking +--- + +# App repo: peak-memory reporting is platform-dependent (bytes vs KB), distorting benchmark tables 1024× on macOS + +## Repository evidence +`divfreebubbles/targets/iter_elast.cpp:44-50` [repo]: `getPeakMemoryMB()` returns `usage.ru_maxrss / 1024.0` with comment "ru_maxrss is in KB on Linux". Same helper pattern in dupl_connects. Values land in the last column of `results_*_memory_time.txt` and in stdout as "Memory usage: … MB". + +## Runtime evidence +[run @ 852a5116c(+), 2026-07-02]: on this Mac, idiv=50 prints "Memory usage: 296304 MB" (≈289 real MB — i.e. the printed number is KiB); idiv=400 prints 1.01205e7 (≈9.65 GB real). The user's own `results_Elastic2D_memory_time.txt` (written Jul 2) shows the same magnitudes → their local benchmark data carries the same unit. + +## Reference evidence +POSIX leaves `ru_maxrss` units unspecified; Linux reports **kilobytes** (`getrusage(2)`), macOS/BSD reports **bytes** (`getrusage(2)` BSD man page). Well-known portability trap. + +## Assessment +Classification: **confirmed bug — application repo** (benchmark instrumentation, not NeoPZ). Severity minor for library correctness, but *material for research outputs*: memory columns produced on macOS overstate 1024×; cross-machine comparisons (commit "adjusting target to get the peak memory"/"run in dell" suggests mixed Linux/Mac usage) are inconsistent. Fix: `#ifdef __APPLE__ /1024/1024 else /1024`. + +## Related +[[flow-iter-elast]] · [[flow-dupl-connects]] diff --git a/ai-analysis/wiki/findings/finding-thread-shared-materials.md b/ai-analysis/wiki/findings/finding-thread-shared-materials.md new file mode 100644 index 000000000..3f8a2c795 --- /dev/null +++ b/ai-analysis/wiki/findings/finding-thread-shared-materials.md @@ -0,0 +1,31 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: possible mathematical risk +severity: major +evidence-commit: 6ffd38b12 +tags: + - neopz + - cpp + - thread-safety + - assembly +--- + +# Parallel assembly calls non-const Contribute on shared material objects — statelessness is an unenforced convention + +## Repository evidence +- One material instance per id, shared by all elements/threads (`Mesh/pzcmesh.h:65` `std::map`) [verified]. +- `Contribute(const TPZMaterialDataT&, REAL, ek, ef)` is **not const-qualified** — data is const, `this` is mutable (`Material/TPZMatSingleSpace.h:112-114`, verified first-hand). +- Both parallel strategies invoke it concurrently: OR producer/consumer (`pzstrmatrixor.cpp:624`; global scatter single-threaded), OT graph-coloring (`pzstrmatrixot.cpp:732`; concurrent non-atomic scatter, safe by coloring) via `pzinterpolationspace.cpp:522` [agent, structure verified in Phase 4/5 sweeps]. +- Mitigations present: `TPZMaterialData` scratch is a per-call stack local (`pzinterpolationspace.cpp:480`) [agent]; parallel==serial equality is unit-tested for sample materials (`TestMultithreading` [agent Phase 1]). + +## The risk (and why it's "possible mathematical risk", not confirmed bug) +Nothing observed misbehaves today; the invariant "materials keep no mutable state inside Contribute" evidently holds for the tested materials. But the invariant is **not compiler-enforced**: any material caching a member (e.g., a lazily-computed constitutive matrix, a stored last-point, `TPZMatWithMem` interactions) becomes a silent data race with non-deterministic assembly — the worst failure mode for a numerics library (wrong numbers, not crashes). Forcing functions (`std::function` members) invoked inside Contribute are likewise shared. + +## What would resolve +Const-qualify `Contribute/ContributeBC/Solution` across the hierarchy (compiler then proves statelessness or flags violations; `mutable`+synchronized escape hatch for legitimate caches); or document + add a TSAN CI job exercising OR/OT on all shipped materials. Expert/maintainer input useful for `TPZMatWithMem` (per-point memory is *by design* mutable — how is it synchronized during parallel assembly? → open question). + +## Related +[[assembly]] · [[structural-matrices]] · [[material-system]] · [[finding-global-state-cluster]] · CPP_TECHNICAL_REVIEW §2-H4 diff --git a/ai-analysis/wiki/findings/finding-voronoi-null-ganalytic.md b/ai-analysis/wiki/findings/finding-voronoi-null-ganalytic.md new file mode 100644 index 000000000..17a709b8b --- /dev/null +++ b/ai-analysis/wiki/findings/finding-voronoi-null-ganalytic.md @@ -0,0 +1,27 @@ +--- +type: finding +status: reviewed +updated: 2026-07-02 +confidence: high +classification: confirmed-bug +severity: minor +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - application +--- + +# App repo: voronoi_mixed_elas dereferences null gAnalytic on its active path + +## Repository evidence +`divfreebubbles/targets/voronoi_mixed_elas.cpp` [repo]: `:84` `TPZAnalyticSolution *gAnalytic = 0;`; the only assignments (`gAnalytic = elas;`) are commented out (`:93`, `:103`); `:143` executes `an.SetExact(gAnalytic->ExactSolution());` → null dereference when the target runs. The existing binary (built Mar 27) predates or was built from a different source state. + +## Assessment +- **Classification: confirmed bug — application repo, not NeoPZ.** Severity minor (research driver; crashes at startup of the error-setup stage, no silent wrong numbers). +- Value for the NeoPZ assessment: (a) evidence that app drivers drift out of compilable/runnable state without CI (`BUILD_TESTS=OFF`, no app CI) — same theme as the `EMHMSparse` drift (OQ6); (b) API-design observation: `TPZAnalysis::SetExact` taking a callable forces the *caller* to null-check the provider — a fluent guard (accepting a provider object) would fail softer → Phase 5 note. + +## What would resolve +Compile+run the target (out of scope: fresh builds not authorized) or user confirmation. Fix is app-side: uncomment the intended `gAnalytic = elas` (or guard the SetExact call). + +## Related +[[divfree-support-lib]] · [[TPZAnalysis]] · [[flow-mhm-hdivconstant]] (drift sibling) diff --git a/ai-analysis/wiki/flows/flow-dfreebubbles-1el.md b/ai-analysis/wiki/flows/flow-dfreebubbles-1el.md new file mode 100644 index 000000000..9ecc08d75 --- /dev/null +++ b/ai-analysis/wiki/flows/flow-dfreebubbles-1el.md @@ -0,0 +1,39 @@ +--- +type: flow +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - hdiv + - vtk +--- + +# Flow: dFreeBubbles1el — minimal manual mixed H(div) with error + VTK + +Driver: `divfreebubbles/targets/main_1element.cpp` (read :100-405 [repo]; 980 lines incl. many commented variants). Binary rebuilt Jul 2 — actively used. + +## Shallow trace +1. **Problem**: Darcy/Laplace on a single-element 2D domain (well-type physical groups), mixed H(div)×L² formulation; the closest surviving driver to the repo's original "div-free bubbles" intent (H1 and DFB comparison paths present but commented, :194-275). +2. **Start**: straight-line `main` (:115). +3. **Mesh**: `TPZGmshReader` with explicit physical-name→matid map (`stringtoint[dim]["Surface"]=1` etc.), reads `MESHDIR + "1element.msh"`; immediately dumps `gmesh.vtk` via `TPZVTKGeoMesh::PrintGMeshVTK` (:124-145) → [[mesh-io-generators]], [[TPZGeoMesh]]. +4. **Geometric elements**: one 2D quad element + 1D boundary lines + points (from the .msh physical groups). +5. **Computational meshes — the manual pattern** (pre-ApproxCreator style): + - `FluxCMesh`: `TPZNullMaterial` per matid (space placeholder — physics lives only in the multiphysics mesh), `cmesh->ApproxSpace().SetAllCreateFunctionsHDiv(dim)`, `SetDefaultOrder(pOrder=4)`, `AutoBuild()` (:307-332) — **layer-1 factory used directly** ([[approx-space-creators]]). + - `PressureCMesh` (analogous, L²/discontinuous [not yet read — Phase 4]). + - `MultiphysicCMesh`: combines {flux, pressure} into `TPZMultiphysicsCompMesh` with real material (`TPZMixedDarcyFlow`-family; body TBC) (:167-172). + - The commented `FluxCMeshDFB` shows the *fully manual* kernel-H(div) construction: per-element `new TPZCompElKernelHDiv(*cmesh,gel)` + neighbor walking (`TPZGeoElSide::Neighbour()`) to instantiate wrap/point elements (:335-405) — direct evidence of the element-level API and of [[TPZCompElHDiv]] kernel variants. +6. **Space selection**: explicit `SetAllCreateFunctionsHDiv` (+ commented HDivConstant/HDivKernel alternates) — family switching at factory level. +7. **Materials**: `TPZNullMaterial` in atomic meshes; physical material in multiphysics mesh (body Phase 4). +8-9. **Assembly/solve**: `TPZLinearAnalysis an(cmesh); SolveProblemDirect(an,cmesh)` (helper wraps struct-matrix + `ELDLt` [agent]) (:182-183). +10. **Errors**: `an.SetExact(exactSolError2,2); util.ComputeError(an, "postprocessHdiv.txt")` (:189-191) → [[error-estimation-convergence]] — this slice exercises the error leg. +11. **VTK**: `PrintResultsMultiphysic(dim, meshvector, an, cmesh)` → multiphysics VTK output (helper wraps `TPZVTKGenerator` [agent; verify Phase 4]) (:186) → [[vtk-output]] — exercises the VTK leg. +12. **Central classes**: `TPZGmshReader`, `TPZNullMaterial`, `TPZCreateApproximationSpace` (via `ApproxSpace()`), `TPZMultiphysicsCompMesh`, `TPZCompElKernelHDiv` (commented path), `TPZKernelHdivUtils`. +13. **Research before judging**: how `TPZBuildMultiphysicsMesh` wires atomic→multiphysics connects; what `exactSolError2` actually is; wrap/point element roles in kernel-HDiv constructions. + +## Quirks noted (app-side) +- `exactSol` computes a 4-well log-potential then **overwrites with `u=x, ∇u=(1,0)`** (:288-293) — dead code above live code inside one lambda; the effective exact solution is linear (space reproduces it exactly → expected ~machine-zero errors). +- Physics-free `TPZNullMaterial` carries `SetBigNumber(1e10)` (:316) — big-number penalty convention surfacing even in placeholder materials; understand `BigNumber`'s role in BC imposition (Phase 4, [[material-system]]). + +Related: [[mesh-io-generators]] · [[approx-space-creators]] · [[TPZCompElHDiv]] · [[error-estimation-convergence]] · [[vtk-output]] diff --git a/ai-analysis/wiki/flows/flow-dupl-connects.md b/ai-analysis/wiki/flows/flow-dupl-connects.md new file mode 100644 index 000000000..b8e27b217 --- /dev/null +++ b/ai-analysis/wiki/flows/flow-dupl-connects.md @@ -0,0 +1,30 @@ +--- +type: flow +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - hdiv + - darcy +--- + +# Flow: dupl_connects2 — semi-hybrid mixed H(div) Darcy benchmark + +Driver: `divfreebubbles/targets/dupl_connects.cpp` (main read :140-340 [repo]). Binary `build/targets/dupl_connects2` (Jun 30). + +## Shallow trace +1. **Problem**: mixed Darcy (flux×pressure) on unit square/cube, `HDivFamily::EHDivConstant`, **semi-hybridization** (`HybridizationType::ESemi`), benchmark of `TPZMatRedSolver(EDarcyHDiv)` vs direct; DIM from argv (default 3D, idivs {2,8,12,16,32}) (:155-214). +2-4. **Mesh**: same `CreateGeoMesh` → `TPZGeoMeshTools::CreateGeoMeshOnGrid` pattern as iter_elast; quads (2D) / hexes (3D). +5-6. **Spaces**: **library-side** `TPZHDivApproxCreator hdivCreator(gmesh)`: `HdivFamily()=EHDivConstant`, `SetProbType(EDarcy)`, `IsRigidBodySpaces()=false`, `SetExtraInternalOrder(0)`, `SetShouldCondense(true)`, `SetHybridType(ESemi)` → `CreateApproximationSpace()` → `TPZMultiphysicsCompMesh` (:206-237). Contrast with [[flow-iter-elast]]: creator + condensation handled fully in-library here → cleanest Phase 4 window into `Pre/TPZHDivApproxCreator.cpp` and the duplicated-connects machinery behind ESemi ([[hybridization]]). +7. **Material**: `TPZMixedDarcyFlow(EDomain, DIM)`, constant permeability 1, exact + forcing lambdas (order 4); Dirichlet BC type 0 from exact (:223-234) → [[material-system]], [[mixed-methods]]. +8-9. **Assembly/solve**: identical benchmark switch as iter_elast: `TPZMatRedSolver(an, EDarcyHDiv).Solve()` vs `TPZSSpStructMatrix`/`Mumps` + ELDLt (:266-323). +10-11. **Outputs**: equation counts to `results_Harmonic2D.txt`, time/memory to `results_memory_time.txt`; error & VTK legs commented out (same pattern as iter_elast). +12. **Central classes**: `TPZHDivApproxCreator`, `TPZMixedDarcyFlow`, `TPZMultiphysicsCompMesh`, `TPZMatRedSolver`, `TPZSSpStructMatrix(Mumps)`. +13. **RESOLVED (Phase 4 trace)**: ESemi duplicates each interior facet connect into even=constant-flux + odd=higher-order pairs (`TPZCompElHDivDuplConnects`, ratio verified: even connect gets 1 shape function, odd gets nshape−1, `TPZCompElHDivDuplConnects.cpp:58-138`); `SemiHybridizeDuplConnects` rebinds only the even connect on the `sideOrient==−1` side to the wrap element (`TPZHDivApproxCreator.cpp:1239-1299`); multiplier submesh order 0; glue = shared connect + `TPZMultiphysicsInterfaceElement`/`TPZLagrangeMultiplierCS`. `EHDivConstant` (order-0 pressure) + per-facet constant-flux multipliers is what makes total condensation well-posed (cf. the singular-K00 guard `TPZHDivApproxCreator.cpp:85-89`). Full details: [[hybridization]]. + +## Quirks noted (app-side) +- The analytic pair is inconsistent as a manufactured solution: `exactSol` = 3D harmonic (`sin·sin·sinh`, Δu=0, and ≡0 on z=0 for 2D runs) yet `forcefunction` is nonzero (and uses `cosh(√2πx)` — x, not z) (:144-153). Harmless for the timing benchmark (error computation disabled), but any re-enabled error check would be meaningless. [hypothesis: copy-paste vestige] + +Related: [[hdiv-space]] · [[hybridization]] · [[static-condensation]] · [[mixed-methods]] · [[flow-iter-elast]] diff --git a/ai-analysis/wiki/flows/flow-iter-elast.md b/ai-analysis/wiki/flows/flow-iter-elast.md new file mode 100644 index 000000000..c57e6d6f2 --- /dev/null +++ b/ai-analysis/wiki/flows/flow-iter-elast.md @@ -0,0 +1,45 @@ +--- +type: flow +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - elasticity + - hybridization +--- + +# Flow: iter_elast — hybrid H1 elasticity benchmark (mandated slice) + +Driver: `divfreebubbles/targets/iter_elast.cpp` (read in full [repo]). Binary: `build/targets/iter_elast` (built Jun 30; runtime = installed NeoPZ @ `852a5116c` per install `pz_config.h` [run]). + +## Shallow trace (Phase 2 answers) +1. **Problem**: 2D linear elasticity on unit square, homogeneous analytic case (`TElasticity2DAnalytic`, E=1, ν=0), discretized with *hybridized-squared H1* spaces; purpose = benchmark iterative Schur-complement solving vs sparse direct (time/memory sweep over 50²…400² quad meshes at fixed p) (:166-337). +2. **Start**: `main` loops `idivs={50,…,400}` (:189-192). +3. **Mesh**: `CreateGeoMesh` → `TPZGeoMeshTools::CreateGeoMeshOnGrid(dim, {0,0,0},{1,1,1}, matIds, nDivs, EQuadrilateral, createBoundEls)` (:204-212, 417-466) → [[TPZGeoMesh]], [[mesh-io-generators]]. +4. **Geometric elements**: structured quads + boundary 1D elements, all `matIds` boundary→`EBoundary`, volume→`EDomain`. +5. **Computational mesh**: `TPZH1HybridApproxCreator hdivCreator(gmesh)` (app-side, [[divfree-support-lib]]) → `CreateApproximationSpace()` returns `TPZMultiphysicsCompMesh` (:218-229) → [[TPZCompMesh]]. +6. **Space selection**: `SetProbType(EElastic)`, `SetDefaultOrder(iorder)`, `SetExtraInternalOrder(2)`, `SetShouldCondense(false)`, `SetHybridType(EStandardSquared)` (:220-226) → [[approx-space-creators]], [[hybridization]]. Post-creation: `ComputeOrthogonalizingRestraints(*cmesh, geltogel, HybridData())`, `HybridizeLowOrderFluxes`, `GroupAndCondenseElements` (:231-233) → [[static-condensation]]. *(These three are app-side extensions over the develop-delta base `TPZH1ApproxCreator` — deep semantics = Phase 4 target.)* +7. **Materials**: `TPZHybridElasticity2D` (develop-delta file) on `EDomain` with forcing+exact from `TElasticity2DAnalytic`; single Dirichlet BC (type 0) on all boundaries via `CreateBC` + `SetForcingFunctionBC` (:470-494) → [[material-system]]. +8. **Assembly**: iterative path delegates entirely to `TPZMatRedSolver(an, EDarcyH1Hybrid).Solve(...)` (:287-289); direct path `TPZSSpStructMatrix>` (MKL) or `TPZSSpStructMatrixMumps` (32 threads) + `an.Assemble()` (:293-321) → [[structural-matrices]], [[assembly]]. +9. **Solve**: iterative = Schur/matrix-reduction inside `TPZMatRedSolver` ([[divfree-support-lib]]); direct = `TPZStepSolver::SetDirect(ELDLt)` + `an.Solve()` (:315-332) → [[matrix-and-solvers]], [[TPZAnalysis]]. +10. **Results/errors**: only equation counts + wall-times + peak RSS, appended to `results_Elastic2D_memory_time.txt`; `PostProcessError` block **commented out** (:391-410). +11. **VTK**: `TPZVTKGenerator` block **commented out** (:361-383) → no visualization leg in this slice. +12. **Central classes**: `TPZH1HybridApproxCreator` → `TPZH1ApproxCreator` (delta), `TPZHybridElasticity2D` (delta), `TPZMultiphysicsCompMesh`, `TPZLinearAnalysis` (`RenumType::ENone`!), `TPZMatRedSolver`, `TPZSSpStructMatrix(Mumps)`, `TPZStructMatrixOR`. +13. **Partially RESOLVED (Phase 4)**: `EStandardSquared` = double hybridization, fully traced — see [[hybridization]] (second interface/Lagrange layer; only 2nd-level skeleton global; atomic meshes = skeleton-flux HDivStandard + broken-H1 volume(+wraps+2nd-level primal skeleton); elastic multipliers {−1,−1,−1,1} with right interface reset to +1). Space construction matches [[avancini-2025-double-hybrid-elasticity]] structurally (H1-primal variant). Solver-mode question RESOLVED: `EDarcyH1Hybrid` vs `EElasticityH1Hybrid` share the sign-flip branch but select different preconditioner block sizes (`ord` vs `2(ord+1)−3`) — iter_elast's choice is a consequential mislabel for the benchmark ([[finding-matred-solver-mode-mislabel]]). Reduction anatomy fully traced (K00 = Lagrange-level-1 connects, Cholesky via Pardiso/MUMPS; matrix-free Schur CG with block-diagonal ELU preconditioner, 500 iter cap / 1e-10) — see [[matrix-and-solvers]] and `ALGORITHM_NOTES.md` §5. Still open: "orthogonalizing restraints" semantics (app-side `ComputeOrthogonalizingRestraints` — expert/maintainer question). + +## Runtime trace [run @ 852a5116c(+), 2026-07-02, pOrder=1 iterative sweep from scratch cwd] +- Sweep completed exit 0; per-idiv console shows the reduction anatomy: e.g. idiv=50: `Number of equations = 168200` (full) → `condensed = 19600`; `NUMBER OF EQUATIONS: Full problem = 19600, High Order Flux = 4900, Linear Flux = 14700`; `Time Assembling SparseMatRed 78 ms`; `Assembling block diagonal 1 ms`; `Decomposing K00... 39 ms`; CG iteration log with residuals ~0.27→9e-11. +- **CG iterations = 19 at idiv=50 AND idiv=400** (residual ~9e-11 both) — mesh-size-independent iteration count; contraction ≈ 0.3/iter. Strong evidence the K00-block reduction acts as an (apparently) spectrally robust preconditioner for this problem family. (Deep mechanics: pending `TPZMatRedSolver` trace.) +- Output-table semantics (matches `results_Elastic2D_memory_time.txt` row `iterative 1 50 78 75 296304`): t1 = SparseMatRed assembly ms; t2 ≈ K00 decomposition + CG ms; third value = `getPeakMemoryMB()`. +- **Memory-unit bug (app-side)**: `getPeakMemoryMB` divides `ru_maxrss` by 1024 with a comment "ru_maxrss is in KB on Linux" (iter_elast.cpp:44-50) — on macOS `ru_maxrss` is in **bytes**, so values printed as "MB" are actually KiB on Mac (observed "Memory usage: 296304 MB" ≈ 289 true MB at 50²; 1.01205e7 "MB" ≈ 9.65 GB at 400²). Cross-platform 1024× distortion in published benchmark tables if mixed. → [[finding-rusage-memory-units]]. +- PZ_LOG active in installed build: run creates a `LOG/` dir (46 log files) in cwd; config read from `neopz_install/pz/include/Util/log4cxx.cfg`. +- `results_Elastic2D.txt` rows are written without newline separators (cosmetic app bug). + +## Quirks noted (app-side, shallow) +- File-scope `std::ofstream` globals open `results_*.txt` in CWD at static-init (two truncate; :53-55) — **never run from `build/targets/`**. +- The `exactSol` lambda fed to `an.SetExact` is a 3D scalar sinh-harmonic (zero at z=0), unrelated to the elasticity exact solution; harmless while error block is commented, but a trap if re-enabled (:88-154 vs :275) — [hypothesis: leftover from a Darcy variant of the benchmark]. +- `hdivfamily` variable declared but unused by the H1 creator (:175). + +Related: [[hybridization]] · [[static-condensation]] · [[approx-space-creators]] · [[divfree-support-lib]] · [[flow-dupl-connects]] diff --git a/ai-analysis/wiki/flows/flow-mhm-hdivconstant.md b/ai-analysis/wiki/flows/flow-mhm-hdivconstant.md new file mode 100644 index 000000000..7c9d647de --- /dev/null +++ b/ai-analysis/wiki/flows/flow-mhm-hdivconstant.md @@ -0,0 +1,32 @@ +--- +type: flow +status: draft +updated: 2026-07-02 +confidence: medium +evidence-commit: 6ffd38b12 +tags: + - divfreebubbles + - mhm + - hdiv +--- + +# Flow: MHM_HDivConstant — multiscale hybrid-mixed Darcy on polygonal partition + +Driver: `divfreebubbles/targets/main_MHM_HDivConstant.cpp` (read :60-240 [repo]). Binary from **Mar 27** — older than current sources (see drift note below). + +## Shallow trace +1. **Problem**: Laplace/Darcy (`TLaplaceExample1::EX` exact) on a domain partitioned into polygonal subdomains (UNSW quadtree file), solved with [[mhm]] using `EHDivConstant` local spaces and **rigid-body spaces on** (needed for total condensation of subdomain interiors). +2. **Start**: `RunMHM(xdiv,pOrder)` (:67). +3-4. **Mesh**: `ReadUNSWQuadtreeMesh("polygon00.txt", elpartition, scalingcenterindices)` (app-side `Common.cpp`) → `TPZAutoPointer`; polygons triangulated via `mhm_gcreator.CreateTriangleElements(gmesh, matmap, partition, scalingcenters)` — triangles fanned around scaling centers, element-partition vector tracks coarse cell ids (:92-123) → [[TPZGeoMesh]]. +5-6. **Spaces**: `TPZMHMHDivApproxCreator mhm_ccreator(mhm_gcreator, gmesh)` (app-side, [[divfree-support-lib]]): `HdivFamily()=EHDivConstant`, `ProbType()=EDarcy`, `IsRigidBodySpaces()=true`, `SetShouldCondense(true)`, `HybridType()=ENone`, `SetPOrderSkeleton(pOrder)` → `BuildMultiphysicsCMesh()`; then **`PutinSubstructures(*multiCmesh)` + `CondenseElements(*multiCmesh)`** — coarse cells become `TPZSubCompMesh` substructures, interiors condensed (:135-164) → [[mhm]], [[static-condensation]]. +7. **Materials**: inserted via `mhm_ccreator.InsertMaterialObjects(LaplaceExact)` (analytic-driven) (:146). +8-9. **Assembly/solve**: `TPZLinearAnalysis` + `TPZSSpStructMatrix` (10 threads) + `TPZStepSolver ELDLt`; the `ESemi` branch would use `TPZMatRedSolver(...,EMHMSparse)` but is dead code here (:166-201). +10-11. **Outputs**: equation/element counts to stdout; **always-on debug block** (`if(1)`) writes `mphysics2.txt` + `cmesh_multi.vtk` (geo-mesh-of-cmesh via `TPZVTKGeoMesh::PrintCMeshVTK`) into CWD (:149-162) → [[vtk-output]]. No error computation active. +12. **Central classes**: `TPZMHMGeoMeshCreator`, `TPZMHMHDivApproxCreator`, `TPZSubCompMesh`, `TPZVTKGeoMesh`, `TPZSSpStructMatrix`. +13. **Research before judging**: MHM skeleton/subdomain construction correctness; rigid-body-space role in subdomain invertibility; relation of app-side creators to the in-library `Pre/TPZMHMHDivApproxCreator` (same name, two repos? verify which is used — include path decides) → Phase 4. + +## Drift finding — CONFIRMED (Phase 4) +Resolved via enum git history (`git log -L`): `EDefault/ESparse/EMHMSparse` were all removed at HEAD `fbe9696` (the commit that introduced `ProblemOrigin` + the elasticity mode); `main_MHM_HDivConstant.cpp:184` additionally uses a 3-arg constructor that no longer exists (`TPZMatRedSolver.h:17-19` has only default + 2-arg). Target still registered in `targets/CMakeLists.txt:7-8` ⇒ **does not compile at HEAD**; binary is a Mar 27 relic. → [[finding-mhm-target-uncompilable]]. +Also noted: `new TPZLinearAnalysis(...)` never deleted (:168) [app-side hygiene]. + +Related: [[mhm]] · [[static-condensation]] · [[hdiv-space]] · [[divfree-support-lib]] · [[vtk-output]] diff --git a/ai-analysis/wiki/flows/flow-unit-test-hdiv-creator.md b/ai-analysis/wiki/flows/flow-unit-test-hdiv-creator.md new file mode 100644 index 000000000..ef925f6a9 --- /dev/null +++ b/ai-analysis/wiki/flows/flow-unit-test-hdiv-creator.md @@ -0,0 +1,34 @@ +--- +type: flow +status: draft +updated: 2026-07-02 +confidence: high +evidence-commit: 6ffd38b12 +tags: + - neopz + - testing + - hdiv + - de-rham +--- + +# Flow: NeoPZ unit-test slice — TestHDivApproxSpaceCreator + TestDeRham + +In-library validation flows (what NeoPZ itself proves about its spaces). Files: `UnitTest_PZ/TestHDivApproxSpaceCreator/TestHDivApproxSpaceCreator.cpp` (1081 lines) and `UnitTest_PZ/TestDeRham/TestDeRham.cpp` (721 lines) [repo]. + +## TestHDivApproxSpaceCreator — "linear solution representation" grid +- One `TEST_CASE("HDiv Approx Space Creator","[hdiv_linear_solution_representation]")` (:152) fanning a nested `GENERATE` grid [repo :152-216]: + `HDivFamily {EHDivConstant, EHDivStandard, EHDivOptimized}` × `ProblemType {EDarcy, EElastic}` × `MMeshType {Quad, Tri, Tetra, Hexa}` × `pOrder {1,2}` × `extraporder {0,1}` × `HybridizationType {ENone, EStandard, ESemi}` × `isRBSpaces {0,1}` × `isCondensed {0,1}` × `isRef {0,1}` (+ an MHM variant instantiating `TPZMHMHDivApproxCreator` — **the library has its own MHM creator**, cf. same-named app-side class, :519-524). +- Per combination `TestHdivApproxSpaceCreator(...)` (:451): builds gmesh → creator → multiphysics cmesh → solve → checks: + `CheckIntegralOverDomain` (flux/pressure integrals vs analytic values), `CheckError` (errors ≈ expected for a linear exact solution), `TestKnownSol` (constant-solution reproduction), `CheckNEqCondensedProb` (equation counts after condensation), `PostProcessVTK` (:56-72 decls). +- **What it proves**: the creator pipeline produces spaces that exactly represent linear/constant solutions across families × hybridizations × condensation × refinement, with correct condensed equation counts. **What it does not prove**: convergence *rates*, curved geometry, 3D prism/pyramid, stability constants → [[error-estimation-convergence]], Phase 7. + +## TestDeRham — basis-level exact-sequence checks +- `TEMPLATE_TEST_CASE("Dimension Compatibility","[derham_tests]", dim=2|3)` + `"Inclusion"`; LAPACK-gated (SVD) (:75-120). +- `CheckRankKerDim(k)`: builds mass-like matrices of `op(φ_i)` and verifies `rank(M_left) = ker(M_right)` for pairs H1→HCurl, HCurl→L2 (2D) / HCurl→HDiv (3D), HDiv→L2, HDivConst→L2; `CheckInclusion` verifies range(op(left)) ⊆ span(right) via block-matrix rank identity `rank([A B; C D]) = rank(D)` (:49-73 header comments quoted). +- Dedicated pair materials (`TPZMatDeRhamH1HCurl` etc., 7 helper materials in dir listing [repo]) assemble the mixed Gram matrices. +- **What it proves**: dimension-level exactness/inclusion of the discrete sequence on the tested meshes/orders (k=1..3). **What it does not prove**: commuting-diagram/interpolation properties, exactness on curved or distorted elements → [[de-rham-complex]]. + +## Flow anatomy (both) +gmesh (`TPZGeoMeshTools`) → atomic cmeshes → `TPZMultiphysicsCompMesh` / basis matrices → assembly (`TPZFStructMatrix`/creators) → LAPACK SVD or solve → Catch2 `REQUIRE(... Approx ...)`. Central classes: `TPZHDivApproxCreator`, `TPZMHMHDivApproxCreator` (lib), `TPZLinearAnalysis`, `TPZFMatrix::SVD`. + +Related: [[de-rham-complex]] · [[hdiv-space]] · [[approx-space-creators]] · [[mixed-methods]] · [[flow-dupl-connects]] diff --git a/ai-analysis/wiki/index.md b/ai-analysis/wiki/index.md new file mode 100644 index 000000000..574e0e08f --- /dev/null +++ b/ai-analysis/wiki/index.md @@ -0,0 +1,115 @@ +--- +type: index +status: reviewed +updated: 2026-07-06 +tags: + - neopz + - index +--- + +# Wiki index + +Analyzed commit: `develop @ 6ffd38b12`. Evidence rules and chronology: [[log]] (`log.md`). +Top-level deliverables live one directory up (`ai-analysis/*.md`); this wiki is the working knowledge graph feeding them. +**Session 2 (2026-07-06)** rebalanced the knowledge base toward the library itself: new deep-dive pages for the non-HDiv element families, TPZConnect, multiphysics composition, condensation/groups/submeshes, and the geometry/refinement/maps layer, plus a survey of the five most recently active downstream applications (`apps/`). + +## Concepts (`concepts/`) +- [[h1-space]] — continuous conforming spaces; where NeoPZ realizes them. → shape-functions, hybridization +- [[hdiv-space]] — normal-trace-conforming vector spaces; NeoPZ families (Standard/Constant/Kernel). → TPZCompElHDiv, mixed-methods +- [[hcurl-space]] — tangential-trace-conforming spaces; "NoGrads" variant. → de-rham-complex +- [[de-rham-complex]] — exact-sequence property; NeoPZ's own SVD-based exactness tests. → TestDeRham +- [[mixed-methods]] — saddle-point two-field formulations; multiphysics machinery. → approx-space-creators +- [[hybridization]] — Lagrange-multiplier continuity; ENone/EStandard/EStandardSquared/ESemi taxonomy. → flow-iter-elast +- [[static-condensation]] — interior-DOF elimination; condensed elements/groups/submeshes; rigid-body spaces. +- [[mhm]] — multiscale hybrid-mixed method; controllers + creators; substructures. → flow-mhm-hdivconstant +- [[sbfem]] — scaled-boundary FEM sub-framework (breadth item). +- [[refinement-hanging-nodes]] — runtime refinement patterns (.rpt), connect dependency constraints. +- [[hp-adaptivity]] — per-connect orders + h-refinement; in-tree mechanisms vs downstream drivers. +- [[geometric-mappings]] — master→physical maps, blend + exact curved maps; axes convention. +- [[piola-transformations]] — vector-basis mapping requirement; NeoPZ's realization = key open question. +- [[quadrature]] — per-topology rules, long-double internals, order sufficiency questions. +- [[assembly]] — element→global pipeline across StrMatrix/materials/connects. +- [[error-estimation-convergence]] — SetExact/PostProcessError path; reproduction- vs rate-testing; downstream estimator suite. +- [[vtk-output]] — legacy .vtk writer model, subdivision of high-order fields. +- [[discontinuous-l2-dg]] — *(Session 2)* L² spaces (TPZCompElDisc vs broken-H1), interface elements, the compositional DG path. + +## Code (`code/`) +- [[TPZGeoMesh]] — geometric mesh container, element/side/neighbor model, refinement genealogy. +- [[TPZCompMesh]] — computational mesh: connects, materials, solution block; Mesh↔Pre coupling. +- [[material-system]] — TPZMaterial/TPZMatBase variadic mixin design; physics dirs; needrefactor legacy layer. +- [[approx-space-creators]] — 2-layer space creation (factory + problem-level creators); hybridization data. (Correction C1 lives here.) +- [[TPZCompElHDiv]] — H(div)/H(curl)/kernel element families and conformity mechanics. +- [[shape-functions]] — static per-topology shape engine; families; hierarchical bases. +- [[topology-module]] — master-element sides, transforms, permutations. +- [[structural-matrices]] — assembly strategies, parallel schemes, equation filter. +- [[matrix-and-solvers]] — storage zoo + direct/iterative/eigen solvers; decomposition state. +- [[TPZAnalysis]] — solve orchestrator; renumbering; preconditioner factory. +- [[post-processing-vtk]] — graph-mesh legacy + TPZVTKGenerator (NGSolve-derived). +- [[persistence]] — TPZSavable/ClassId/chunk translators; thin test coverage. +- [[mesh-io-generators]] — gmsh reader (in-tree), grid generators, analytic solutions. +- [[TPZAutoPointer]] — house ref-counted pointer; dual raw/smart ownership conventions. +- [[divfree-support-lib]] — ../divfreebubbles application-side extensions (creators, Schur solvers, custom elements). + +Session-2 deep-dive pages: +- [[element-families]] — H1 / H(curl) / discontinuous / interface elements; family enums resolved; dispatch table inventory. +- [[TPZConnect]] — DOF anatomy, dependency (restraint) machinery, Lagrange levels, SaddlePermute, renumbering strata. +- [[multiphysics-composition]] — TPZMultiphysicsCompMesh mechanics: AddElements/AddConnects, datavec stacking, solution transfer. +- [[condensation-groups-submeshes]] — TPZElementGroup / TPZCondensedCompEl / TPZSubCompMesh; ordering constraints; rigid-body modes. +- [[geometry-refinement-maps]] — TPZGeoEl hierarchy, uniform vs pattern refinement, .rpt format, genealogy→restraints bridge, special/blend maps, TPZGeoElMapped. + +## Apps (`apps/`) — Session-2 downstream usage survey +- [[apps-overview]] — method, comparison table, nine cross-cutting observations. +- [[app-iterative-saddle-point]] — Uzawa/augmented-Lagrangian saddle-point iteration; low-level Matrix/Pardiso usage. +- [[app-gfem]] — GFEM fracture enrichment via TPZCompElH1 subclass; SBFem-derived singular modes. +- [[app-error-estimation]] — reconstruction-based estimators + closed hp-adaptive loops; quarter-point/SBFem/NACA geometry. +- [[app-wann]] — 3D/2D/1D coupled reservoir-wellbore Darcy; connect surgery; cylinder maps; directional refinement. +- [[app-mixed-elasticity]] — tensor-valued mixed elasticity, weak/strong symmetry, 3–7-field multiphysics, MHM controllers. + +## Flows (`flows/`) +- [[flow-iter-elast]] — mandated slice: 2D hybrid-squared H1 elasticity benchmark; MatRedSolver vs direct; exercises the develop-delta files. +- [[flow-dupl-connects]] — semi-hybrid mixed H(div) Darcy benchmark (`ESemi`, `EHDivConstant`), lib-side creator. +- [[flow-mhm-hdivconstant]] — MHM on polygonal partition; substructures + condensation; app-source drift finding (OQ6). +- [[flow-dfreebubbles-1el]] — minimal manual mixed H(div); the active error + VTK legs. +- [[flow-unit-test-hdiv-creator]] — in-library validation: creator grid test + De Rham rank/kernel tests. + +## Findings (`findings/`) +NeoPZ (library): +- [[finding-hybridelasticity2d-missing-rhs-at-pin]] — **major/confirmed**: body-force RHS absent from TPZHybridElasticity2D::Contribute at the pin (fixed upstream 2 commits later); no test would catch it. +- [[finding-hdivconstant-fad-index]] — minor/confirmed: FAD branch facet-count inconsistency in TPZShapeHDivConstant (latent: curved × HDivConstant × variable order). +- [[finding-approxspace-copy-drops-families]] — minor/confirmed: copy ops drop HDiv/H1/HCurl family flags. +- [[finding-approx-creator-hygiene]] — minor/confirmed cluster: tautological guard, mis-scoped if, stubs, dead interface machinery in the creator layer. + +NeoPZ C++/architecture (Phase 5): +- [[finding-debugstop-throws-release]] — **major/confirmed**: assertion macro throws messageless bad_exception in all configs (3k call sites, 9 catches). +- [[finding-global-state-cluster]] — major/confirmed: per-TU gTolerance (SetTolerance is a silent no-op), gRefDBase mutability, legacy statics. +- [[finding-mesh-lifetime-ownership]] — major/confirmed pattern: gmesh-first destruction dangles cmesh; raw-owner copy hazards (TPZAnalysis::fSolver). +- [[finding-thread-shared-materials]] — major/math-risk: parallel assembly relies on unenforced material statelessness (non-const Contribute). +- [[finding-build-config-gaps]] — major/confirmed: RelWithDebInfo gets neither PZDEBUG nor PZNODEBUG; 14 dead #ifdef DEBUG blocks; warnings off. +- [[finding-local-test-crashes-workingtree]] — major/insufficient-evidence: 5/40 suites crash in local working-tree build (pin is CI-green). + +divfreebubbles (application): +- [[finding-matred-solver-mode-mislabel]] — minor/confirmed, measurement-relevant: elasticity benchmarked with Darcy-shaped preconditioner. +- [[finding-rusage-memory-units]] — minor/confirmed: ru_maxrss bytes-vs-KB ⇒ 1024× memory overstatement on macOS benchmark tables. +- [[finding-mhm-target-uncompilable]] — minor/confirmed: registered target uses removed enum + ctor. +- [[finding-voronoi-null-ganalytic]] — minor/confirmed: null gAnalytic dereference on active path. + +## Sources (`sources/`) +- [[devloo-1997-pz-environment]] — founding architecture paper (design intent baseline). +- [[devloo-group-shape-construction]] — 2009/2013 shape-construction papers = published spec of Shape/ H(div)/H(curl) bases. +- [[avancini-2025-double-hybrid-elasticity]] — CMAME 2025 primal double-hybrid elasticity (↔ `EStandardSquared`, iter_elast) + Taraschi–Correa 2026 analysis. +- [[carvalho-2024-semi-hybrid-stokes]] — IJNME 2024 semi-hybrid-mixed (↔ `ESemi`, duplicated connects). +- [[araya-2013-mhm]] — MHM origin (SINUM 2013) + scalable-implementation companion. +- [[devloo-mhm-elasticity-polygonal]] — MHM elasticity on polygonal meshes (Devloo group). +- [[boffi-brezzi-fortin-2013]] — canonical mixed-FEM text (traces, inf-sup, Piola, exactness). +- [[cockburn-2009-unified-hybridization]] — canonical hybridization frame. +- [[devloo-hdiv-variants-accuracy]] — H(div) flavors on curved/hp meshes + divergence-accuracy remark. + +## Deliverables (../) — all phases complete 2026-07-02 +- `CODEBASE_ATLAS.md` — Phase 1 ✔ +- `EXECUTION_FLOWS.md` — Phases 2+4 ✔ +- `DOMAIN_PRIMER.md` — Phase 3 ✔ +- `ALGORITHM_NOTES.md` — Phase 4 ✔ +- `CPP_TECHNICAL_REVIEW.md` — Phase 5 ✔ +- `FINDINGS_AND_ROADMAP.md` — Phase 6 ✔ (+roadmap) +- `TESTING_AND_VALIDATION_REVIEW.md` — Phase 7 ✔ +- `NEOPZ_TECHNICAL_ASSESSMENT.md` — Phase 9 final report ✔ diff --git a/ai-analysis/wiki/log.md b/ai-analysis/wiki/log.md new file mode 100644 index 000000000..32df39e7f --- /dev/null +++ b/ai-analysis/wiki/log.md @@ -0,0 +1,134 @@ +--- +type: log +status: reviewed +updated: 2026-07-02 +tags: + - neopz + - log +--- + +# Analysis log + +Chronological record of major steps, discoveries, corrections, contradictions and open questions. +Newest entries at the bottom. Every entry lists evidence class: [repo] = repository evidence, [ref] = reference evidence, [agent] = subagent report (not yet independently re-verified), [run] = runtime observation. + +## 2026-07-02 — Session 1 + +### Phase 0 — setup and pinning +- Engagement started. Full plan approved by user (autonomous execution, phases 1→9). +- [repo] Repo = clone of `git@github.com:labmec/neopz.git`; repo default branch is `main` (`refs/remotes/origin/HEAD`), review canon is `develop` per user instruction. +- **Pinned analysis commit: local `develop` @ `6ffd38b12`** (2026-06-12, "Making some methods virtual"). +- [repo] Working tree = branch `SemiHybridElasticity` @ `4de234fae` = develop + 3 commits touching exactly 5 files: `Material/Elasticity/TPZHybridElasticity2D.cpp`, `Matrix/TPZSYSMPMatrix.h`, `Matrix/pzmatrix.h`, `Pre/TPZH1ApproxCreator.{h,cpp}`. Rule: cross-check these via `git show develop:` before citing. +- [repo] Local develop is 2 commits behind origin/develop @ `852a5116c` (last fetch 2026-06-19); those 2 commits belong to the same SemiHybridElasticity line. +- [repo] Runtime artifacts: divfreebubbles links `find_package(NeoPZ)` → `../neopz_install` prefix; `libpz.dylib` rebuilt 2026-06-30 16:29, `iter_elast` binary 16:43 same day. Runtime traces = evidence about that installed build (≈ develop + 5-file delta), labeled [run], never conflated with the develop pin. +- User decisions: (1) pin as above, (2) autonomous cadence with per-phase checkpoints, (3) run existing artifacts only, cwd-in-tmp; never overwrite `divfreebubbles/build/targets/results_*.txt` (live data, last written 2026-07-02 22:13). + +### Phase 1 — cartography (this session) +- Three read-only Explore agents swept: (a) NeoPZ module structure, (b) divfreebubbles app repo, (c) NeoPZ tests/CI/docs. Reports archived in conversation; load-bearing claims re-verified in main thread before entering wiki. +- Verified directly [repo]: CMake ≥3.14, `project(PZ)`, C++17, single `add_library(pz ...)` target (CMakeLists.txt:3,8,13,52); 24 `option(...)` flags; module `add_subdirectory` order (CMakeLists.txt:320-343); 5 GitHub workflow files; 4 `.h.h` template-body files (`Geom/pznoderep.h.h`, `Mesh/TPZGeoElement.h.h`, `Mesh/pzgeoelrefless.h.h`, `Mesh/tpzgeoelrefpattern.h.h`); `Publications/` = 3 H(div)-paper companion sources; `Material/needrefactor/` = 19 entries + `REAL/` subdir with 108 files. +- Verified directly [repo]: core headers read — `Material/TPZMatBase.h` (variadic mixin `TPZMatBase`), `Pre/TPZApproxCreator.h` (`HybridizationType {ENone,EStandard,EStandardSquared,ESemi}`, `ProblemType {ENone,EElastic,EDarcy,EStokes}`), `Mesh/pzcmesh.h`, `Mesh/pzgmesh.h`, `StrMatrix/TPZStructMatrix.h`, `Analysis/TPZAnalysis.h`, `Post/TPZVTKGenerator.h` (adapted from NGSolve, attributed), `Util/tpzautopointer.h` (atomic ref-count, Devloo), `README.md`, `Pre/pzcreateapproxspace.h` (function-pointer factory, Devloo 2009). +- **CORRECTION**: explorer agent (a) claimed `pzcreateapproxspace.h` lives in `Mesh/` and flagged a cross-module split as a "surprise". Wrong — it is `Pre/pzcreateapproxspace.h` [repo, verified by find]. The low-level factory and high-level creators are both in `Pre/`. Lesson: agent-only claims stay marked [agent] until re-verified. +- [repo] First-hand read of `divfreebubbles/targets/iter_elast.cpp` (full file): 2D hybrid elasticity benchmark, `TPZH1HybridApproxCreator` (app-side, `divfree/`), `HybridizationType::EStandardSquared`, orthogonalizing restraints + `HybridizeLowOrderFluxes` + `GroupAndCondenseElements`, `TPZMatRedSolver` `EDarcyH1Hybrid` vs direct MKL/MUMPS path; error/VTK blocks commented out; `results_*.txt` opened cwd-relative, two in truncate mode. +- Open question (Phase 5 candidate): `TPZCreateApproximationSpace` copy ctor / `operator=` appear to copy only `fp[8]` + some bools, not the `HDivFamily/H1Family/HCurlFamily` flavor flags or `fStyle` (Pre/pzcreateapproxspace.h:58-75, read cut at 75 — **verify full file before claiming**). +- Wiki bootstrapped: index, atlas, 14 code pages, 16 concept stubs (status: draft; concepts get filled in Phase 3). + +### Corrections ledger +| # | Claim | Source | Correction | Status | +|---|-------|--------|------------|--------| +| C1 | `pzcreateapproxspace.h` in `Mesh/` | agent (a) | Actually `Pre/pzcreateapproxspace.h` | fixed in atlas + [[approx-space-creators]] | + +### Phase 2 — shallow vertical slices (this session) +- Traced 5 slices; pages created: [[flow-iter-elast]], [[flow-dupl-connects]], [[flow-mhm-hdivconstant]], [[flow-dfreebubbles-1el]], [[flow-unit-test-hdiv-creator]]; `EXECUTION_FLOWS.md` v1 written. +- **OQ2 RESOLVED** [repo]: installed NeoPZ stamps `PZ_BRANCH="SemiHybridElasticity"`, `PZ_REVISION="852a5116c"` (= origin/develop tip at last fetch; develop + 2 delta commits). Caveat: config stamp regenerates at cmake-configure, dylib rebuilt Jun 30 — stamp is a lower bound; delta to worktree HEAD is at most the `MultiplyByScalar`-virtual commit. Runtime label: `[run @ 852a5116c(+)]`. +- Verified [repo]: `HDivFamily {EHDivStandard, EHDivConstant, EHDivKernel, EHDivOptimized}`, `H1Family {EH1Standard, EH1WidePrism}`, `HCurlFamily {EHCurlStandard, EHCurlNoGrads}` (Shape/TPZEnumApproxFamily.h:5-11). hdiv-space page corrected (EHDivOptimized added). +- Verified [repo]: `divfree/TPZMatRedSolver.h:15` `ProblemOrigin {EDarcyHDiv, EElasticityHDiv, EDarcyH1Hybrid, EElasticityH1Hybrid}`. +- New observations (app-side unless noted): + - iter_elast uses `EDarcyH1Hybrid` mode for an elasticity problem (`EElasticityH1Hybrid` exists) → Phase 4 must read `TPZMatRedSolver::Solve` before classifying (naming debt vs mis-selection). + - Benchmark drivers have error/VTK legs commented out and internally inconsistent analytic lambdas (3D sinh solution in 2D sweeps; forcing ≠ −Δu of exact; dead assignments overwriting exact solutions in main_1element) — benchmarks validate performance only; correctness legs live in dFreeBubbles1el + unit tests. + - Both benchmarks run `TPZLinearAnalysis(..., RenumType::ENone)` — renumbering off; why? → Phase 6. + - Same-name class `TPZMHMHDivApproxCreator` exists in NeoPZ `Pre/` AND `divfreebubbles/divfree/` — include-path-dependent selection; migration-in-progress pattern → Phase 5 risk. + - `TestDeRham` mechanics verified first-hand [repo:TestDeRham.cpp:49-120]: rank/kernel + inclusion checks via SVD, dims 2&3, k=1..3, pairs H1→HCurl, HCurl→L2/HDiv, HDiv(Const)→L2. + - `TestHDivApproxSpaceCreator` grid verified first-hand [repo:152-216]: 3 HDiv families × Darcy/Elastic × 4 mesh types × p{1,2} × extra-p{0,1} × hybridization {ENone,EStandard,ESemi} × RB × condensed × refined (+lib-side MHM creator at :519-524). + +### Phase 3 — domain & reference bootstrap (this session) +- Network research performed (WebSearch/WebFetch OK). 9 source pages created (see index §Sources). Key identifications, code-driven: + - `EStandardSquared` ↔ Avancini–Shauer–Oliveira–Devloo CMAME 2025 primal *double-hybrid* elasticity (H(div)–L² displacements/pressure, weak tangential continuity via shear-traction multiplier). Mapping marked hypothesis-level. + - `ESemi` ↔ Carvalho–Devloo IJNME 2024 *semi-hybrid-mixed* (strong normal, weak tangential continuity; duplicated connects). + - Shape/ H(div)/H(curl) construction ↔ De Siqueira–Devloo–Gomes JCAM 240 (2013): geometry-based vectors × hierarchical H1 scalars — matches the code-structure hypothesis in [[shape-functions]]. + - MHM ↔ Araya–Harder–Paredes–Valentin SINUM 51(6) 2013 (+ Devloo-group polygonal-elasticity variant). + - H(div) flavor/divergence-order variance is published (IJNME 2018 two-space paper; arXiv:1808.03625) → flavor surprises default to "intentional variant" pending trace. +- `DOMAIN_PRIMER.md` written (10 sections incl. reviewer caution list). Concept pages hybridization/mhm/piola/hdiv-space updated with reference-evidence blocks. +- Taraschi–Correa arXiv:2601.21635 (2026) fetched: primal hybrid (u,m,p) elasticity analysis — locking-free coercivity + inf-sup; related-community analysis anchor for the elasticity-hybrid line. +- Note: `Publications/` in-tree companions (hdiv2d/3d 2015, hdivCurved JCAM) still unmatched to exact papers — acceptable; not on critical path. + +### Phase 4 — deep review (this session) +- **iter_elast executed** [run @ 852a5116c(+), scratch cwd, p=1 iterative sweep, exit 0]: condensation 168,200→19,600 eqs (50²); reduced split "High Order Flux" 4,900 + "Linear Flux" 14,700; K00 factorized; **CG = 19 iterations at 50² and 400²** (mesh-independent). Output-column semantics confirmed; memory column = KiB-on-macOS bug → [[finding-rusage-memory-units]]. +- **Piola question RESOLVED** (agent trace, key lines re-verified first-hand): contravariant Piola in split factorization — master directions from Topology (+`fSideOrient` signs +permutation gather), `(1/|detJ|)·J` applied in `TPZCompElHDiv::ComputeShape` (`pzelchdiv.cpp:1032-1033`), FAD branch for curved derivatives. |detJ|-vs-signed-detJ composition left as expert-validation item. → [[piola-transformations]] status: reviewed/high. +- **H1 hybrid creator traced at develop** (agent, key lines re-verified): EStandardSquared = literal double hybridization (2nd interface/Lagrange layer; 1st-level flux absorbed into volume condensation groups; only 2nd-level skeleton global). Lagrange-level enum {EL2,EFlux,EDistFlux,EDelayDec,EAvSol,EHybFlux}; multipliers Darcy {1,1,1,−1} / Elastic {−1,−1,−1,1} (verified `TPZApproxCreator.cpp:780-795`). +- **HDiv creator + ESemi traced** (agent): duplicated-connect mechanics precise (even=constant-flux connect rebound to wrap on sideOrient=−1 side; odd=higher-order stays continuous); ESemi requires EHDivConstant/EHDivOptimized; elastic path adds rotation space (weak symmetry); "singular K00" guard documents why condensed HDivConstant elasticity needs ESemi or RB spaces. +- **Delta-file diffs characterized**: develop lacks TPZHybridElasticity2D body-force RHS (fixed 2 commits later upstream) → [[finding-hybridelasticity2d-missing-rhs-at-pin]] (major, confirmed, fixed-upstream); pzmatrix delta = virtual MultiplyByScalar; TPZSYSMPMatrix delta = self-assignment guard (same missing guard still present in `TPZMatRed::CopyFrom` [repo pzmatred.h:66-79]). +- Findings created: hybridelasticity2d-missing-rhs (major), hdivconstant-fad-index (minor, confirmed inconsistency REAL vs FAD branch, verified :191 vs :304), approxspace-copy-drops-families (minor), approx-creator-hygiene cluster (minor: tautology, mis-scoped if — both verified via `git show develop:`; stubs; dead Backup/UnitaryLagrange machinery), rusage-memory-units (app), voronoi-null-ganalytic (app). +- OQ4 RESOLVED (confirmed app bug). Remaining in-flight: MatRedSolver trace (agent), OQ6/OQ7. + +### Phase 4→7 runtime evidence batch (this session) +- MatRedSolver trace complete [agent, key lines verified]: split by Lagrange level {1}→K00 (mode-independent); matrix-free Schur CG + block-diag(ELU) preconditioner; **EDarcyH1Hybrid vs EElasticityH1Hybrid differ only in preconditioner block size** ⇒ iter_elast mislabel is consequential for benchmarks → [[finding-matred-solver-mode-mislabel]]. OQ6 resolved (enum removed at app HEAD `fbe9696`; 3-arg ctor gone) → [[finding-mhm-target-uncompilable]]. OQ7 resolved: `RenumType::ENone` because `TPZSparseMatRed::ReorderEquations` imposes its own Lagrange-level-contiguous ordering. +- **Direct-vs-iterative sweep** [run, p=1]: 50² parity (81/69 vs 78/75 ms); 400²: direct solve 7,851 ms vs Schur-CG 4,718 ms; assembly ≈ equal (~5.3 s); memory similar. Direct-solve growth superlinear; iterative ≈ linear (mesh-independent CG). → Phase 6. +- **ctest on existing build** (Release, 40 tests) [run]: 35 pass / **5 crash** (TestCondensedHangingNodes SIGTRAP; TestReduced, TestErrorAnalysis, TestHangingNode, TestSBFem bus errors). Failing binaries same-session as libpz ⇒ not stale-ABI. Upstream CI **green at pin `6ffd38b` and at `852a511`** [web api]. Attribution: local working-tree state (build = 852a5116c + then-uncommitted edits) or machine config → [[finding-local-test-crashes-workingtree]] (insufficient-evidence; not counted against the pin). + +### Phase 5 — C++ & architecture review (this session) +- Two sweeps (ownership/threads; API/build) + first-hand verification of all H-severity claims. `CPP_TECHNICAL_REVIEW.md` written. +- Verified H-items: DebugStop throws bad_exception unconditionally (pzerror.cpp:15-28, guards commented out); `gTolerance` header-static per-TU (TPZTopologyUtils.h:23) ⇒ SetTolerance silent no-op; asymmetric gmesh/cmesh destructor protection (pzgmesh.cpp:97-103 vs pzcmesh.cpp:178-187); `Contribute` non-const (TPZMatSingleSpace.h:112-114) while shared across assembly threads; build-config triad (CMakeLists.txt:82-90 — RelWithDebInfo gets neither macro; 14 dead `#ifdef DEBUG`; no -Wall, Xcode warnings silenced). +- Notable positives recorded: OR/OT parallel assembly design (coloring + condvar ordering, per-thread scratch), material mixin discipline, 3757 `override`, atomic TPZAutoPointer, good header-doc coverage, extensibility walkthroughs quantified (material ~335 lines; solver 3 overrides; element family = the weak point, ~500 lines with copy-paste dispatch across 14 files). +- Layering: single `pz` target makes CMake order decorative; 6 backward include edges; Mesh⇄Pre SCC. Counts: 963 `new TPZ*`, TPZAutoPointer 758, unique_ptr 0. +- 5 new finding pages (see index). OR/OT question resolved in [[structural-matrices]]. + +### Phases 6–8 (this session) +- Phase 6: `FINDINGS_AND_ROADMAP.md` written — measured Schur-vs-direct crossover table, K00-dominance analysis, shared-memory-only ceiling (no MPI; BDDC dormant), perf-infra gaps, tradeoff-annotated suggestions, consolidated findings register, roadmap v1. +- Phase 7: `TESTING_AND_VALIDATION_REVIEW.md` written — inventory + proves/doesn't-prove analysis (invariant-strong, rate-weak), live ctest results integrated, 8-point validation strategy topped by a manufactured-solution **rate** matrix with nonzero body forces (directly motivated by the at-pin RHS bug). +- Phase 8 lint: 60 wiki pages, 61 link targets, **0 broken links, 0 orphans** (scripted check). Duplicate scan: hp-adaptivity vs refinement-hanging-nodes intentionally split & cross-linked. Stale-claim scan: DOMAIN_PRIMER §4 softened — EStandardSquared is a *structurally matching H1-primal variant* of the Avancini 2025 method, not a verbatim implementation (matches Phase 4 trace + source-page caveat). Flows all link both code+concepts; all source pages linked from concepts/findings; index updated through Phase 5 findings. + +### Phase 9 — final report (this session) +- `NEOPZ_TECHNICAL_ASSESSMENT.md` written (§1–§11 per spec): confidence-labeled ([HC]/[MC]/[LC]), every §5 tension classified 5-way, §10 = 10 expert questions, §11 = evidence-boundary map. Engagement complete; wiki is the durable knowledge base; log ends here for session 1. + +### Corrections ledger (cont.) +| # | Claim | Source | Correction | Status | +|---|-------|--------|------------|--------| +| C2 | `TPZMatRedSolver` has modes `EDefault`/`EMHMSparse` | agent (b) report + older driver code | Current header has neither; only 4 ProblemOrigin values | fixed in [[matrix-and-solvers]]; spawned OQ6 | + +## 2026-07-06 — Session 2: library-breadth rebalance + +### Mandate & method +- User feedback: Session 1 over-weighted divfreebubbles/HDiv; rebalance the docs toward the library itself (Topology→Geom→Shape stack, all space types incl. discontinuous, TPZConnect restraints, TPZMultiphysicsCompMesh, TPZCondensedCompEl/TPZElementGroup/TPZSubCompMesh, materials, matrices, StrMatrix), and survey the 5 most recent NeoPZ application projects in `~/GitHub` (each embeds its own near-identical neopz). +- Method: 9 parallel read-only explorers (5 downstream apps + 4 library subsystems); all load-bearing claims spot-verified first-hand before entering the wiki. Same pin (`develop @ 6ffd38b12`); downstream claims carry app-repo evidence class at each repo's HEAD — never conflated with pin evidence. +- Downstream recency determined by the app repos' own git logs [repo]: Iterative-Saddle_Point (2026-03-27), GFEM (2025-12-18), ErrorEstimation (2025-11-05), wann (2025-09-23), MixedElasticity (2025-05-19). NeoPZ_masterResearch excluded (build/examples area, not an app repo). + +### New wiki content +- `apps/` (new section): [[apps-overview]] + [[app-iterative-saddle-point]], [[app-gfem]], [[app-error-estimation]], [[app-wann]], [[app-mixed-elasticity]]. Highlights: wann ≠ electromagnetics (it is wellbore-Darcy + ANN); GFEM subclasses `TPZCompElH1::ComputeShape` for enrichment; ErrorEstimation implements 4 estimator families + closed hp loops; MixedElasticity runs 3–7-field tensor mixed methods; Iterative-Saddle_Point drives Uzawa loops over cloned Pardiso matrices. Cross-cutting observations (9) recorded in the overview. +- `code/` (new deep-dive pages, agent-traced + line-verified): [[element-families]] (H1/HCurl/disc/interfaces — incl. resolutions: H1Family is creation-time & prism-only; HCurlFamily is a live runtime switch; covariant Piola confirmed in `TPZCompElHCurl::TransformShape`; L² pressure = broken-H1 (p>0) vs TPZCompElDisc (p=0); no `EDisconnected` enum exists), [[TPZConnect]] (packed flags; dependency = L2 projection of coarse trace; complex-correct `ApplyConstraints`; condensed∧dependent illegal; `SaddlePermute` mechanics — resolves the old fBlock/fSolutionBlock OQ), [[multiphysics-composition]] (AddElements ancestor-walk; AddConnects dependency re-offset; datavec order = mesh-vector order — resolves material-system OQ), [[condensation-groups-submeshes]] (Resequence rules; K11Reduced/UGlobal; SubCompMesh dual inheritance + rigid-body modes; ordering constraints), [[geometry-refinement-maps]] (TPZGeoEl policy stack; .rpt format; genealogy→RestrainSide bridge; TPZGeoElMapped exact-map inheritance; pyramid→6 pyr + 4 tet; gRefDBase deserialization coupling). +- `concepts/`: new [[discontinuous-l2-dg]]; upgraded to reviewed: [[h1-space]], [[hcurl-space]], [[sbfem]] (Hamiltonian + direct `dgeev_`, bypasses TPZEigenSolver stack), [[hp-adaptivity]] (drivers confirmed downstream); targeted updates: [[mixed-methods]] (weak symmetry resolved), [[refinement-hanging-nodes]], [[geometric-mappings]], [[static-condensation]], [[piola-transformations]] (HCurl covariant note), [[error-estimation-convergence]]. +- `code/` updates: [[material-system]] (taxonomy verified vs CMakeLists; CSTATE electromagnetics + eigen mixins; BC framework; TPZMatWithMem; post-processing seams), [[matrix-and-solvers]] (eigen-solver stack verified), [[TPZCompMesh]], [[TPZCompElHDiv]], [[divfree-support-lib]]. + +### Deliverables revised +- `NEOPZ_TECHNICAL_ASSESSMENT.md`: Session-2 method note; exec summary gains "How it is actually used" (six-repo evidence); §3 domain-map additions; §6 extensibility re-weighed (material layer absorbs ~all downstream variation; GFEM shows family *modification* is cheap); §11 evidence classes updated. +- `DOMAIN_PRIMER.md` §10–12 (families as code structures; eigen/complex/SBFem; downstream usage); `ALGORITHM_NOTES.md` §9–11; `CODEBASE_ATLAS.md` §7 downstream landscape; `EXECUTION_FLOWS.md` scope note; `CPP_TECHNICAL_REVIEW.md` M8 corrected + §6 corroboration. + +### Corrections ledger (cont.) +| # | Claim | Source | Correction | Status | +|---|-------|--------|------------|--------| +| C3 | `needrefactor/` "still compiles into `pz`" | Session-1 CPP sweep (M8) + final report §6 | No `add_subdirectory(needrefactor)`; `libpz.dylib` has zero needrefactor symbols [verified by nm]. Risk is header/name shadowing only; severity M→L | fixed in CPP review, atlas (§9 ledger), final report §6+§9 | +| C4 | Agent cited wann sources under `sources/` | app explorer | Actual dir is `src/` | corrected in [[app-wann]] | + +### Notable cross-repo observations (for future sessions) +- [repo] `TPZHybridElasticity2D` exists app-side in ErrorEstimation (`ErrorEstimation/Material/TPZHybridElasticity2D.h:25`, edited 2025-11-05) *and* in the library (a 5-delta file of this working tree) — the SemiHybridElasticity line spans both repos; same-name migration risk live right now. +- [repo] Embedded neopz branches: develop (Iterative, MixedElasticity), `Australia25` (GFEM, ErrorEstimation), develop@f3b4000 (wann) — recent commits in each are app-motivated library fixes (HDiv side-orient dependency check for wann; eigenvector-loading/subdivision fixes for GFEM). +- MatRed-pattern reimplementations: divfreebubbles `TPZSparseMatRed`, GFEM `TPZSSpMatRedStructMatrix`+`TPZSparseMatRed`, Iterative's manual Schur loop → candidate library feature. +- None of the five apps uses H(curl)/CSTATE — that coverage rests on Electromagnetics materials + unit tests (older WGMAResearch line downstream). + +### Open questions (running list) +- OQ1: Copy semantics of `TPZCreateApproximationSpace` (see above) — Phase 5. +- ~~OQ2~~ RESOLVED (see Phase 2 notes): installed build = `852a5116c(+)`. +- OQ3: `[!shouldfail]`-tagged unit tests (SVD, some skyline ops) — known gaps; what do they imply for LAPACK-path reliability? Phase 7. +- OQ4: divfreebubbles `voronoi_mixed_elas` possible null `gAnalytic` dereference [agent] — confirm by reading source in Phase 2/4. +- OQ5: docs claim "open-source" but no LICENSE file in tree [agent, verified absent by agent search] — re-verify and note in Phase 7 hygiene. +- OQ6: `main_MHM_HDivConstant.cpp:184` references `TPZMatRedSolver::EMHMSparse` which no longer exists in the header [repo] — does the current app tree still build this target? Check git log of `TPZMatRedSolver.h` / try understanding when enum changed (read-only). App-side finding candidate. +- OQ7: Why do benchmark drivers disable renumbering (`RenumType::ENone`)? Interaction with MatRedSolver block structure? — Phase 4/6. diff --git a/ai-analysis/wiki/sources/araya-2013-mhm.md b/ai-analysis/wiki/sources/araya-2013-mhm.md new file mode 100644 index 000000000..057cec15c --- /dev/null +++ b/ai-analysis/wiki/sources/araya-2013-mhm.md @@ -0,0 +1,35 @@ +--- +type: source +status: reviewed +authority: canonical +scope: paper +updated: 2026-07-02 +confidence: high +tags: + - fem + - mhm +--- + +# Multiscale Hybrid-Mixed method (Araya–Harder–Paredes–Valentin 2013) + +## Bibliographic reference +R. Araya, C. Harder, D. Paredes, F. Valentin, "Multiscale Hybrid-Mixed Method", SIAM J. Numer. Anal. 51(6) (2013) 3505–3531. DOI [10.1137/120888223](https://epubs.siam.org/doi/abs/10.1137/120888223). (Origin; Harder–Valentin follow-ups 2015 extend.) Implementation-side companion in the same community: "On the Implementation of a Scalable Simulator for Multiscale Hybrid-Mixed Methods" ([arXiv:1703.10435](https://arxiv.org/pdf/1703.10435)). + +## Why this source matters +Defines the MHM method NeoPZ's `TPZMHM*` controllers/creators implement (Devloo's group collaborates directly with the Valentin school). + +## Claims extracted +- MHM relaxes continuity of the primal variable on a coarse skeleton via Lagrange multipliers while keeping **strong continuity of the normal flux component**; basis functions carry fine scales by solving **independent local problems** per coarse element (embarrassingly parallel); dual variable from postprocessing is **locally conservative** [abstracts]. +- Well-posedness of local problems requires handling the constant/rigid-body kernel per subdomain (the multiplier system sees only skeleton unknowns + coarse constants). + +## Applicability to NeoPZ +Grounds [[mhm]]: expected invariants for `TPZMHMHDivApproxCreator`/`PutinSubstructures`/`CondenseElements` — subdomain local solves = `TPZSubCompMesh` internal condensation; coarse constants = `IsRigidBodySpaces()=true` requirement observed in [[flow-mhm-hdivconstant]]; skeleton flux continuity = wrap/skeleton element structure. + +## Limits of applicability +NeoPZ's realization (H(div) local solvers, EHDivConstant family, polygonal partitions) is a Devloo-group variant ([[devloo-mhm-elasticity-polygonal]]); the SINUM paper's exact spaces/estimates don't transfer verbatim. + +## Related wiki pages +[[mhm]] · [[static-condensation]] · [[hybridization]] · [[flow-mhm-hdivconstant]] + +## Open questions +- Which MHM generation (controllers vs creators) matches which paper generation — Phase 4/5 duplication check. diff --git a/ai-analysis/wiki/sources/avancini-2025-double-hybrid-elasticity.md b/ai-analysis/wiki/sources/avancini-2025-double-hybrid-elasticity.md new file mode 100644 index 000000000..05a30389b --- /dev/null +++ b/ai-analysis/wiki/sources/avancini-2025-double-hybrid-elasticity.md @@ -0,0 +1,39 @@ +--- +type: source +status: reviewed +authority: strong +scope: paper +updated: 2026-07-02 +confidence: medium +tags: + - neopz + - elasticity + - hybridization +--- + +# Primal double-hybrid elasticity with H(div)–L² spaces (Avancini et al. 2025) + related analysis + +## Bibliographic reference +G. Avancini, N. Shauer, H.L. Oliveira, P.R.B. Devloo, "A primal double-hybrid FEM for 3D compressible and incompressible elasticity using H(div)-L2 spaces", Comput. Methods Appl. Mech. Engrg. (2025), art. 118295 (ADS bibcode 2025CMAME.44618295A; [ResearchGate](https://www.researchgate.net/publication/391164187)). +Related analysis (same community): G. Taraschi, M.R. Correa, "Numerical analysis of a locking-free primal hybrid method for linear elasticity with H(div)-conforming stress recovery", [arXiv:2601.21635](https://arxiv.org/html/2601.21635) (2026) — (u, m, p) primal-hybrid + pressure; inf-sup and locking-free coercivity proofs (fetched abstract + structure). + +## Why this source matters +Published counterpart of the elasticity-hybridization line the working tree is actively developing (branch SemiHybridElasticity; delta files `TPZH1ApproxCreator`, `TPZHybridElasticity2D`) and the mandated slice [[flow-iter-elast]]. + +## Claims extracted +- Displacements approximated in **H(div)** (normal component continuous by construction); **tangential continuity imposed weakly** via a Lagrange multiplier = shear stress on edges/faces; pressure in L², De Rham-compatible with the displacement space → stable for compressible through incompressible regimes [2025 abstract]. +- "Double-hybrid": two multiplier levels in the formulation (verify exact second hybridization against the paper body in Phase 4). +- Taraschi–Correa: existence/uniqueness under kernel-coercivity + inf-sup (constants independent of λ → locking-free); element-wise recovery gives H(div)-conforming, locally equilibrated, weakly symmetric stress. + +## Applicability to NeoPZ +Interprets `HybridizationType::EStandardSquared` and `HybridizationData::SetProblemHybridH1` semantics ([[approx-space-creators]], [[hybridization]]); explains why iter_elast/semiHybrid_elas hybridize *elasticity* and condense to skeleton systems; grounds Phase 4 invariants (multiplier order pairing, SPD-ness of condensed system, incompressible-limit behavior). + +## Limits of applicability +**Mapping is hypothesis-level until Phase 4**: iter_elast drives a `TPZH1Hybrid…` (H1 displacement?) creator while the 2025 paper uses H(div) displacements — the code may implement the paper's method, a primal-H1 double hybrid variant, or both selected by ProblemType/family. Do not attribute the paper's stability claims to the code path before tracing. + +## Related wiki pages +[[hybridization]] · [[flow-iter-elast]] · [[approx-space-creators]] · [[mixed-methods]] · [[hdiv-space]] + +## Open questions +- Which exact spaces does `EStandardSquared` produce for ProblemType::EElastic at the pin? (Phase 4 trace of `TPZH1ApproxCreator` + `HybridizationData::SetProblemHybridH1`.) +- Does "orthogonalizing restraints" (app-side) correspond to a construction in the 2025 paper or to unpublished work? diff --git a/ai-analysis/wiki/sources/boffi-brezzi-fortin-2013.md b/ai-analysis/wiki/sources/boffi-brezzi-fortin-2013.md new file mode 100644 index 000000000..e6501fb35 --- /dev/null +++ b/ai-analysis/wiki/sources/boffi-brezzi-fortin-2013.md @@ -0,0 +1,38 @@ +--- +type: source +status: reviewed +authority: canonical +scope: textbook +updated: 2026-07-02 +confidence: high +tags: + - fem + - mixed-methods +--- + +# Mixed Finite Element Methods and Applications (Boffi–Brezzi–Fortin 2013) + +## Bibliographic reference +D. Boffi, F. Brezzi, M. Fortin, *Mixed Finite Element Methods and Applications*, Springer Series in Computational Mathematics 44, 2013. DOI 10.1007/978-3-642-36519-5. + +## Why this source matters +Canonical reference for every mixed-method expectation used in this assessment: inf-sup theory, H(div) conformity, RT/BDM families, Piola maps, hybridization basics. + +## Claims extracted (the ones this assessment leans on) +- H(div) conformity ⇔ normal-trace continuity; H(curl) ⇔ tangential-trace continuity (Ch. 2). +- Contravariant Piola map preserves normal traces & the divergence pairing; covariant map preserves tangential traces — required on non-affine/curved maps for optimal rates (Ch. 2.1.3). +- Saddle-point well-posedness = ellipticity-on-kernel + inf-sup (Brezzi conditions) (Ch. 4-5). +- Discrete exactness/commuting diagrams underlie stability of compatible pairs (Ch. 2.5, FEEC-adjacent). +- Hybridization of mixed methods produces SPD condensed multiplier systems (Ch. 7 context; cf. [[cockburn-2009-unified-hybridization]]). + +## Applicability to NeoPZ +Reference evidence for [[hdiv-space]], [[hcurl-space]], [[mixed-methods]], [[piola-transformations]], [[de-rham-complex]], [[hybridization]] — as *expected invariants*, not as prescriptions of NeoPZ's basis choices (NeoPZ uses its own hierarchical families, [[devloo-group-shape-construction]]). + +## Limits of applicability +NeoPZ's families ≠ RT/BDM; dimension counts, DOF layouts and some stability proofs differ. Use for *properties* (traces, inf-sup, mapping requirements), not for family-specific facts. + +## Related wiki pages +[[mixed-methods]] · [[hdiv-space]] · [[piola-transformations]] · [[de-rham-complex]] · [[hybridization]] + +## Open questions +— none (background canon). diff --git a/ai-analysis/wiki/sources/carvalho-2024-semi-hybrid-stokes.md b/ai-analysis/wiki/sources/carvalho-2024-semi-hybrid-stokes.md new file mode 100644 index 000000000..6cf7181e4 --- /dev/null +++ b/ai-analysis/wiki/sources/carvalho-2024-semi-hybrid-stokes.md @@ -0,0 +1,38 @@ +--- +type: source +status: reviewed +authority: strong +scope: paper +updated: 2026-07-02 +confidence: medium +tags: + - neopz + - hybridization + - stokes + - hdiv +--- + +# Semi-hybrid-mixed method for Stokes–Brinkman–Darcy with H(div) velocities (Carvalho, Devloo et al. 2024) + +## Bibliographic reference +P.G.S. Carvalho, P.R.B. Devloo, et al., "A semi-hybrid-mixed method for Stokes–Brinkman–Darcy flows with H(div)-velocity fields", Int. J. Numer. Methods Eng. (2024). DOI [10.1002/nme.7363](https://onlinelibrary.wiley.com/doi/10.1002/nme.7363). Related talk: "A Semi-Hybrid approximation of the Stokes equations using H(div) spaces" (Devloo, Oden Institute seminar). + +## Why this source matters +Defines **semi-hybridization** — the published meaning behind `HybridizationType::ESemi` and the duplicated-connects machinery (`TPZCompElHDivDuplConnects*`, app + lib) exercised by [[flow-dupl-connects]] and the current SemiHybrid* research line. + +## Claims extracted +- Velocity in H(div): normal-component continuity kept **strong** ("taken for granted"); **tangential continuity imposed weakly** by a Lagrange multiplier playing the role of tangential traction; pressure discontinuous, divergence-compatible with velocity [abstract]. +- "Semi": only part of the interface continuity is moved to multipliers (vs full hybridization which breaks all continuity) → smaller multiplier space, keeps local conservation. +- Stokes–Darcy coupling is natural in this setting; in the Darcy region the weak tangential condition can be dropped. + +## Applicability to NeoPZ +Semantics for `ESemi` in [[approx-space-creators]]/[[hybridization]]; rationale for duplicated connects (the duplicated face functions become the weakly-constrained part); context for `TPZMatRedSolver` reductions (skeleton multiplier block = Schur target) in [[flow-dupl-connects]] and [[flow-iter-elast]]. + +## Limits of applicability +Paper treats Stokes/Brinkman; dupl_connects applies ESemi to *Darcy* where the paper says tangential weak continuity is unnecessary — the code's ESemi-for-Darcy may hybridize the *normal-trace/flux* structure differently. Trace before judging (Phase 4). + +## Related wiki pages +[[hybridization]] · [[hdiv-space]] · [[flow-dupl-connects]] · [[divfree-support-lib]] + +## Open questions +- Exactly which connects are duplicated for ESemi in `TPZHDivApproxCreator` at the pin, and which material glues them (`TPZLagrangeMultiplier`?). diff --git a/ai-analysis/wiki/sources/cockburn-2009-unified-hybridization.md b/ai-analysis/wiki/sources/cockburn-2009-unified-hybridization.md new file mode 100644 index 000000000..02e937f85 --- /dev/null +++ b/ai-analysis/wiki/sources/cockburn-2009-unified-hybridization.md @@ -0,0 +1,36 @@ +--- +type: source +status: reviewed +authority: canonical +scope: paper +updated: 2026-07-02 +confidence: high +tags: + - fem + - hybridization +--- + +# Unified hybridization of DG, mixed and continuous Galerkin (Cockburn–Gopalakrishnan–Lazarov 2009) + +## Bibliographic reference +B. Cockburn, J. Gopalakrishnan, R. Lazarov, "Unified hybridization of discontinuous Galerkin, mixed, and continuous Galerkin methods for second order elliptic problems", SIAM J. Numer. Anal. 47(2) (2009) 1319–1365. DOI 10.1137/070706616. + +## Why this source matters +The standard modern frame for *what hybridization is* (break continuity, introduce skeleton multipliers, condense to a skeleton problem) — the vocabulary against which NeoPZ's `HybridizationType` taxonomy and wrap/interface/Lagrange geometry can be assessed as conventional-or-variant. + +## Claims extracted +- Hybridized mixed methods: local solvers per element + a global equation only for the trace/multiplier unknown; the condensed system is SPD for symmetric elliptic problems. +- The multiplier is the trace of the primal variable (or numerical flux), and transmission conditions define the skeleton bilinear form. +- One frame covers mixed/DG/CG hybrid variants → variations (which continuity is broken, which multiplier space) are legitimate design choices, not errors. + +## Applicability to NeoPZ +Baseline for [[hybridization]]: `EStandard` ≈ classic single-level hybridization; `EStandardSquared`/`ESemi` are Devloo-group extensions ([[avancini-2025-double-hybrid-elasticity]], [[carvalho-2024-semi-hybrid-stokes]]); SPD-ness expectation justifies LDLt/CG on condensed systems in the benchmark slices. + +## Limits of applicability +Scalar elliptic focus; elasticity/Stokes variants need the specific papers. Static-condensation implementation details (grouping, connect levels) are NeoPZ-specific. + +## Related wiki pages +[[hybridization]] · [[static-condensation]] · [[mixed-methods]] · [[flow-iter-elast]] + +## Open questions +— none (background canon). diff --git a/ai-analysis/wiki/sources/devloo-1997-pz-environment.md b/ai-analysis/wiki/sources/devloo-1997-pz-environment.md new file mode 100644 index 000000000..68a451ea4 --- /dev/null +++ b/ai-analysis/wiki/sources/devloo-1997-pz-environment.md @@ -0,0 +1,38 @@ +--- +type: source +status: reviewed +authority: canonical +scope: paper +updated: 2026-07-02 +confidence: high +tags: + - neopz + - architecture +--- + +# PZ: an object-oriented environment for scientific programming (Devloo 1997) + +## Bibliographic reference +P.R.B. Devloo, "PZ: An object oriented environment for scientific programming", Computer Methods in Applied Mechanics and Engineering 150 (1997) 133–153. DOI 10.1016/s0045-7825(97)00097-2. (Cited as the reference publication in `README.md` [repo].) + +## Why this source matters +The founding design paper of this exact library: states the original architectural intent (separation of geometry/topology/interpolation/algebra, extensibility via OO), against which today's structure can be honestly compared (what evolved vs. what ossified). + +## Concepts covered +Geometric vs computational mesh split; element/side topology abstraction; hp interpolation; matrix abstraction; OO design for FEM. + +## Claims extracted (relevant to the assessment) +- The gmesh/cmesh split and the "side" abstraction are *original, deliberate* design pillars — not accretions. → grounds [[TPZGeoMesh]], [[TPZCompMesh]], [[topology-module]]. +- Extensibility via subclassing (materials, elements, matrices) is the intended extension mechanism → baseline for Phase 5 extensibility judgement. + +## Applicability to NeoPZ +Architecture-intent evidence for `CODEBASE_ATLAS` §1-3 and the Phase 5 review ("essential vs accidental" complexity calls). + +## Limits of applicability +1997 design predates C++11/17, multiphysics, HDiv/HCurl families, creators — do not treat as normative for those layers. + +## Related wiki pages +[[TPZGeoMesh]] · [[TPZCompMesh]] · [[material-system]] · [[shape-functions]] + +## Open questions +- Locate a copy for detail-level claims if Phase 5 needs direct quotes (paywalled; abstract-level use so far). diff --git a/ai-analysis/wiki/sources/devloo-group-shape-construction.md b/ai-analysis/wiki/sources/devloo-group-shape-construction.md new file mode 100644 index 000000000..0e096170f --- /dev/null +++ b/ai-analysis/wiki/sources/devloo-group-shape-construction.md @@ -0,0 +1,40 @@ +--- +type: source +status: reviewed +authority: canonical +scope: paper +updated: 2026-07-02 +confidence: high +tags: + - neopz + - shape-functions + - hdiv + - hcurl +--- + +# Devloo-group shape-function construction papers (2009–2015) + +## Bibliographic reference (tightly related group) +1. P.R.B. Devloo, C.M.A.A. Bravo, E.C. Rylo, "Systematic and generic construction of shape functions for p-adaptive meshes of multidimensional finite elements", CMAME 198 (2009) 1716–1725. *(H1 hierarchical construction; per-topology, per-side.)* +2. D. De Siqueira, P.R.B. Devloo, S.M. Gomes, "A new procedure for the construction of hierarchical high order Hdiv and Hcurl finite element spaces", J. Comput. Appl. Math. 240 (2013) 204–214. ([ScienceDirect](https://www.sciencedirect.com/science/article/pii/S0377042712003998)) +3. Related follow-ups: hierarchical H(div) bases on curved 2D manifolds (ResearchGate 282859729); "Two-Dimensional H(div)-Conforming Finite Element Spaces with hp-Adaptivity" (Springer, 10.1007/978-3-319-39929-4_9). + +## Why this source matters +These papers *are* the published specification of what `Shape/` implements: NeoPZ's H(div)/H(curl) bases are not RT/BDM/Nédélec textbook families but the Devloo-group construction. + +## Claims extracted +- **Construction principle** [2013 abstract]: choose vector fields based on each element's geometry, multiply them by hierarchical H1 scalar functions → vector basis with continuous normal (H(div)) or tangential (H(curl)) interface components. +- Bases are hierarchical, per-side organized → variable order per connect (hp) is by-construction. +- [2009] H1 shapes built systematically from topology side-closures + orientation rules. + +## Applicability to NeoPZ +Direct: [[shape-functions]] (`TPZShapeHDiv*`, `TPZShapeHCurl*` = "vectors × H1 scalars" — matches the code-structure hypothesis recorded there), [[TPZCompElHDiv]], [[hdiv-space]], [[hcurl-space]]. Conformity-by-construction explains why unit tests focus on trace continuity + permutation invariance rather than comparing against RT/BDM. + +## Limits of applicability +2D-centric in [2]; 3D families, `EHDivConstant`/`EHDivKernel`/`EHDivOptimized` flavors and later refinements are separate developments — do not over-apply. Textbook Piola expectations may not map 1:1 onto this construction ([[piola-transformations]]). + +## Related wiki pages +[[shape-functions]] · [[hdiv-space]] · [[hcurl-space]] · [[topology-module]] · [[piola-transformations]] + +## Open questions +- Which paper (if any) documents the 3D H(div) family as implemented at the pin? (Candidate: Devloo et al. IJNME 2018, see [[devloo-hdiv-variants-accuracy]].) diff --git a/ai-analysis/wiki/sources/devloo-hdiv-variants-accuracy.md b/ai-analysis/wiki/sources/devloo-hdiv-variants-accuracy.md new file mode 100644 index 000000000..880221f6a --- /dev/null +++ b/ai-analysis/wiki/sources/devloo-hdiv-variants-accuracy.md @@ -0,0 +1,36 @@ +--- +type: source +status: draft +authority: strong +scope: paper +updated: 2026-07-02 +confidence: medium +tags: + - neopz + - hdiv +--- + +# H(div) variants & divergence accuracy (Devloo group, 2018 + arXiv 1808.03625) + +## Bibliographic reference (tightly related group) +1. P.R.B. Devloo et al., "Mixed finite element approximations based on 3-D hp-adaptive curved meshes with two types of H(div)-conforming spaces", Int. J. Numer. Methods Eng. (2018). DOI [10.1002/nme.5698](https://onlinelibrary.wiley.com/doi/10.1002/nme.5698). +2. Devloo group, "A remark concerning divergence accuracy order for H(div)-conforming finite element flux approximations", [arXiv:1808.03625](https://arxiv.org/pdf/1808.03625). + +## Why this source matters +Documents (a) that NeoPZ deliberately ships **multiple H(div) space types** on 3D hp-adaptive *curved* meshes and (b) the group's own analysis of divergence accuracy orders — the published context for `HDivFamily` flavors (`EHDivStandard/EHDivConstant/...`) and the `fExtraInternalPOrder` (hdiv+/hdiv++) knob. + +## Claims extracted +- Two H(div) space types with different internal enrichment yield different pressure/divergence accuracy on the same mesh [1, title/abstract level]. +- Divergence order of H(div) flux approximations can differ from the flux order depending on family/geometry — a known, published subtlety, not an implementation accident [2]. + +## Applicability to NeoPZ +Direct context for [[hdiv-space]] flavors and the enriched-order options in [[approx-space-creators]]; supports classifying flavor-related surprises as *intentional variants*; feeds Phase 7 expectations (which orders should convergence tests show per family). + +## Limits of applicability +Claims held at abstract level (paywalled/preprint skim pending); exact family definitions at the pin must come from code (Phase 4) — mark any mismatch as insufficient-evidence first. + +## Related wiki pages +[[hdiv-space]] · [[approx-space-creators]] · [[piola-transformations]] · [[geometric-mappings]] · [[error-estimation-convergence]] + +## Open questions +- Do the paper's "two types" correspond to `EHDivStandard` vs `EHDivConstant` at the pin, or to older families? What is `EHDivOptimized`? diff --git a/ai-analysis/wiki/sources/devloo-mhm-elasticity-polygonal.md b/ai-analysis/wiki/sources/devloo-mhm-elasticity-polygonal.md new file mode 100644 index 000000000..d18cf444a --- /dev/null +++ b/ai-analysis/wiki/sources/devloo-mhm-elasticity-polygonal.md @@ -0,0 +1,36 @@ +--- +type: source +status: draft +authority: strong +scope: paper +updated: 2026-07-02 +confidence: medium +tags: + - neopz + - mhm + - elasticity +--- + +# New H(div)-conforming MHM for elasticity on polygonal meshes (Devloo, Farias et al.) + +## Bibliographic reference +P.R.B. Devloo, A.M. Farias, S.M. Gomes, et al., "New H(div)-conforming multiscale hybrid-mixed methods for the elasticity problem on polygonal meshes" ([Semantic Scholar](https://www.semanticscholar.org/paper/e7502db2ca2eea5cdea18dba1c5a0f11f38f7504); ESAIM:M2AN or similar venue — pin exact venue when needed). + +## Why this source matters +The MHM+H(div)+polygonal-mesh+elasticity combination is precisely what the divfreebubbles MHM/voronoi drivers exercise ([[flow-mhm-hdivconstant]], `voronoi_mixed_elas`). + +## Claims extracted +- Family of MHM methods for 2D linear elasticity on general polygonal meshes; approximate displacement and **stress divergence super-convergent in L²** [abstract via search]. +- Local problems use H(div)-conforming stress spaces; rigid-body modes per subdomain are the coarse unknowns (consistent with `IsRigidBodySpaces`). + +## Applicability to NeoPZ +Reference semantics for polygonal partitions (quadtree/Voronoi imports), scaling-center triangulation of polygons, and the role of `EHDivConstant` in making subdomain condensation exact. Feeds invariants for [[mhm]] and expected convergence for Phase 7 validation gaps. + +## Limits of applicability +Paper-level; the at-pin code may implement a later/earlier variant. Venue/year still to pin down (marked draft). + +## Related wiki pages +[[mhm]] · [[hdiv-space]] · [[flow-mhm-hdivconstant]] · [[mixed-methods]] + +## Open questions +- Exact bibliographic detail + whether the divergence super-convergence is tested anywhere in-tree (Phase 7).