Consolidate numerical research and preserve a reproducible handoff
Document the baseline, hypotheses, measured results, failed approaches, current policy defaults, and remaining rotating n=3 and virial limitations. Include the authoritative LaTeX report, Pandoc-generated Markdown, compiled PDF, source provenance, branch decisions, and consolidation validation. Organize raw results and miscellaneous artifacts under working/ without deleting them; version the directory guide, relocation hashes, archive verifier, and report build/conversion checks. Keep build caches at their original paths and clearly distinguish retained binaries from the validated research build. Preserve experimental policies without promoting failed trials to defaults.
This commit is contained in:
@@ -0,0 +1,934 @@
|
||||
# EOS relation architecture and migration plan
|
||||
|
||||
**Status:** design proposal for review
|
||||
**Date:** 2026-08-29
|
||||
**Scope:** equation-of-state architecture required before improving the surface prescription and wiring it into the nonlinear residual/Jacobian
|
||||
**Implementation status:** no MeanField source code has been changed by this document
|
||||
|
||||
## Executive decision
|
||||
|
||||
Replace the current universal virtual `EquationOfState` interface with a two-layer design built from one EOS declaration:
|
||||
|
||||
1. A **compile-time relation catalog** gives concrete EOS types strongly typed thermodynamic quantities and explicitly lists the relations they support.
|
||||
2. A **generated runtime view** type-erases any conforming concrete EOS and exposes the same catalog through checked runtime queries and evaluation.
|
||||
|
||||
The compile-time catalog is the source of truth. The runtime capability table and dispatch logic are generated from it; an EOS author does not maintain a second virtual interface by hand.
|
||||
|
||||
For the surface, the user-facing condition remains physically isobaric:
|
||||
|
||||
```cpp
|
||||
using Isobaric = ConstantSurface<eos::quantity::Pressure>;
|
||||
```
|
||||
|
||||
The current formulation identifies enthalpy as the carrier field whose boundary row can be replaced. A generic surface compiler asks the EOS for a relation that solves that carrier in terms of the prescribed pressure and any other required local state quantities. For a polytrope, the declared relation is
|
||||
|
||||
\[
|
||||
h = h(P),
|
||||
\]
|
||||
|
||||
so the compiled residual happens to be \(h-h(P_*)\). For a more general EOS it may be
|
||||
|
||||
\[
|
||||
h = h(P,s,Y_e),
|
||||
\]
|
||||
|
||||
so the compiled residual is
|
||||
|
||||
\[
|
||||
h-h(P_*,s,Y_e),
|
||||
\]
|
||||
|
||||
and the surface enthalpy is not constant. There is therefore no public `ConstantEnthalpy` condition and no semantically misleading `targetEnthalpy` in the resolved surface data.
|
||||
|
||||
Only one surface-enforcement mechanism is proposed now: **replacement of the existing boundary rows associated with the selected carrier field**. No `SurfaceEnforcementKind` enum and no Lagrange-multiplier placeholder should be introduced.
|
||||
|
||||
## Design goals
|
||||
|
||||
The design must provide all of the following:
|
||||
|
||||
- A constant-pressure surface is represented as such in the type system.
|
||||
- Passing a density where a pressure is expected is a compile-time error.
|
||||
- A templated algorithm can require a particular EOS relation or derivative at compile time.
|
||||
- A heterogeneous algorithm can accept different EOS implementations through one runtime type.
|
||||
- Runtime consumers can inspect capabilities before evaluation and receive structured errors when a capability or input is invalid.
|
||||
- The runtime contract cannot drift from the compile-time contract.
|
||||
- Multi-input relations are first-class; the architecture must not assume that pressure, density, and enthalpy are globally related by unary functions.
|
||||
- Current polytropic formulas, exterior continuation, validation behavior, and derivative behavior are preserved during migration.
|
||||
- Hot quadrature paths can continue to use statically dispatched concrete EOS code.
|
||||
- The EOS migration can be completed and tested before surface assembly or nonlinear-solver wiring changes.
|
||||
|
||||
## Non-goals for this migration
|
||||
|
||||
- Adding temperature-, entropy-, or composition-dependent production EOS implementations.
|
||||
- Introducing a units library. Quantity types will prevent category mistakes, but their stored scalar remains the code's current `double` in the existing unit convention.
|
||||
- Choosing between Lagrange multipliers, penalties, Nitsche terms, or other surface enforcement schemes.
|
||||
- Wiring surface rows into `PreparedStellarEquilibriumOperator`.
|
||||
- Changing the six-field nonlinear block layout.
|
||||
- Generalizing every prepared operator to every possible EOS in the first patch series.
|
||||
- Implementing automatic relation composition through arbitrary graph paths. Exact declared relations are sufficient and easier to diagnose.
|
||||
|
||||
## Current state and why it needs to change
|
||||
|
||||
### Current EOS contract
|
||||
|
||||
`libmeanfield/interface/eos/eos_base.cppm` defines one abstract class with eight virtual methods. Five are value relations and three are derivatives. The interface assumes that every EOS can provide unary, globally single-valued transformations such as `enthalpy_from_pressure(double)` and `pressure_from_enthalpy(double)`.
|
||||
|
||||
That is true for the current barotropic polytrope, but it is not a valid universal EOS contract. A general EOS may require entropy, temperature, composition, or another branch coordinate. For example, `h(P)` may not exist while `h(P,s,Y_e)` does.
|
||||
|
||||
The use of raw `double` also means that the compiler cannot distinguish pressure, density, and enthalpy arguments.
|
||||
|
||||
### Current static and dynamic usage
|
||||
|
||||
Most numerical production code already takes `const eos::Polytrope&` directly:
|
||||
|
||||
- barotropic-closure kernels and their prepared operator,
|
||||
- pressure-force kernels and their prepared operator,
|
||||
- displacement and stellar-equilibrium preparation.
|
||||
|
||||
The virtual base is concentrated in:
|
||||
|
||||
- `StructureBase::equationOfState()`,
|
||||
- `StellarModel::equationOfState()`,
|
||||
- `SurfaceBase::validate(...)` and `SurfaceBase::resolve(...)`.
|
||||
|
||||
This is favorable for migration. The hot numerical paths can adopt typed relation calls without first adopting runtime dispatch. The model and surface boundaries can then move to the generated runtime view or retain concrete types as appropriate.
|
||||
|
||||
### Current surface resolution
|
||||
|
||||
`Isobaric` stores a target pressure, but resolves it immediately through the virtual `enthalpy_from_pressure` method. `ResolvedSurfaceCondition` then stores only `targetEnthalpy` and exposes
|
||||
|
||||
\[
|
||||
R_\mathrm{surface}=h-h_*, \qquad J_\mathrm{surface}\,\delta h=\delta h.
|
||||
\]
|
||||
|
||||
This loses the physical identity of the prescription and assumes there is one scalar surface enthalpy. That assumption does not survive a general EOS.
|
||||
|
||||
The root prepared operator currently consumes the target mass from `StellarModel`, but it does not consume or assemble the resolved surface condition. The enthalpy space retains stellar-surface degrees of freedom and an isobaric surface quadrature term exists, but surface DOF selection, boundary-row replacement, residual insertion, and Jacobian insertion are not yet wired.
|
||||
|
||||
## Layer 1: strongly typed thermodynamic quantities
|
||||
|
||||
### Quantity tags and values
|
||||
|
||||
Define quantity identity separately from scalar storage:
|
||||
|
||||
```cpp
|
||||
namespace mean_field::eos::quantity {
|
||||
struct Density;
|
||||
struct Pressure;
|
||||
struct SpecificEnthalpy;
|
||||
struct Entropy;
|
||||
|
||||
template<class Species>
|
||||
struct MassFraction;
|
||||
}
|
||||
|
||||
template<class Quantity>
|
||||
class Value final {
|
||||
public:
|
||||
explicit constexpr Value(double value) noexcept : m_value(value) {}
|
||||
[[nodiscard]] constexpr double value() const noexcept { return m_value; }
|
||||
|
||||
private:
|
||||
double m_value;
|
||||
};
|
||||
|
||||
using DensityValue = Value<quantity::Density>;
|
||||
using PressureValue = Value<quantity::Pressure>;
|
||||
using EnthalpyValue = Value<quantity::SpecificEnthalpy>;
|
||||
```
|
||||
|
||||
The constructor should not impose a universal sign or finiteness rule. Domain rules belong to individual relations. This matters because the current polytrope intentionally extends `rho(h)` and `P(h)` into the exterior by returning zero for finite `h <= 0`, while negative density and pressure inputs are rejected.
|
||||
|
||||
The initial migration can use explicit `.value()` extraction at interfaces to MFEM and XAD. A future units system can replace the scalar representation without changing relation identity.
|
||||
|
||||
### Typed derivatives
|
||||
|
||||
Derivative results should retain both numerator and denominator quantities:
|
||||
|
||||
```cpp
|
||||
template<class OutputQuantity, class InputQuantity>
|
||||
class PartialDerivative final {
|
||||
public:
|
||||
explicit constexpr PartialDerivative(double value) noexcept;
|
||||
[[nodiscard]] constexpr double value() const noexcept;
|
||||
};
|
||||
```
|
||||
|
||||
This makes `dP/dh`, `dP/drho`, and `drho/dh` different C++ types. It prevents a derivative with the right numerical representation but the wrong physical meaning from being substituted accidentally.
|
||||
|
||||
## Layer 2: the compile-time relation catalog
|
||||
|
||||
### Relation signatures
|
||||
|
||||
A relation describes an output quantity and an ordered list of input quantities:
|
||||
|
||||
```cpp
|
||||
template<class OutputQuantity, class... InputQuantities>
|
||||
struct Relation final {
|
||||
using Output = OutputQuantity;
|
||||
using Inputs = TypeList<InputQuantities...>;
|
||||
};
|
||||
|
||||
template<class... Relations>
|
||||
struct RelationSet final {};
|
||||
```
|
||||
|
||||
Useful aliases make diagnostics and implementation readable:
|
||||
|
||||
```cpp
|
||||
using PressureFromDensity =
|
||||
Relation<quantity::Pressure, quantity::Density>;
|
||||
|
||||
using PressureFromEnthalpy =
|
||||
Relation<quantity::Pressure, quantity::SpecificEnthalpy>;
|
||||
|
||||
using EnthalpyFromPressure =
|
||||
Relation<quantity::SpecificEnthalpy, quantity::Pressure>;
|
||||
```
|
||||
|
||||
Multi-input relations use the same representation:
|
||||
|
||||
```cpp
|
||||
using EnthalpyFromPressureEntropyComposition = Relation<
|
||||
quantity::SpecificEnthalpy,
|
||||
quantity::Pressure,
|
||||
quantity::Entropy,
|
||||
quantity::MassFraction<Electron>
|
||||
>;
|
||||
```
|
||||
|
||||
Inputs are ordered because evaluation needs a stable calling convention. Composition components should use species-specific quantity tags, so a relation never needs two indistinguishable generic `MassFraction` arguments.
|
||||
|
||||
### Concrete EOS declaration
|
||||
|
||||
`Polytrope` declares exactly the value relations it supports and implements typed overloads selected by relation tag:
|
||||
|
||||
```cpp
|
||||
class Polytrope final {
|
||||
public:
|
||||
using Relations = RelationSet<
|
||||
Relation<quantity::Pressure, quantity::Density>,
|
||||
Relation<quantity::Pressure, quantity::SpecificEnthalpy>,
|
||||
Relation<quantity::SpecificEnthalpy, quantity::Density>,
|
||||
Relation<quantity::SpecificEnthalpy, quantity::Pressure>,
|
||||
Relation<quantity::Density, quantity::SpecificEnthalpy>
|
||||
>;
|
||||
|
||||
[[nodiscard]] PressureValue
|
||||
evaluate(PressureFromDensity, DensityValue density) const;
|
||||
|
||||
[[nodiscard]] PartialDerivative<quantity::Pressure, quantity::Density>
|
||||
partial(PressureFromDensity, Wrt<quantity::Density>, DensityValue density) const;
|
||||
|
||||
// Remaining declared relation and derivative overloads follow the same form.
|
||||
};
|
||||
```
|
||||
|
||||
The public customization point is concise at call sites:
|
||||
|
||||
```cpp
|
||||
const PressureValue pressure =
|
||||
eos::evaluate<eos::quantity::Pressure>(equationOfState, density);
|
||||
|
||||
const auto derivative =
|
||||
eos::partial<eos::quantity::Pressure, eos::quantity::SpecificEnthalpy>(
|
||||
equationOfState,
|
||||
enthalpy
|
||||
);
|
||||
```
|
||||
|
||||
The customization point constructs the exact `Relation<Output, Inputs...>` from its typed arguments, verifies that the relation appears once in `EOS::Relations`, and dispatches to the matching member overload.
|
||||
|
||||
There is no name such as `IsobaricReduction<Polytrope>`. The EOS declares thermodynamic relations only. It has no dependency on the surface subsystem.
|
||||
|
||||
### EOS and algorithm concepts
|
||||
|
||||
The base EOS concept checks structural consistency:
|
||||
|
||||
```cpp
|
||||
template<class Candidate>
|
||||
concept EquationOfStateModel = requires {
|
||||
typename std::remove_cvref_t<Candidate>::Relations;
|
||||
} && ValidRelationSet<typename std::remove_cvref_t<Candidate>::Relations>
|
||||
&& ImplementsEveryDeclaredRelation<std::remove_cvref_t<Candidate>>;
|
||||
```
|
||||
|
||||
The relation set validator should reject:
|
||||
|
||||
- duplicate signatures,
|
||||
- non-quantity types,
|
||||
- missing `evaluate` overloads,
|
||||
- incorrect output types.
|
||||
|
||||
C++ cannot generally reflect over arbitrary extra member overloads. An EOS may therefore contain an undeclared implementation detail, but the public customization point and runtime adapter must refuse to expose it unless its signature appears in `Relations`. The catalog, rather than the set of discoverable member names, defines the public capability set.
|
||||
|
||||
Derivatives are capabilities of individual relations, not a requirement imposed on every EOS relation. Algorithms state what they need:
|
||||
|
||||
```cpp
|
||||
template<class EOS>
|
||||
concept BarotropicClosureEOS =
|
||||
EquationOfStateModel<EOS> &&
|
||||
HasRelation<EOS, Relation<quantity::Density, quantity::SpecificEnthalpy>> &&
|
||||
HasPartial<EOS,
|
||||
Relation<quantity::Density, quantity::SpecificEnthalpy>,
|
||||
quantity::SpecificEnthalpy>;
|
||||
```
|
||||
|
||||
Likewise, the pressure-force operator can require `P(h)` and `dP/dh`, while seed construction can require `h(rho)`. A concrete EOS that lacks one of those capabilities can still satisfy the general `EquationOfStateModel` concept and be used by algorithms whose requirements it meets.
|
||||
|
||||
This is the core compile-time enforcement: requirements are local to consumers rather than falsely universal.
|
||||
|
||||
### Evaluation errors and numerical domains
|
||||
|
||||
Type correctness does not imply that a numerical input lies in a relation's domain. Introduce one EOS-domain exception family for statically dispatched code and a corresponding structured error for runtime calls:
|
||||
|
||||
```cpp
|
||||
enum class EosErrorCode {
|
||||
unsupported_relation,
|
||||
unsupported_derivative,
|
||||
wrong_input_count,
|
||||
wrong_input_quantity,
|
||||
nonfinite_input,
|
||||
outside_domain,
|
||||
nonfinite_result
|
||||
};
|
||||
```
|
||||
|
||||
Typed `evaluate`/`partial` may throw a specific `EosEvaluationError` carrying this code. This preserves the current convenient kernel API and existing exception semantics. The runtime view catches only the standardized EOS exception and returns `std::expected<..., EosError>`; unrelated exceptions remain programming failures and are not silently reclassified.
|
||||
|
||||
The first migration must preserve these current polytropic domain choices exactly:
|
||||
|
||||
- finite negative density: rejected,
|
||||
- finite negative pressure: rejected,
|
||||
- nonfinite inputs: rejected,
|
||||
- finite `h <= 0` for `rho(h)` and `P(h)`: zero exterior continuation,
|
||||
- derivative values at `h = 0`, including the special `n = 1` behavior: unchanged.
|
||||
|
||||
## Layer 3: generated runtime EOS view
|
||||
|
||||
### Why a generated type-erased view
|
||||
|
||||
A monolithic virtual base makes every virtual member a promise made by every EOS. That recreates the current problem as soon as a general EOS lacks a unary transformation.
|
||||
|
||||
Instead, use a small non-owning `EquationOfStateView`, analogous to `std::span` or `std::function_ref`. It can refer to any concrete type satisfying the compile-time EOS concept:
|
||||
|
||||
```cpp
|
||||
class EquationOfStateView final {
|
||||
public:
|
||||
template<EquationOfStateModel EOS>
|
||||
EquationOfStateView(EOS& eos) noexcept; // lvalues only; stores a const view
|
||||
|
||||
[[nodiscard]] std::span<const RelationDescriptor> relations() const noexcept;
|
||||
|
||||
template<class OutputQuantity, class... InputQuantities>
|
||||
[[nodiscard]] bool supports() const noexcept;
|
||||
|
||||
template<class OutputQuantity, class... InputQuantities>
|
||||
[[nodiscard]] std::expected<Value<OutputQuantity>, EosError>
|
||||
tryEvaluate(Value<InputQuantities>... inputs) const;
|
||||
|
||||
template<class OutputQuantity, class WrtQuantity, class... InputQuantities>
|
||||
[[nodiscard]] std::expected<PartialDerivative<OutputQuantity, WrtQuantity>, EosError>
|
||||
tryPartial(Value<InputQuantities>... inputs) const;
|
||||
};
|
||||
```
|
||||
|
||||
This lets one ordinary function accept different EOS types:
|
||||
|
||||
```cpp
|
||||
std::expected<PressureValue, EosError>
|
||||
pressureAtDensity(EquationOfStateView eos, DensityValue density) {
|
||||
return eos.tryEvaluate<quantity::Pressure>(density);
|
||||
}
|
||||
```
|
||||
|
||||
The function remains strongly typed at its own boundary. The only check deferred to runtime is whether the erased concrete EOS supports `P(rho)`.
|
||||
|
||||
### Runtime identity and descriptors
|
||||
|
||||
Runtime descriptors use stable quantity identifiers, not `typeid` names:
|
||||
|
||||
```cpp
|
||||
enum class QuantityId {
|
||||
density,
|
||||
pressure,
|
||||
specific_enthalpy,
|
||||
entropy,
|
||||
// Explicitly registered composition quantities follow.
|
||||
};
|
||||
|
||||
struct RelationDescriptor final {
|
||||
QuantityId output;
|
||||
std::span<const QuantityId> inputs;
|
||||
std::uint64_t availablePartialMask; // bit i corresponds to input i
|
||||
};
|
||||
```
|
||||
|
||||
`QuantityTraits<Q>::id` provides the compile-time-to-runtime mapping. These identifiers should be treated as stable public values if they are ever serialized or exposed in diagnostics.
|
||||
|
||||
The erased implementation stores:
|
||||
|
||||
- a `const void*` to the concrete EOS,
|
||||
- a pointer to a static generated descriptor table,
|
||||
- generated function pointers for relation evaluation and partial evaluation.
|
||||
|
||||
The dispatcher compares an exact relation key, reconstructs typed values, and invokes the same `eos::evaluate` or `eos::partial` customization point used by static code.
|
||||
|
||||
### One source of truth
|
||||
|
||||
The adapter for `EquationOfStateView{polytrope}` is generated by iterating `Polytrope::Relations`. It must not contain a second handwritten list of supported functions. Consequently:
|
||||
|
||||
- a declared-but-unimplemented relation fails compilation,
|
||||
- an undeclared relation is not exposed by the public customization point or runtime view,
|
||||
- runtime descriptors exactly match compile-time declarations,
|
||||
- runtime dispatch cannot claim a relation the static EOS does not have,
|
||||
- derivative availability is generated with `requires` checks against each relation/input pair.
|
||||
|
||||
This is the most important runtime-contract guarantee.
|
||||
|
||||
### Ownership
|
||||
|
||||
Start with the non-owning view only. It is sufficient for the current model, which owns its structure prescription and keeps the contained EOS at a stable address. The view's lifetime contract must be explicit and tested.
|
||||
|
||||
If heterogeneous EOS ownership becomes necessary, add `AnyEquationOfState` later as an owning wrapper whose view uses the same generated adapter. It should not be required for the first migration.
|
||||
|
||||
### Where to use static and runtime dispatch
|
||||
|
||||
Use concrete EOS types and compile-time concepts in:
|
||||
|
||||
- quadrature kernels,
|
||||
- prepared closure and pressure operators,
|
||||
- surface-constraint compilation,
|
||||
- derivative-sensitive nonlinear and preconditioner code.
|
||||
|
||||
Use `EquationOfStateView` in:
|
||||
|
||||
- heterogeneous collections,
|
||||
- logging, diagnostics, inspection, and configuration boundaries,
|
||||
- non-templated model views,
|
||||
- functions that genuinely need to accept unrelated EOS concrete types through one ABI.
|
||||
|
||||
Runtime erasure should not be forced into every quadrature-point evaluation merely to make an outer API non-templated.
|
||||
|
||||
## Surface architecture enabled by the EOS relations
|
||||
|
||||
### Physical prescription type
|
||||
|
||||
Represent a constant thermodynamic surface by the quantity being prescribed:
|
||||
|
||||
```cpp
|
||||
template<class Quantity>
|
||||
class ConstantSurface final {
|
||||
public:
|
||||
using PhysicalQuantity = Quantity;
|
||||
|
||||
explicit ConstantSurface(Value<Quantity> target);
|
||||
[[nodiscard]] Value<Quantity> target() const noexcept;
|
||||
};
|
||||
|
||||
using Isobaric = ConstantSurface<eos::quantity::Pressure>;
|
||||
```
|
||||
|
||||
Thus `Isobaric` is a pressure prescription at compile time and continues to store a pressure value at runtime. A pressure target cannot be constructed from an `EnthalpyValue` accidentally.
|
||||
|
||||
No public constant-enthalpy surface is introduced as part of this work.
|
||||
|
||||
### The formulation chooses the carrier; the EOS supplies the relation
|
||||
|
||||
The current nonlinear formulation already has an enthalpy unknown and a hydrostatic residual row. The planned row-replacement enforcement therefore identifies the enthalpy field as the **carrier field** for a scalar thermodynamic surface condition.
|
||||
|
||||
This is a property of the equation formulation and its block layout, not a property of an isobaric condition and not a property of a polytrope.
|
||||
|
||||
Given:
|
||||
|
||||
- a physical condition `ConstantSurface<Pressure>`,
|
||||
- carrier quantity `SpecificEnthalpy`,
|
||||
- the surface field bindings available in the formulation,
|
||||
- a concrete EOS relation catalog,
|
||||
|
||||
the generic compiler searches for one declared relation satisfying all of these conditions:
|
||||
|
||||
1. Its output is the carrier quantity.
|
||||
2. The prescribed physical quantity occurs exactly once among its inputs.
|
||||
3. Every other input is bound to a field or parameter available on the surface.
|
||||
4. Every other state-dependent input has the partial derivative needed for the Jacobian.
|
||||
5. Exactly one relation matches.
|
||||
|
||||
The selection rule is independent of the names `Isobaric` and `Polytrope`.
|
||||
|
||||
For the current polytrope, the match is `h(P)`. For a general EOS it could be `h(P,s,Y_e)`. If there is no match, the model is not compatible with this formulation and compilation fails with a diagnostic listing the missing relation. If multiple relations match, compilation fails as ambiguous; the formulation must supply a more specific set of bindings or an explicit coordinate policy.
|
||||
|
||||
The first implementation should not silently fall back to the direct equation `P(state)-P*`. At `P*=0` the current polytrope has `dP/dh = rho = 0`, producing a degenerate Newton row. Requiring a relation that solves for the carrier gives the intended identity pivot without inventing an enforcement-mode hierarchy.
|
||||
|
||||
### Compiled constraint data
|
||||
|
||||
Use the name `CompiledConstantSurfaceConstraint`, not `ConstantTraceConstraint`. “Trace” is a finite-element term for restricting a volume field to a boundary. It may appear in low-level MFEM implementation comments, but it should not define the public physical API.
|
||||
|
||||
A representative typed result is:
|
||||
|
||||
```cpp
|
||||
template<
|
||||
class PhysicalQuantity,
|
||||
class CarrierField,
|
||||
class SelectedRelation,
|
||||
class Dependencies>
|
||||
class CompiledConstantSurfaceConstraint final {
|
||||
public:
|
||||
using PhysicalCondition = ConstantSurface<PhysicalQuantity>;
|
||||
using Relation = SelectedRelation;
|
||||
using SurfaceDependencies = Dependencies;
|
||||
|
||||
[[nodiscard]] Value<PhysicalQuantity> target() const noexcept;
|
||||
|
||||
template<class SurfaceState>
|
||||
[[nodiscard]] double residual(const SurfaceState& state) const;
|
||||
|
||||
template<class SurfaceState, class SurfaceVariation>
|
||||
[[nodiscard]] double jacobianAction(
|
||||
const SurfaceState& state,
|
||||
const SurfaceVariation& variation
|
||||
) const;
|
||||
};
|
||||
```
|
||||
|
||||
The compiled object retains the physical target and the selected EOS relation. It does not expose or semantically store a `targetEnthalpy`.
|
||||
|
||||
For the polytrope, an implementation may privately cache the constant numerical value `h(P*)` as an optimization. That cache is not the condition's identity. For `h(P,s,Y_e)`, the right-hand side is evaluated from local boundary state and cannot be one global scalar.
|
||||
|
||||
### Surface dependencies
|
||||
|
||||
Dependencies should exist in both typed and runtime forms:
|
||||
|
||||
```cpp
|
||||
template<class ResidualField, class... ReadFields>
|
||||
struct SurfaceConstraintDependencies final {
|
||||
using RowField = ResidualField;
|
||||
using StateFields = FieldSet<ReadFields...>;
|
||||
};
|
||||
```
|
||||
|
||||
For the polytrope's `h(P*)` relation:
|
||||
|
||||
```cpp
|
||||
SurfaceConstraintDependencies<field::Enthalpy, field::Enthalpy>
|
||||
```
|
||||
|
||||
The first `field::Enthalpy` means that enthalpy boundary rows are replaced. The second means the residual reads the surface enthalpy value. A more general `h(P*,s,Y_e)` relation yields:
|
||||
|
||||
```cpp
|
||||
SurfaceConstraintDependencies<
|
||||
field::Enthalpy,
|
||||
field::Enthalpy,
|
||||
field::Entropy,
|
||||
field::ElectronFraction
|
||||
>
|
||||
```
|
||||
|
||||
The Jacobian dependencies are derived mechanically from the selected relation:
|
||||
|
||||
\[
|
||||
\delta R = \delta h
|
||||
-\frac{\partial h}{\partial s}\,\delta s
|
||||
-\frac{\partial h}{\partial Y_e}\,\delta Y_e.
|
||||
\]
|
||||
|
||||
At runtime, the prepared operator needs a compact equivalent:
|
||||
|
||||
```cpp
|
||||
struct RuntimeSurfaceConstraintDependencies final {
|
||||
field::FieldId rowField;
|
||||
std::vector<field::FieldId> stateFields;
|
||||
};
|
||||
```
|
||||
|
||||
The field IDs feed block dependency declaration and Jacobian assembly. They are generated from the typed dependencies, not maintained independently.
|
||||
|
||||
### Physical runtime description
|
||||
|
||||
If a non-templated model view needs to report the prescribed condition, use:
|
||||
|
||||
```cpp
|
||||
struct ConstantSurfaceDescriptor final {
|
||||
eos::QuantityId physicalQuantity;
|
||||
double target;
|
||||
};
|
||||
```
|
||||
|
||||
This replaces a closed `SurfacePhysicalKind` enum. The quantity identity already says that the condition is constant pressure, constant temperature, and so on. The typed API remains the authority; this descriptor is for runtime inspection.
|
||||
|
||||
### Enforcement
|
||||
|
||||
Do not add `SurfaceEnforcementKind` now. The first surface assembler will do one thing:
|
||||
|
||||
- find the stellar-surface DOFs of the carrier field,
|
||||
- replace the corresponding existing residual rows with the compiled constraint,
|
||||
- replace the corresponding Jacobian rows with derivatives declared by the compiled dependencies.
|
||||
|
||||
This keeps the existing six blocks and preserves the nonlinear unknown count. Lagrange multipliers would add unknowns, residuals, couplings, null-space questions, and preconditioner blocks. If they are ever needed, they should arrive as a deliberate new formulation, not as an enum value that suggests the current assembler can support them.
|
||||
|
||||
## Proposed module and file layout
|
||||
|
||||
The names below are concrete recommendations; small naming adjustments are acceptable if module-build constraints require them.
|
||||
|
||||
```text
|
||||
libmeanfield/interface/eos/
|
||||
quantities.cppm Quantity tags, Value, PartialDerivative, QuantityId
|
||||
relations.cppm Relation, RelationSet, aliases, relation-list utilities
|
||||
concepts.cppm EquationOfStateModel and per-algorithm capability concepts
|
||||
evaluation.cppm evaluate/partial customization points and EOS errors
|
||||
runtime.cppm EquationOfStateView and generated adapters
|
||||
polytropic.cppm Polytrope and its declared relation implementations
|
||||
|
||||
libmeanfield/interface/surface/
|
||||
constant.cppm ConstantSurface<Q> and Isobaric alias
|
||||
dependencies.cppm Typed/runtime SurfaceConstraintDependencies
|
||||
compiled.cppm CompiledConstantSurfaceConstraint
|
||||
compiler.cppm Generic condition + carrier + EOS relation selection
|
||||
```
|
||||
|
||||
During compatibility phases, `eos_base.cppm`, `surface_base.cppm`, and the current `isobaric.cppm` remain temporarily and forward to the new API. They are removed only after all call sites have migrated.
|
||||
|
||||
`CMakeLists.txt` must list each new C++ module partition explicitly and add the new test translation units. The project already requires C++23, so `std::expected` is available.
|
||||
|
||||
## Test plan
|
||||
|
||||
The tests are grouped by the guarantee they protect. Negative compile-time cases should use concepts and `requires` expressions so the normal test target still compiles; no separate intentionally failing build is required initially.
|
||||
|
||||
### 1. Quantity-type tests
|
||||
|
||||
Suggested file: `tests/eos/quantities.cpp`
|
||||
|
||||
- `DensityValue`, `PressureValue`, and `EnthalpyValue` are distinct types.
|
||||
- A relation accepting `PressureValue` is not invocable with `EnthalpyValue`.
|
||||
- `PartialDerivative<Pressure, Enthalpy>` is not convertible to `PartialDerivative<Pressure, Density>`.
|
||||
- Explicit scalar extraction is required at raw numerical-library boundaries.
|
||||
- Value wrappers preserve the underlying scalar exactly and do not impose incorrect universal domain validation.
|
||||
|
||||
### 2. Compile-time relation-contract tests
|
||||
|
||||
Suggested file: `tests/eos/relation_contract.cpp`
|
||||
|
||||
- `Polytrope` satisfies `EquationOfStateModel`.
|
||||
- Its five current value-relation signatures are present exactly once.
|
||||
- Unsupported signatures such as `rho(P,s)` are absent.
|
||||
- `evaluate<Pressure>(polytrope, DensityValue)` returns `PressureValue`.
|
||||
- `evaluate<Pressure>(polytrope, EnthalpyValue)` selects a different declared relation.
|
||||
- `partial<Pressure, Enthalpy>(...)` returns the correct derivative type.
|
||||
- A synthetic EOS with a duplicate relation fails `ValidRelationSet`.
|
||||
- A synthetic EOS with a declared but missing implementation fails `EquationOfStateModel`.
|
||||
- A synthetic EOS with a wrong return type fails `EquationOfStateModel`.
|
||||
- A relation can have three or more inputs without any special machinery.
|
||||
|
||||
Representative negative assertions:
|
||||
|
||||
```cpp
|
||||
static_assert(!HasRelation<SyntheticEOS,
|
||||
Relation<quantity::Density, quantity::Pressure, quantity::Entropy>>);
|
||||
|
||||
static_assert(!EquationOfStateModel<DeclaredButNotImplementedEOS>);
|
||||
```
|
||||
|
||||
### 3. Polytrope characterization and numerical tests
|
||||
|
||||
Port and retain the existing coverage in `tests/physics/barotrope.cpp` and `tests/physics/barotrope_pressure.cpp` before deleting legacy method names.
|
||||
|
||||
For every migrated relation:
|
||||
|
||||
- compare against the existing analytic formula over representative `n`, `K`, and state values,
|
||||
- preserve zero values at the stellar surface,
|
||||
- preserve exterior `h < 0` continuation,
|
||||
- preserve invalid-constructor checks,
|
||||
- preserve nonfinite-input and negative-domain errors,
|
||||
- test inverse round trips `rho -> h -> rho` and `P -> h -> P` where defined,
|
||||
- compare each available analytic partial against centered finite differences away from nondifferentiable endpoints,
|
||||
- test the `n = 1`, `h = 0` derivative separately.
|
||||
|
||||
These are characterization tests: migration is not an opportunity to alter formulas or endpoint conventions silently.
|
||||
|
||||
### 4. Runtime-view contract tests
|
||||
|
||||
Suggested file: `tests/eos/runtime.cpp`
|
||||
|
||||
- Construct `EquationOfStateView` from `Polytrope` without allocation or ownership transfer.
|
||||
- The runtime relation descriptors equal the compile-time catalog exactly.
|
||||
- Available-partial flags equal compile-time `HasPartial` results.
|
||||
- Typed and erased evaluation agree for every declared relation.
|
||||
- Typed and erased derivative evaluation agree for every available partial.
|
||||
- An unsupported relation returns `unsupported_relation`.
|
||||
- An unsupported partial returns `unsupported_derivative`.
|
||||
- Raw internal dispatch rejects wrong arity and wrong input quantity.
|
||||
- Domain failures become the corresponding structured `EosError`.
|
||||
- Construction from an EOS temporary is rejected at compile time.
|
||||
- Moving a stable-address model owner leaves an already-created view referring to the same EOS object.
|
||||
- One function taking `EquationOfStateView` successfully evaluates two different synthetic concrete EOS types.
|
||||
|
||||
The final test is the direct proof that heterogeneous runtime consumption works.
|
||||
|
||||
### 5. Per-consumer concept tests
|
||||
|
||||
Suggested file: `tests/eos/consumer_contracts.cpp`
|
||||
|
||||
Define small synthetic EOS types to prove that requirements are local:
|
||||
|
||||
- an EOS with `rho(h)` and `drho/dh` satisfies `BarotropicClosureEOS`,
|
||||
- an EOS lacking `drho/dh` does not,
|
||||
- an EOS with `P(h)` and `dP/dh` satisfies `PressureForceEOS`,
|
||||
- an EOS can satisfy one operator concept without satisfying another,
|
||||
- an EOS can satisfy the general `EquationOfStateModel` concept without providing `h(P)`.
|
||||
|
||||
### 6. Surface-compilation tests
|
||||
|
||||
Suggested file: `tests/surface/constraint_compilation.cpp`
|
||||
|
||||
These tests prepare the surface architecture but do not assemble MFEM rows yet.
|
||||
|
||||
- `Isobaric::PhysicalQuantity` is `quantity::Pressure`.
|
||||
- `Isobaric` accepts `PressureValue` and not `EnthalpyValue`.
|
||||
- With enthalpy as carrier, the generic compiler selects the polytrope's `h(P)` relation without an isobaric or polytrope specialization.
|
||||
- For a polytrope, the compiled residual equals `h-h(P*)` and its carrier Jacobian is one.
|
||||
- The compiled condition still reports its target as pressure.
|
||||
- No public `targetEnthalpy` exists.
|
||||
- A synthetic EOS declaring `h(P,s,Y_e)` produces dependencies on enthalpy, entropy, and electron fraction.
|
||||
- Changing entropy at fixed target pressure changes the computed boundary enthalpy in that synthetic EOS, proving the design does not assume one surface enthalpy.
|
||||
- The Jacobian action for that EOS includes all required partials and agrees with finite differences.
|
||||
- An EOS lacking a relation that solves the chosen carrier fails the `SurfaceCompilable` concept.
|
||||
- Two matching relations produce an ambiguity at compile time rather than an arbitrary selection.
|
||||
- An EOS lacking a required partial for an additional state input fails `SurfaceCompilable`.
|
||||
|
||||
### 7. Regression tests for migrated production consumers
|
||||
|
||||
Existing kernel and prepared-operator suites remain the regression authority:
|
||||
|
||||
- `tests/operators/kernels/barotropic_closure_kernels.cpp`,
|
||||
- `tests/operators/prepared_barotropic_closure.cpp`,
|
||||
- `tests/operators/kernels/pressure_force_kernels.cpp`,
|
||||
- `tests/operators/prepared_pressure_force.cpp`,
|
||||
- displacement and prepared stellar-equilibrium suites,
|
||||
- structure seed and model tests.
|
||||
|
||||
The migration should change how values are requested from the EOS, not the expected residuals, Jacobian actions, quadrature behavior, or tolerances.
|
||||
|
||||
## Migration plan
|
||||
|
||||
Each phase should compile and pass tests independently. Compatibility shims are intentional and temporary.
|
||||
|
||||
### Current-file migration map
|
||||
|
||||
| Current area | Migration action |
|
||||
|---|---|
|
||||
| `libmeanfield/interface/eos/eos_base.cppm` | Keep as a compatibility base through Phases 1–5, then remove. It is not the new runtime contract. |
|
||||
| `libmeanfield/interface/eos/polytropic.cppm` | Add the relation catalog and typed overloads first; make legacy virtual methods forward to them; later remove inheritance and wrappers. |
|
||||
| `libmeanfield/interface/models/structure/structure_base.cppm` | Replace inheritance-only requirements with a structural `StructurePrescription` concept; runtime consumers eventually use a structure/model view. |
|
||||
| `libmeanfield/interface/models/structure/polytropic.cppm` and `libmeanfield/impl/models/polytropic.cpp` | Preserve the concrete `Polytrope` return type, migrate seed construction to typed `h(rho)`, and retain current Lane–Emden behavior. |
|
||||
| `libmeanfield/interface/models/stellar_model.cppm` | Replace immediate prescription erasure with a typed, CTAD-friendly owning model; add `StellarModelView` for runtime heterogeneity. |
|
||||
| `libmeanfield/interface/surface/surface_base.cppm` | Retain only during compatibility; replace `ResolvedSurfaceCondition` with a typed compiled constraint after model/EOS migration. |
|
||||
| `libmeanfield/interface/surface/isobaric.cppm` | Replace the raw-double derived class with `ConstantSurface<Pressure>`; remove `resolveTargetEnthalpy`. |
|
||||
| Barotropic closure interfaces/implementations/kernels | Require `rho(h)` and `drho/dh`; migrate calls without changing residual or Jacobian formulas. |
|
||||
| Pressure-force interfaces/implementations/kernels | Require `P(h)` and `dP/dh`; migrate calls without changing quadrature or linearization. |
|
||||
| Displacement and stellar-equilibrium preparation | Forward the typed EOS or a statically bound evaluator; avoid introducing per-quadrature runtime erasure. |
|
||||
| `libmeanfield/interface/mean_field.cppm` and `CMakeLists.txt` | Export/register new modules in dependency order and add the new test files. |
|
||||
| Existing EOS, surface, model, kernel, and prepared-operator tests | Port incrementally; retain legacy-vs-typed comparison tests until compatibility wrappers are removed. |
|
||||
|
||||
### Phase 0: establish the baseline
|
||||
|
||||
1. Record the exact current test command and result.
|
||||
2. Preserve the dirty working tree; do not mix unrelated existing edits into the EOS patches.
|
||||
3. Ensure the current polytrope domain and endpoint behavior is fully covered before changing its API.
|
||||
4. Add no surface wiring in this phase.
|
||||
|
||||
**Exit criterion:** the legacy behavior is characterized well enough to distinguish migration regressions from intended future changes.
|
||||
|
||||
### Phase 1: add quantity and relation infrastructure beside the old API
|
||||
|
||||
1. Add quantity tags, typed values, typed derivatives, relation signatures, relation sets, and utilities.
|
||||
2. Add EOS errors and the `evaluate`/`partial` customization points.
|
||||
3. Add compile-time validator tests with synthetic EOS types.
|
||||
4. Export the new modules from the main `mean_field` module.
|
||||
5. Leave `EquationOfState` and every current call site untouched.
|
||||
|
||||
**Exit criterion:** the infrastructure is tested but has no numerical behavior change.
|
||||
|
||||
### Phase 2: declare the polytrope relation catalog
|
||||
|
||||
1. Add `Polytrope::Relations` and typed `evaluate`/`partial` overloads.
|
||||
2. Initially keep `Polytrope : EquationOfState`.
|
||||
3. Implement legacy virtual methods as thin conversions to the typed relation API, so formulas have one implementation.
|
||||
4. Port the characterization tests to exercise both APIs and compare their results.
|
||||
5. Preserve all current domain and endpoint behavior.
|
||||
|
||||
**Exit criterion:** `Polytrope` satisfies the new compile-time concept and the legacy API is a forwarding compatibility layer.
|
||||
|
||||
### Phase 3: add the generated runtime view
|
||||
|
||||
1. Implement `QuantityId`, `RelationDescriptor`, generated descriptor tables, and generated dispatch.
|
||||
2. Implement non-owning `EquationOfStateView`.
|
||||
3. Add typed runtime queries and structured errors.
|
||||
4. Test descriptor/catalog equivalence and heterogeneous use.
|
||||
5. Do not put runtime dispatch into hot kernels.
|
||||
|
||||
**Exit criterion:** one non-templated function can safely accept multiple EOS concrete types, and all advertised runtime capabilities are generated from the static catalog.
|
||||
|
||||
### Phase 4: migrate concrete numerical call sites
|
||||
|
||||
Migrate in dependency order:
|
||||
|
||||
1. Polytropic structure seed construction: `h(rho)`.
|
||||
2. Barotropic closure kernels and prepared closure: `rho(h)` and `drho/dh`.
|
||||
3. Pressure-force kernels and prepared pressure operator: `P(h)` and `dP/dh`.
|
||||
4. Displacement and stellar-equilibrium preparation that forwards the EOS.
|
||||
5. Corresponding tests and helpers.
|
||||
|
||||
Initially, these functions may continue taking `const Polytrope&`; replacing raw method names with relation calls still gives typed arguments and relation checks. Introduce per-consumer concepts before generalizing signatures.
|
||||
|
||||
Where a template would force large kernel definitions into exported module interfaces, use either:
|
||||
|
||||
- explicit instantiation for supported library EOS types, or
|
||||
- a small statically bound evaluator object created from the concrete EOS.
|
||||
|
||||
Do not solve module organization by routing every quadrature call through the runtime view.
|
||||
|
||||
**Exit criterion:** production numerical code no longer calls the legacy unary virtual methods directly.
|
||||
|
||||
### Phase 5: preserve concrete types through model construction
|
||||
|
||||
The current `StellarModel` erases `StructureType` and `SurfaceType` immediately. That prevents compile-time EOS/surface compatibility checks.
|
||||
|
||||
Introduce a typed owning model:
|
||||
|
||||
```cpp
|
||||
template<class Structure, class Surface>
|
||||
requires StructurePrescription<Structure> && SurfacePrescription<Surface>
|
||||
class StellarModel final {
|
||||
// unique_ptr<Structure> and unique_ptr<Surface> retain stable addresses
|
||||
};
|
||||
|
||||
template<class Structure, class Surface>
|
||||
StellarModel(Structure, Surface) -> StellarModel<Structure, Surface>;
|
||||
```
|
||||
|
||||
Replace inheritance-only prescription concepts with structural concepts. During transition, `PolytropicStructure::equationOfState()` can use a covariant return of `const Polytrope&` while it still derives from `StructureBase`, allowing typed callers to recover the concrete EOS.
|
||||
|
||||
Add a non-owning `StellarModelView` for functions that genuinely need a uniform runtime type. Its EOS accessor returns `EquationOfStateView`.
|
||||
|
||||
Keep stable-address ownership because prepared operators and contexts borrow EOS/model objects.
|
||||
|
||||
**Exit criterion:** surface compilation sees the concrete surface type and concrete EOS type, while heterogeneous inspection remains possible through runtime views.
|
||||
|
||||
### Phase 6: remove the old universal virtual EOS base
|
||||
|
||||
1. Change remaining model/structure runtime boundaries to `EquationOfStateView`.
|
||||
2. Remove inheritance from `Polytrope`.
|
||||
3. Remove legacy unary wrappers after a repository search confirms no production or test use.
|
||||
4. Remove `eos_base.cppm`; do not reuse the old universal-interface name for an unrelated runtime abstraction.
|
||||
5. Keep the distinct names `EquationOfStateModel` for the concept and `EquationOfStateView` for runtime erasure.
|
||||
|
||||
**Exit criterion:** no API implies that every EOS supplies every unary conversion.
|
||||
|
||||
### Phase 7: migrate the surface prescription, without wiring it yet
|
||||
|
||||
1. Add `ConstantSurface<Q>` and make `Isobaric` an alias or thin named wrapper for `ConstantSurface<Pressure>`.
|
||||
2. Add the formulation's enthalpy-carrier declaration.
|
||||
3. Implement generic relation selection from condition, carrier, available bindings, and EOS catalog.
|
||||
4. Add typed and runtime dependency descriptions.
|
||||
5. Replace `ResolvedSurfaceCondition` with `CompiledConstantSurfaceConstraint` or a similarly typed result.
|
||||
6. Remove public `targetEnthalpy` and preserve physical pressure in the condition and runtime descriptor.
|
||||
7. Add the synthetic multi-input EOS tests described above.
|
||||
8. Do not yet modify root residual/Jacobian assembly.
|
||||
|
||||
**Exit criterion:** a polytropic isobaric condition compiles naturally through `h(P)`, while a multi-input EOS demonstrates a nonconstant surface enthalpy.
|
||||
|
||||
### Phase 8: wire the single enforcement mechanism
|
||||
|
||||
This is deliberately the next project after the EOS migration and surface compilation design are accepted.
|
||||
|
||||
1. Build the stellar-surface DOF map for the carrier field.
|
||||
2. Declare the compiled surface dependencies in the operator block graph.
|
||||
3. Replace the selected hydrostatic residual rows.
|
||||
4. Replace the matching Jacobian rows for every declared dependency.
|
||||
5. Test residual/Jacobian consistency, finite differences, block sparsity, and zero-pressure conditioning.
|
||||
6. Then connect the completed residual/Jacobian to the nonlinear solver and begin preconditioner development.
|
||||
|
||||
## Patch-series boundaries
|
||||
|
||||
The implementation should be reviewable as small patches rather than one architectural rewrite:
|
||||
|
||||
1. Quantity and relation primitives plus tests.
|
||||
2. Typed `Polytrope` relation catalog plus forwarding legacy API.
|
||||
3. Generated `EquationOfStateView` plus tests.
|
||||
4. Structure seed and EOS unit-test migration.
|
||||
5. Closure kernel/operator migration.
|
||||
6. Pressure kernel/operator migration.
|
||||
7. Remaining operator forwarding migration.
|
||||
8. Typed model ownership and runtime model view.
|
||||
9. Removal of the legacy EOS base.
|
||||
10. Typed constant-pressure surface compiler and synthetic general-EOS tests.
|
||||
|
||||
Every patch should leave the test target green. Surface row assembly begins only after this series is complete.
|
||||
|
||||
## Risks and controls
|
||||
|
||||
### Compile-time relation ambiguity
|
||||
|
||||
**Risk:** more than one EOS relation can solve the selected carrier from the prescribed quantity and available surface fields.
|
||||
|
||||
**Control:** require an exact unique match. Make ambiguity a failed concept with a diagnostic listing candidate signatures. Do not select by declaration order.
|
||||
|
||||
### Mistaking a coordinate transform for a physical condition
|
||||
|
||||
**Risk:** `h(P)` could again leak into public state as “constant enthalpy.”
|
||||
|
||||
**Control:** the physical prescription stores `PressureValue`; the compiled constraint stores the selected relation separately; runtime inspection reports pressure; any cached transformed value remains private.
|
||||
|
||||
### Runtime/static contract drift
|
||||
|
||||
**Risk:** a runtime virtual table advertises different capabilities than the concrete EOS.
|
||||
|
||||
**Control:** generate descriptors and dispatch exclusively from `EOS::Relations` and compile-time derivative detection.
|
||||
|
||||
### Template and C++ module build cost
|
||||
|
||||
**Risk:** fully templating large MFEM kernels increases module dependencies and compile time.
|
||||
|
||||
**Control:** migrate relation calls first while retaining concrete `Polytrope` signatures; then use explicit instantiation or small statically bound evaluators for additional production EOS types.
|
||||
|
||||
### Runtime view lifetime
|
||||
|
||||
**Risk:** a non-owning `EquationOfStateView` outlives its concrete EOS.
|
||||
|
||||
**Control:** retain stable-address model ownership, document borrowing, prohibit construction from temporaries, and add lifetime-oriented tests. Add an owning wrapper only when a real ownership use case appears.
|
||||
|
||||
### Accidental change to exterior continuation
|
||||
|
||||
**Risk:** generic domain checking rejects negative enthalpy that the current solver uses to represent the exterior.
|
||||
|
||||
**Control:** values themselves impose no domain; each polytropic relation preserves its existing domain policy; characterization tests cover negative and zero enthalpy.
|
||||
|
||||
### Premature generality in surface enforcement
|
||||
|
||||
**Risk:** an enforcement enum creates abstractions for block layouts that do not exist.
|
||||
|
||||
**Control:** condition types describe physics; the current assembler implements one row-replacement formulation. A future Lagrange-multiplier formulation gets its own architecture if and when required.
|
||||
|
||||
## Acceptance criteria before surface wiring begins
|
||||
|
||||
The EOS migration is complete enough to support the next stage when all of the following are true:
|
||||
|
||||
- `Polytrope` satisfies the compile-time `EquationOfStateModel` relation concept.
|
||||
- Thermodynamic arguments and derivative results are quantity typed.
|
||||
- Consumer concepts express the exact relations and partials each numerical component needs.
|
||||
- A generated `EquationOfStateView` supports heterogeneous runtime consumers and passes catalog-equivalence tests.
|
||||
- No production numerical code calls the legacy universal virtual EOS methods.
|
||||
- The old `EquationOfState` virtual base is removed.
|
||||
- The typed model path retains the concrete EOS and surface prescription through compatibility checking.
|
||||
- `Isobaric` is a constant-pressure type and stores a `PressureValue`.
|
||||
- Surface relation selection is generic over condition quantity, carrier, available fields, and EOS relation catalog.
|
||||
- `ResolvedSurfaceCondition::targetEnthalpy` is gone.
|
||||
- A synthetic `h(P,s,Y_e)` EOS test proves that an isobaric surface need not be isoenthalpic.
|
||||
- All existing closure, pressure-force, displacement, seed, model, and stellar-equilibrium tests pass without numerical regression.
|
||||
- No surface residual/Jacobian rows or nonlinear-solver behavior have been changed yet.
|
||||
|
||||
## Recommended immediate implementation order after review
|
||||
|
||||
Begin with Phases 1–3: quantity/relation primitives, the typed polytrope catalog, and the generated runtime view. Those establish both halves of the contract while compatibility wrappers keep current code working. Then migrate the numerical call sites and typed model ownership before changing the surface types.
|
||||
|
||||
This ordering makes the later isobaric surface a direct consumer of an already-tested EOS relation system, rather than using the surface work to define EOS behavior implicitly.
|
||||
182
reports/sources/original_audits/MeanField_audit_2026-09-16.md
Normal file
182
reports/sources/original_audits/MeanField_audit_2026-09-16.md
Normal file
@@ -0,0 +1,182 @@
|
||||
# MeanField architecture and current-state audit
|
||||
|
||||
Date: September 16, 2026. Repository examined: `/Users/tboudreaux/Programming/4DSTAR/MeanField`.
|
||||
|
||||
## Scope and confidence
|
||||
|
||||
This was a read-only source and artifact audit of the active equilibrium path, its operator, mapping, normalization, preconditioning, solver, seed, test, and experiment infrastructure. No repository files were changed, no solver run was launched, and no fresh build or regression suite was executed. This report is stored in the separate ChatGPT project workspace.
|
||||
|
||||
The checked-out commit is `75cc63873992984966ea20011cc04d9984f54be4`, but the working tree is substantially newer: 49 tracked files differ, with 3,626 additions and 267 deletions, plus untracked experiments, helper code, documentation, and numerical artifacts. The working tree, not HEAD alone, is the object of this audit. Existing modifications were preserved.
|
||||
|
||||
The user's observations—roughly 20 seconds per Newton step at n=1 and zero angular momentum, convergence at low rotation, and plateaus at higher index/rotation—are the current operational baseline. The archived measurements establish some of this independently, but do not establish the current rotation threshold or the cause of the plateau. This audit does not claim exhaustive line-by-line verification of every module or numerical correctness of the entire working tree.
|
||||
|
||||
## Purpose and numerical problem
|
||||
|
||||
MeanField is an experimental numerical test bed intended to inform SERiF/4D-STAR development. The immediate implemented problem is a three-dimensional, self-gravitating, rigidly rotating, barotropic free-boundary equilibrium. The presence of older advection, viscosity, Coriolis, and continuity integrators does not mean those equations participate in the current sandbox solve.
|
||||
|
||||
The polytropic EOS implements
|
||||
|
||||
\[
|
||||
P=K\rho^{1+1/n},\qquad h=(n+1)K\rho^{1/n},\qquad
|
||||
\rho(h)=\left[h/((n+1)K)\right]^n\quad(h\geq0).
|
||||
\]
|
||||
|
||||
The active EOS accepts finite n >= 1 and positive K. Its standalone density-from-enthalpy relation extends to zero density for negative h, but the **prepared closure rejects negative enthalpy at its quadrature points**. This distinction matters when interpreting rejected Newton trials. The independent density field is checked for finiteness in that preparation path; a successful preparation is not itself a global density-positivity certificate.
|
||||
|
||||
With the code's positive rotation potential Psi = |Omega cross (x-center)|^2/2, the hydrostatic equation is the weak form of h + Phi - Psi - C = 0. Gravity uses a mixed gradient–potential formulation, with the stored flux representing grad(Phi), not physical acceleration -grad(Phi). Density closure is weakly enforced in the density test space. Pressure in the mechanical operator is evaluated from enthalpy.
|
||||
|
||||
The shape residual is obtained by first assembling the volume mechanical virtual-work residual and then applying the transpose of the surface-to-volume deformation Jacobian. Its Jacobian includes both the derivative of the mechanical residual and the derivative of this pullback. Consequently, solving the shape equations does not independently force every unrestricted volume mechanical test row to zero.
|
||||
|
||||
The usual sandbox model additionally imposes:
|
||||
|
||||
- Fixed total mass, generating the Bernoulli coordinate C.
|
||||
- Fixed axial angular momentum, generating a scalar angular velocity along a prescribed axis; both density and changing geometry contribute to the inertia derivative.
|
||||
- Fixed central density, implemented through a central **enthalpy** point condition and a hydrostatic border coordinate lambda_c.
|
||||
- Zero surface pressure, compiled to enthalpy boundary rows replacing the corresponding hydrostatic rows.
|
||||
|
||||
Key implementations: [EOS](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/eos/polytropic.cppm), [physical core residual/Jacobian](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_stellar_equilibrium.cpp:795), [central-density border](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/prepared_central_density.cppm:71), [rotation coupling](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/prepared_variadic_stellar_equilibrium.cppm:712).
|
||||
|
||||
## Architecture
|
||||
|
||||
The main flow is: physics specifications -> compiled equilibrium problem and block manifest -> prepared physical operator -> normalized operator and scaled inverse -> FGMRES inside damped Newton -> a report with a borrowed accepted-state view.
|
||||
|
||||
| Layer | Responsibility and current implementation |
|
||||
| --- | --- |
|
||||
| Model declarations | `model::StellarModel` canonicalizes a compile-time specification pack. EOS, surface conditions, integral constraints, and phase conditions declare their own dependencies and contributions. |
|
||||
| Compilation | The compiler derives state/residual blocks, Jacobian edges, manifests, normalization metadata, and prepared specification runtimes. `PreparedVariadicStellarEquilibriumOperator` is the active aggregate. |
|
||||
| Discretization | MFEM parallel spaces on paired physical/logical STROID meshes. Field-support maps distinguish reduced solver coordinates from full MFEM true DOFs. Nonconforming support resolution is explicitly rejected. |
|
||||
| Geometry | Radial surface parameters generate a vector displacement through a default power-law interior extension (power 2) and fixed-infinity vacuum extension. Kelvin compactification represents the exterior through infinity. |
|
||||
| Prepared operators | Cache reference basis information, geometry, thermodynamics, local algebraic blocks, and residuals. Dependency identities/revisions determine invalidation. The global Jacobian is applied without assembling a monolithic matrix. |
|
||||
| Normalization | Frozen reference-geometry diagonal Riesz factors and physical scales from M, reference R, and G. Distinct primal and dual coordinate maps. |
|
||||
| Preconditioning | Material/surface and gravity block approximations, wrapped by a small dense specification-border correction and coordinate permutation/scaling. |
|
||||
| Nonlinear runtime | A context owns the problem, accepted/trial state, normalization, inverse, and linear backend. Trial preparation, acceptance, refresh, rollback, and view invalidation are explicit. |
|
||||
| Validation | Catch2 operator/runtime tests plus separate research experiments and a saved-field physical-validation/replay harness. |
|
||||
|
||||
C++23 modules divide interfaces (`libmeanfield/interface`) from implementations (`libmeanfield/impl`). The build uses MFEM, MPI, Hypre, UMFPACK, STROID, XAD, and other installed dependencies. Several old APIs remain compatibility paths; design/handoff documents are historical evidence and must be checked against current source.
|
||||
|
||||
The default field families are density and potential L2 order 2, gravity RT index 2, and enthalpy/displacement H1 order 3, plus a scalar surface parameter space. A compile-time option increments registered field orders uniformly. The mesh generator uses order-4 geometry; this is not fourth-order approximation for every field.
|
||||
|
||||
The saved coarse n=1 model has 1,216 hex elements (832 stellar, 384 vacuum) and 178,074 root values:
|
||||
|
||||
| Block | Size |
|
||||
| --- | ---: |
|
||||
| Gravity gradient | 98,928 |
|
||||
| Potential | 32,832 |
|
||||
| Density on stellar support | 22,464 |
|
||||
| Surface shape | 866 |
|
||||
| Enthalpy on stellar support | 22,981 |
|
||||
| Three generated scalar coordinates | 3 |
|
||||
|
||||
The root geometry unknown is the surface field, not the much larger full vector displacement. Extension operators and coordinate maps are therefore essential numerical components, not incidental mesh utilities.
|
||||
|
||||
Entry points: [sandbox](/Users/tboudreaux/Programming/4DSTAR/MeanField/sandbox.cpp:92), [equilibrium problem](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/stellar_equilibrium_problem.cppm:118), [field registry](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/field/field_registry.cppm), [default deformation](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/stellar_equilibrium_problem.cppm:317).
|
||||
|
||||
## Normalization and preconditioning
|
||||
|
||||
For a spatial coefficient block with reference Gram diagonal d_i and characteristic physical scale s, normalized state factors are sqrt(d_i)/s and normalized weak-residual factors are 1/(s sqrt(d_i)). Surface pointwise hydrostatic replacement rows receive special treatment; generated global scalar blocks use declared physical scales.
|
||||
|
||||
The wrapper implements x = R x_hat, F_hat = L F, and J_hat = L J R. Its inverse wrapper applies R^-1 P^-1 L^-1. The normalization remains fixed during a solve unless explicitly refreshed. It uses reference computational geometry, including finite reference-domain gravity metrics, rather than an evolving exact physical norm over the infinite exterior. This is a deliberate coordinate policy, not evidence of a missing normalization layer.
|
||||
|
||||
The current default inverse has:
|
||||
|
||||
- Diagonal density and enthalpy approximations, with enthalpy-to-density coupling.
|
||||
- An uncalibrated surface mass/Riesz diagonal and a surface-then-material triangular application.
|
||||
- Independent material/surface and gravity subsystems at the structure level.
|
||||
- Gravity approximate LDU with a fixed order-5 matrix-free Chebyshev H(div) mass inverse and three fixed BoomerAMG cycles for a potential Schur surrogate.
|
||||
- A directly solved small dense border Schur matrix. Its construction uses the approximate structure inverse, so it is **not** the exact Schur complement of the full physical Jacobian.
|
||||
|
||||
Alternative triangular structure couplings, approximate LDU policies, calibrated surface scalars, and a surface mass-plus-stiffness surrogate already exist. The September 3 campaign found that apparently better isolated surface approximations did not improve the full system. It selected the defaults primarily using nonrotating n=3 linearizations and explicitly left rotating/refinement generalization unresolved. Its recommendation to add normalization is historical: normalization is now implemented.
|
||||
|
||||
References: [normalization factors](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/operators.cppm:325), [frozen wrapper](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/stellar_equilibrium.cppm:650), [default structure policy](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/stellar_structure.cppm:850), [surface surrogate](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/material_surface.cppm:1439), [border Schur assembly](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/specification_border.cppm:2333).
|
||||
|
||||
## Newton and initialization
|
||||
|
||||
The seed is a spherical Lane–Emden profile projected into independent density and enthalpy spaces, with a separate mixed gravity solve. Initial shape is zero, C is initialized from -GM/R, and angular velocity from target J divided by spherical inertia. A seed at nonzero target J is therefore not already a rotating equilibrium. The seed requires a compatible spherical reference radius.
|
||||
|
||||
The sandbox currently requests FGMRES restart 40, relative linear tolerance 0.03, at most 200 linear iterations, and at most 30 Newton iterations. The nonlinear criterion is max(atol, rtol times the initial residual), with sandbox atol=0 and rtol=1e-8. This is materially tighter than the saved validation experiment's atol=1e-8: for its initial residual 1.81e-4, the sandbox-style threshold would be about 1.81e-12.
|
||||
|
||||
FGMRES reports a separately recomputed true residual. Newton refuses a correction if that linear solve has not converged, even when it might provide some nonlinear decrease. The forcing tolerance is fixed across Newton steps. Backtracking uses the squared normalized-residual merit, sampled geometry admissibility, and thermodynamic rejection. A geometric preflight estimates safe step length from determinant polynomials at selected sample points. The next linear guess retains (1-alpha) times the previous correction after damping; this is vector reuse, not Krylov recycling.
|
||||
|
||||
Accepted-state refresh and rollback are carefully implemented. However, a successful report certifies **nonlinear residual convergence**, not independently verified physical equilibrium. Capture and serialization methods remain explicit unimplemented stubs. The experiment's saved-field files provide a separate persistence/replay mechanism; its replay currently requires exactly zero rotation.
|
||||
|
||||
References: [Newton loop](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/solver/stellar_context.cppm:1199), [linear solve](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/solver/linear_backend.cppm:720), [Newton options](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/solver/newton.cppm:28), [seed projection](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/seed/stellar_equilibrium_projection.cpp:175).
|
||||
|
||||
## Evidence for present numerical and performance state
|
||||
|
||||
The archived n=1, J=0 benchmark reaches normalized residual 6.60533e-9 in three full Newton steps, with 24, 25, and 28 Krylov iterations. G=M=R=1, K=2/pi, and target central density pi/4. These are actual saved data, not just a README claim.
|
||||
|
||||
| Diagnostic | Archived final value |
|
||||
| --- | ---: |
|
||||
| Relative mass error | 2.36e-11 |
|
||||
| Energy virial error using P(rho) | 3.10e-7 |
|
||||
| Force-based virial error using P(rho) | 3.73e-7 |
|
||||
| Energy virial error using P(h) | 2.62e-7 |
|
||||
| Gravity energy/force consistency | 6.30e-8 |
|
||||
| Density relative volume L2 error | 4.70e-4 |
|
||||
| Enthalpy relative volume L2 error | 3.27e-4 |
|
||||
| Interior potential relative volume L2 error | 1.26e-4 |
|
||||
| Gravity-gradient relative volume L2 error | 5.98e-4 |
|
||||
| Surface-radius RMS error / R | 2.75e-4 |
|
||||
|
||||
Thus the saved model comfortably satisfies the user's 1e-5 virial requirement and also the older 1e-6 screen. Eight existing physical screening checks nevertheless fail. The diagnostic replay finds approximately 1.3% near-surface exterior-potential error; this is outside the interior potential norm above. Weak closure permits pointwise EOS mismatch because rho and h occupy different spaces. The experiment quantitatively demonstrates the n=1 projection contribution to the difference between pressure integrals from h and rho.
|
||||
|
||||
The old problematic mesh had a documented corner folding mechanism missed by production samples. The later saved n=1 solve has healthy sampled geometry and substantially better reference conditioning; it should not be described as suffering the same demonstrated fold. Nevertheless, current production inspection and preflight still use finite quadrature sample sets, not an element-wide positivity proof.
|
||||
|
||||
A one-level refined mesh and analytic geometry control exist. The refined equilibrium output directory contains input mesh, metadata, and analytic checks, but no accepted equilibrium fields or completed equilibrium convergence results. The corresponding report still describes that solve as in progress. I therefore do not infer demonstrated equilibrium h-convergence from it.
|
||||
|
||||
The September 9 optimization report records 1.53x whole-process, 1.70x Newton, and 2.02x linear-solve speedups for that particular batch, with roundoff-level agreement in saved physical metrics. Later working-tree optimizations go substantially further: tensor contractions, compact geometry data, fixed-mesh caches, batched field evaluations, specialized H(div) mass action, cheaper Riesz diagonal assembly, and fixed divergence reuse. The isolation harness documents a later first-Newton-step reference of 24.174 seconds. This is consistent with the user's approximate 10x improvement relative to the old 227–255 second steps, but is not a fresh matched end-to-end benchmark performed here.
|
||||
|
||||
Seven saved isolation-check CSVs contain 1,328 check rows, all marked passed. The latest batch includes 182 passing checks and measured incremental speedups of about 2.12x for pressure displacement action, 6.32x for source displacement action, 4.89x for hydrostatic preparation, and 6.61x for Schur preparation. These are operation-specific measurements with different baselines; they must not be multiplied into a claimed global speedup.
|
||||
|
||||
Validation provenance matters: the archived full-suite XML contains 592 tests, 588 passing and four failing. The failures are centrifugal virial h-refinement geometry, the n=3 projected-seed closure screen, and two-/four-rank MPI groups. The historical report reproduced those failures in preserved earlier binaries; it did not certify the newer September 14 working tree. The current H(div) constructor still requires both a local stellar and a local vacuum representative on every rank, confirming the partition limitation remains in source.
|
||||
|
||||
At audit time, 12 production source files were newer than the release sandbox executable and 30 newer than the release test executable. The isolation harness executable was newer than the inspected production sources. Timestamps are provenance clues, not hashes proving build identity, but they rule out treating the existing sandbox/tests as a demonstrated fresh validation of the latest source.
|
||||
|
||||
Evidence: [saved physical findings](/Users/tboudreaux/Programming/4DSTAR/MeanField/experiments/POLYTROPE_VALIDATION_FINDINGS_2026-09-09.md), [actual screening results](/Users/tboudreaux/Programming/4DSTAR/MeanField/polytrope_solution_2026-09-09/verification_checks.csv), [refinement status](/Users/tboudreaux/Programming/4DSTAR/MeanField/experiments/POLYTROPE_H_CONVERGENCE_2026-09-09.md), [historical full-suite report](/Users/tboudreaux/Programming/4DSTAR/MeanField/performance_optimization_2026-09-09/IMPLEMENTATION_AND_VALIDATION.md), [latest microbenchmarks](/Users/tboudreaux/Programming/4DSTAR/MeanField/final_optimizations_01/summary.txt).
|
||||
|
||||
## Main concerns for the next investigation
|
||||
|
||||
These distinguish observed implementation limitations from hypotheses about the plateau.
|
||||
|
||||
1. **Physical acceptance is separate from solver success.** The default Newton stopping criterion does not require virial balance. The dedicated validation program is currently specialized to single-rank, nonrotating n=1. General physical diagnostics and a 1e-5 acceptance gate are needed for the requested campaign.
|
||||
|
||||
2. **Central-density border and branch compatibility deserve early scrutiny.** The implemented equations are R_c=h(0)-h(rho_c,target) and R_h <- R_h+lambda_c e_c. This is not a direct constraint on the independent DG density at the center. At the saved equilibrium lambda_c is approximately -4.64e-13, with negligible effect on the unbordered residual. Along a rotating sequence, do not assume independently retained K, M, J, and rho_c targets remain compatible with the unmodified physical equations. Measure lambda_c, its normalized residual contribution, and the unbordered hydrostatic residual. This is a formulation question to investigate, not a proven diagnosis of present stagnation.
|
||||
|
||||
3. **The default inverse omits structure-level cross coupling and gives shape only a reference mass surrogate.** Exact Jacobian couplings are present; the approximation is in the inverse. Its adequacy at higher index/deformation must be measured on the actual troublesome Newton right-hand sides. Existing nonrotating policy rankings need not transfer.
|
||||
|
||||
4. **Higher n changes surface sensitivity.** The implemented d rho/d h tends to zero at h=0 for n>1, whereas n=1 has a nonzero one-sided value. Negative quadrature enthalpy triggers trial rejection. Inspect where rejected trials and weak material/shape responses occur rather than assuming the issue is only a Krylov iteration cap.
|
||||
|
||||
5. **Globalization is basic and failure modes need separation.** Fixed linear forcing, restart length, geometry caps, positivity rejection, and merit decrease can each limit progress. A plateau needs block-resolved residuals, true linear residuals, step lengths, and rejection reasons before selecting a remedy. The much tighter sandbox stopping threshold must be recorded in any comparison.
|
||||
|
||||
6. **The critical-rotation target is not yet an implemented acceptance coordinate.** The active sandbox takes angular momentum; some experiments use a reference Keplerian frequency. A declared Omega/Omega_crit convention, equatorial radius, and equatorial effective-gravity diagnostic are needed before labeling a model 50% or 99% critical. These goals are not established by setting a reference frequency fraction alone.
|
||||
|
||||
7. **Geometry safety and spatial accuracy remain independent requirements.** The present sampled geometry can be healthy while the surface and local gravity field are inaccurate. Near-corner/edge inspection and off-interface gravity sampling should accompany deformed models. A low scalar virial error alone cannot certify the spatial solution.
|
||||
|
||||
8. **Current-source regression status must be refreshed.** Rebuild explicit targets before comparing new solves. Maintain the known failure ledger without weakening assertions. Distributed scalability is presently constrained by local-material ownership assumptions, separate from serial nonlinear convergence.
|
||||
|
||||
## Validation additions with the highest immediate value
|
||||
|
||||
For zero surface pressure, preserve the independent requirement
|
||||
|
||||
\[
|
||||
\epsilon_{vir}=\frac{|2T+W+3\Pi|}{|W|}\leq10^{-5},\qquad
|
||||
W=\tfrac12\int\rho\Phi\,dV,\quad\Pi=\int P\,dV.
|
||||
\]
|
||||
|
||||
Evaluate energy- and force-based versions, compare P(h) with P(rho), and vary diagnostic quadrature independently of solve quadrature. If nonzero surface pressure is later enabled, include the boundary-pressure contribution rather than applying the zero-pressure formula unchanged. Do not loosen the existing stricter baseline screens to meet the new minimum requirement.
|
||||
|
||||
The useful next tests are:
|
||||
|
||||
- A reproducible end-to-end baseline and rotating/index sweep recording state, mesh, source/build identity, solver controls, per-block residuals, unbordered residuals, border contribution, geometry minima, thermodynamic minima, and virial diagnostics.
|
||||
- Independent radial Lane–Emden comparisons at additional indices, including a noninteger index, plus completed h/p convergence of accepted fields, shape, and global quantities. Separate reference integration from production seed generation.
|
||||
- Full coupled Jacobian directional checks at accepted nonzero-rotation and higher-index states, including simultaneous angular-velocity, density, enthalpy, and surface perturbations. Use multiple admissible finite-difference step sizes and inspect each block, not just a global norm dominated by gravity.
|
||||
- Rotating sanity checks: mass and angular momentum closure, T=Omega J/2 for the implemented rigid rotation, Bernoulli variation, surface pressure, symmetry/centering, and equatorial effective gravity. Positive/negative spin partners provide a useful symmetry comparison.
|
||||
- Independent finite-radius gravitational flux/Poisson balance and exterior monopole checks, with sampling slightly off mesh/block interfaces. This helps distinguish localized trace effects from finite-volume field errors.
|
||||
- Tensor virial or componentwise force-balance checks to expose anisotropic errors hidden by cancellation in the scalar virial.
|
||||
- A targeted regression for the historical between-sample fold, plus stronger geometric sampling at large deformation. This is distinct from the existing test that rejects an obvious fold.
|
||||
|
||||
## Suggested order of subsequent work
|
||||
|
||||
First establish a freshly built baseline and preserve one reproducible plateau state with complete block and line-search telemetry. Audit target compatibility and border contamination at that state. Then check its full Jacobian and normalization balance before comparing existing and new inverse policies. Introduce continuation through accepted states and adaptive solve controls as measured experiments, retaining cost-to-solution and physical acceptance as the outcomes.
|
||||
|
||||
The intended milestones are understood: robust higher-index equilibria, at least 50% critical rotation, an eventual attempt beyond 99%, and every accepted model virialized to 1e-5 or better. The current infrastructure supports a disciplined investigation, but neither high-rotation convergence nor those models' physical accuracy has yet been demonstrated by the artifacts inspected here.
|
||||
@@ -0,0 +1,206 @@
|
||||
# MeanField: current solver state and plateau diagnosis
|
||||
|
||||
Audit date: 16 September 2026. Repository: `/Users/tboudreaux/Programming/4DSTAR/MeanField`. This report supersedes the earlier read-only convergence assessment with fresh builds and controlled measurements. It does not promote a numerical remedy.
|
||||
|
||||
## Assessment
|
||||
|
||||
MeanField has a working, composable equilibrium operator and a useful experimental solver, with substantial derivative and lifecycle coverage. The present limitation is not one universal “Newton plateau.” The experiments separate **late linear-solve failure at already accurate n=1 states**, **more persistent coupled linear difficulty at higher index**, and **large nonlinear curvature in higher-index corrections**. There is also a distinct physical concern with retaining a prescribed central enthalpy while fixing K, mass and angular momentum.
|
||||
|
||||
The user's primary milestone is the stellar virial error at or below 1e-5. The n=1 cases satisfy it comfortably. The n=1.5 retained state satisfies the enthalpy-pressure virial metric despite remaining algebraically unconverged; it is not yet a validated equilibrium. The n=3 run never leaves its seed, which fails the virial milestone. Exterior pointwise accuracy is not an independent acceptance requirement: exterior changes should be judged by their influence on stellar equilibrium and virial balance.
|
||||
|
||||
**Scope of changes:** one opt-in diagnostic executable and helper headers, plus its build target and documentation. Production operators, preconditioner policies, normalization and solver acceptance rules were not changed. Larger Krylov windows and removal of the central phase were controlled diagnostic comparisons only.
|
||||
|
||||
## Code and architecture
|
||||
|
||||
The active model is a barotropic, rigidly rotating, self-gravitating free-boundary equilibrium in three dimensions. It is not yet a thermal or baroclinic stellar transport model. Its principal equations are mixed gravity, a weak polytropic density closure, Bernoulli balance, reduced mechanical virtual work, and mass/angular-momentum constraints:
|
||||
|
||||
\[
|
||||
\rho(h)=\left[\frac{h}{(n+1)K}\right]^n,\quad
|
||||
P=K\rho^{1+1/n},\quad
|
||||
B=h+\Phi-\tfrac12|\boldsymbol\Omega\times\boldsymbol r|^2-C.
|
||||
\]
|
||||
|
||||
Density and enthalpy are independent finite-element fields, as are potential and the RT gravity-gradient field. Pressure in the mechanical operator comes from h, whereas gravity and rotation forces use the independent density. These represent consistent continuum physics but do not enforce pointwise discrete equality automatically.
|
||||
|
||||
| Layer | Current state |
|
||||
|---|---|
|
||||
| Model and composition | Compile-time specifications generate blocks, scalar coordinates, couplings and a root manifest; the variadic prepared operator is the active aggregate. |
|
||||
| Discretization | MFEM/MPI with supported-field reductions and explicit maps to full true DOFs. C++23 module interfaces are separated from implementations. |
|
||||
| Geometry | A scalar radial surface graph generates interior displacement through a power-2 extension. A Kelvin compactification represents the vacuum through infinity with the outer boundary fixed. |
|
||||
| Operators | Prepared matrix-free Jacobian actions; cached reference tables, geometry, thermodynamics and contractions. Dependency revisions govern invalidation. |
|
||||
| Runtime | Context-owned accepted and trial states, rollback, inverse refresh and stale-view checks; FGMRES inside damped Newton. |
|
||||
| Research infrastructure | Many alternative inverse policies and historical experiments exist. Production checkpoint/continuation capture is unfinished; the new snapshot is an experiment-only frozen-state facility. |
|
||||
|
||||
The campaign used the existing 1,216-hex mesh: 832 stellar and 384 vacuum elements, with order-4 geometry. Default approximation spaces are RT index 2 for gravity, L2 order 2 for potential and density, and H1 order 3 for enthalpy and surface/deformation. The bordered root has 178,074 unknowns: 98,928 gravity, 32,832 potential, 22,464 density, 22,981 enthalpy, 866 surface and three scalar coordinates. Mesh order is not the approximation order of every field.
|
||||
|
||||
Sources: [root composition](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_stellar_equilibrium.cpp:795), [problem/deformation defaults](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/stellar_equilibrium_problem.cppm:317), [context and Newton runtime](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/solver/stellar_context.cppm:1199). The [earlier architecture audit](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/MeanField_audit_2026-09-16.md) contains the fuller module map.
|
||||
|
||||
## Experimental controls and provenance
|
||||
|
||||
The current working tree, including the user's existing optimizations, was rebuilt in Release with Homebrew Clang 22.1.8. Library IPO was enabled, profiling disabled, and the field-order increment was zero. Sandbox, validation executable and test targets compiled successfully. The starting HEAD was `75cc63873992984966ea20011cc04d9984f54be4`, with 49 already-modified tracked files and additional untracked research material. The starting diff and status are archived with the campaign; HEAD alone does not describe the tested source.
|
||||
|
||||
Runs were serial, single-rank CPU jobs on the same mesh. M=R_reference=G=1. For n=1, K=2/pi and rho_c=pi/4. Other indices were calibrated to M=R=1 using the production Lane–Emden seed integrator (step 1e-3): this is seed-consistent calibration, not an independent high-precision continuum reference.
|
||||
|
||||
Live Newton used restart 40, at most 200 linear iterations, relative linear tolerance 0.03, nonlinear rtol=1e-8 and atol=0, with geometry preflight enabled. Runs stopped at linear failure rather than exhausting their nonlinear budgets. A nonzero exit status for these experiments records the intended failure observation, not a compilation or setup failure.
|
||||
|
||||
Frozen comparisons used the same state, physical right-hand side and default inverse, changing only the Krylov window from 40 to 160. Both started cold and independently recomputed the true residual. The live solver can retain the unused portion of a damped correction as its next initial guess; that distinction matters for the n=1.5 comparison. No probe trial was committed. Finite-difference and nonlinear-trial probes used the window-40 direction, even when window 160 gave a better solve.
|
||||
|
||||
Physical diagnostics integrate only stellar material at quadrature orders 14 and 18, reconstruct physical positions and the Piola-transformed gravity field, and use the actual n and K. They measure
|
||||
|
||||
\[
|
||||
W_E=\tfrac12\int\rho\Phi\,dV,\quad
|
||||
W_F=-\int\rho\,\boldsymbol x\cdot\nabla\Phi\,dV,\quad
|
||||
\epsilon_V=\frac{|2T+W+3\int P\,dV|}{|W_E|}.
|
||||
\]
|
||||
|
||||
Both W choices and both P(h)/P(rho) definitions are exported. Signed DG density is retained. Negative density makes a full physical P(rho) diagnostic undefined rather than silently clipped. Samples do not certify global positivity.
|
||||
|
||||
## Fresh convergence and physical results
|
||||
|
||||
Here F is the normalized, bordered weak residual. Omega is in the reference units above; it is **not** a measured fraction of critical rotation. Virial columns below use P(h).
|
||||
|
||||
| Model | Accepted Newton steps | Retained F | Energy / force virial | Immediate stopping condition |
|
||||
|---|---:|---:|---:|---|
|
||||
| n=1, J=0 | 3 full | 6.6053e-9 | 2.616e-7 / 3.246e-7 | Linear defect 0.04442 after 200 iterations |
|
||||
| n=1, J=0.01 | 4 full | 5.0898e-10 | 2.610e-7 / 3.246e-7 | Linear defect 0.35468 after 200 |
|
||||
| n=1, J=0.01, no central phase | 4 full | 5.0976e-10 | 2.612e-7 / 3.248e-7 | Linear defect 0.33345 after 200 |
|
||||
| n=1, J=0.05 | 5 full | 6.0406e-9 | 3.016e-7 / 3.188e-7 | Linear defect 0.50520 after 200 |
|
||||
| n=1.5, J=0 | 2: alpha=1, then 1/16 | 1.6976e-4 | 2.245e-6 / 2.318e-6 | Linear defect 0.14163 after 200 |
|
||||
| n=3, J=0 | 0 | 3.1006e-3 | 5.326e-5 / 8.341e-5 | First linear solve fails at 0.05631 |
|
||||
|
||||
The strict n=1,J=0 nonlinear target is 1.81e-12 because it is relative to the initial residual. The same three-step model was previously classified as converged by the validation driver's absolute tolerance of 1e-8. These labels are compatible: the fresh run reproduces that state but requests further algebraic reduction.
|
||||
|
||||
The first three accepted n=1 steps take 22–24 seconds, confirming the current roughly 20-second operating point. I did not rerun the old pre-optimization code, so the factor-of-ten historical gain is not independently remeasured here. Once linear iterations grow, steps cost 66–106 seconds; backtracking can cost more. Improving per-action performance has not removed the conditioning problem.
|
||||
|
||||
For n=1, P(rho) virials are also below 3.74e-7, with order-14/order-18 changes below 8e-14. Mass/J errors are tiny. Nevertheless, Bernoulli RMS is about 1.14e-4 and density-closure RMS about 6.7e-5 in these reference units. The initial nonrotating n=1 seed already passes the virial requirement, which directly demonstrates that virial success alone does not certify interior equilibrium.
|
||||
|
||||
The faster-rotation case reaches Omega=0.18589155, compared with 0.03821371 at J=0.01. It passes all four virial metrics and has no negative density/enthalpy samples. Yet its maximum sampled EOS density mismatch reaches 0.00934 of the sampled density scale, approximately **0.93%**, compared with 0.0424% at J=0.01. Its Bernoulli range rises to 0.0146 while volume RMS changes little. This is a concentrated internal-consistency concern that global integrals and RMS alone would largely miss. The unbordered residual is 4.5423e-6, dominated by the central source, despite bordered F=6.0406e-9. This case was not subjected to a frozen restart comparison or a no-phase control.
|
||||
|
||||
For n=1.5, quadrature changes the P(h) virial by only 1.84e-9, supporting its integrated milestone. But negative DG density carries 2.89e-5 of the mass magnitude, and full P(rho) virials are undefined. Bernoulli RMS worsens from 1.49e-4 to 1.92e-4; gradient-force mismatch rises from 0.00153 to 0.01090. EOS closure improves. These are distinct errors that a single residual or virial number cannot classify. Negative density may be a projection undershoot rather than a large bulk failure; its magnitude and pressure contribution need an explicit error budget.
|
||||
|
||||
The n=3 state is the unchanged projected seed, not a converged model. Its virial failure is stable under quadrature refinement. A sampled bound on the pressure contribution associated with negative-density regions is below 1e-6 in virial units, too small to explain the measured 5–8e-5 P(h) defect.
|
||||
|
||||
## Preconditioner: capable baseline, incomplete coupled approximation
|
||||
|
||||
The default is accurately described by three levels:
|
||||
|
||||
1. **Material/surface:** solve surface q with a raw reference boundary-mass diagonal; apply the actual q-to-material coupling; solve enthalpy with a hydrostatic mass diagonal; solve density with its closure mass diagonal, including the live EOS h-to-rho derivative. Material-to-surface feedback is omitted. Replaced hydrostatic rows at the surface receive identity treatment in the enthalpy diagonal.
|
||||
2. **Gravity:** approximate mixed LDU with degree-5 Chebyshev flux-mass inversion and three fixed AMG cycles for the potential surrogate B diag(M_g)^-1 B^T. Recovery uses two flux-mass actions. The surrogate and recovery do not use identical mass inverses.
|
||||
3. **Structure and borders:** material/surface and gravity are independent at the structure level. A small dense scalar Schur complement is inverted exactly relative to that approximate structure inverse. Its completed scalar columns are cached; it is not the exact Schur complement of the stellar Jacobian.
|
||||
|
||||
Sources: [material policy and action](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/material_surface.cppm:995), [default structure policy](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/stellar_structure.cppm:850), [gravity surrogate](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/preconditioning/gravity_field.cpp:68), [border construction](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/specification_border.cppm:2333).
|
||||
|
||||
The live high-n EOS derivative is present; geometry refresh and stale-inverse protections are implemented. No material diagonal regularization floor activated in the inspected states. A claim that the preconditioner simply forgot nonlinear EOS dependence would be incorrect.
|
||||
|
||||
### Measured restart sensitivity
|
||||
|
||||
| Frozen state | Window 40: iterations / true relative defect | Window 160: iterations / true relative defect | Interpretation |
|
||||
|---|---:|---:|---|
|
||||
| n=1, J=0 endpoint | 200 / 0.04442 | 72 / 0.02914 | Larger window meets 0.03 target; 87.2 s becomes 31.0 s |
|
||||
| n=1, J=0.01 endpoint | 200 / 0.35468 | 125 / 0.02519 | Larger window meets target; 90.5 s becomes 56.7 s |
|
||||
| n=1.5, J=0 endpoint | 200 / 0.06491 | 70 / 0.02694 | Larger window meets target; 92.8 s becomes 32.1 s |
|
||||
| n=3, J=0 seed | 200 / 0.05631 | 200 / 0.04026 | Improvement is insufficient; both fail |
|
||||
|
||||
At J=0.01 the histories coincide through iteration 40 and separate immediately after the first restart. The 160-vector solve finishes before restarting. Reported and independently recomputed defects agree. This establishes loss of useful accumulated Krylov information, rather than false residual reporting, for that state.
|
||||
|
||||
The failed window-40 n=1 corrections are nevertheless useful nonlinear directions: full admissible trials reduce F from 6.605e-9 to 2.937e-10 at J=0 and from 5.090e-10 to 1.805e-10 at J=0.01, matching their linear predictions closely. Production Newton never tries them because the fixed linear-quality gate fails. This is an observed gate/window limitation, not an observed nonlinear residual floor. It does not establish that loosening the gate is the best remedy.
|
||||
|
||||
At n=1.5 the cold window-40 defect, 0.06491, is smaller than the live warm-started result, 0.14163. The previous accepted step was only 1/16, so production retained 15/16 of the earlier correction as its next guess. That reuse did not help this particular solve. The comparison supports evaluating correction reuse separately from Krylov basis retention; it is not evidence that warm starts are generally harmful.
|
||||
|
||||
### Measured omitted feedback
|
||||
|
||||
At the rotating n=1 endpoint, 96.9% of the failed linear defect's squared norm lies in Poisson; at the n=3 seed it is 98.8%. The n=3 initial gravity residual is nearly zero: correcting material closure creates gravity imbalance that the coupled iteration struggles to remove.
|
||||
|
||||
For unit normalized scalar directions, I formed the preconditioner's completed structure response and applied the true full Jacobian. The scalar tails match the approximate Schur exactly, but the structure defects remain large and predominantly Poisson. For example, the central-border column's Poisson action is approximately 2.18e4 for n=1 and 3.15e5 for n=3. These arbitrary unit-column amplitudes are diagnostic, not physical solution errors. They directly expose missing material-to-gravity completion, consistent with stronger d(rho)/dh at higher central concentration.
|
||||
|
||||
The small normalized border matrix has a large raw condition number, 2.78e7 for rotating n=1 and 9.69e7 for n=3. This is dominated by a central-column scale near 7.3e6. Simple diagnostic row/column equilibration reduces those numbers to approximately 1.46 and 2.39. These are not estimates of the full Jacobian condition number and do not demonstrate a singular border or failure of its dense solve.
|
||||
|
||||
## Normalization: implemented consistently; physical weighting remains open
|
||||
|
||||
With reference Gram diagonal d and characteristic physical scale s, the state factor is sqrt(d)/s and the residual factor is 1/(s sqrt(d)), with point-row and scalar exceptions. Factors are frozen during the solve and based on M, R_reference and G, not divided by the requested J. Zero rotation is therefore not a normalization singularity.
|
||||
|
||||
Writing x_hat=Sx and F_hat=LF gives
|
||||
|
||||
\[
|
||||
\widehat J=LJS^{-1},\qquad
|
||||
\widehat P^{-1}=SP^{-1}L^{-1},\qquad
|
||||
\widehat J\widehat P^{-1}=LJP^{-1}L^{-1}.
|
||||
\]
|
||||
|
||||
Thus **state-only rescaling cancels from the consistently right-preconditioned system**. Direct tests spanning block state-factor changes of 1e-3–1e3 preserve the preconditioned action and physical correction to about 1e-16. Wrapper/explicit Jacobian actions and round trips likewise agree at roundoff.
|
||||
|
||||
This rules against a basic coordinate-wrapper error in the inspected states, not against a poor residual norm. Residual weighting changes what Krylov and line search minimize. The factors are identical across the tested indices at M=R=G=1 and do not adapt to concentration, EOS susceptibility or deformation. Their large ranges reflect support sizes and point-row treatment, not automatically a bug. The normalized weak norm is not a demonstrated unit-, mesh- or index-independent physical stopping criterion.
|
||||
|
||||
Future residual weighting should be evaluated through interior errors and virial, with stellar/vacuum gravity contributions separated. **Poisson dominance alone does not show that the exterior dominates the failure.** Exterior normalization or approximation changes remain acceptable if their induced interior errors satisfy the physical budget.
|
||||
|
||||
Sources: [factor construction](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/operators.cppm:325), [frozen stellar wrapper](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/stellar_equilibrium.cppm:650).
|
||||
|
||||
## Operator and globalization hypotheses
|
||||
|
||||
### 1. Higher-index corrections encounter real nonlinear curvature
|
||||
|
||||
For n=1.5, a valid linear correction is rejected at alpha=1, 1/2, 1/4 and 1/8 solely on residual merit; alpha=1/16 is accepted. All those trials are admissible. Gravity rows, initially almost zero, dominate the residual after the first step.
|
||||
|
||||
For n=3, the frozen full correction is admissible but increases F by a factor 6.92; alpha=0.1 decreases it. Its measured vector Taylor remainder is approximately 0.0215 alpha^2 over several decades of alpha. This supports smooth curvature along the tested direction rather than a gross derivative inconsistency. The current geometry-dependent gravity mass/source terms contain q–gravity and q–density interactions even though gravity is linear in its fields at fixed geometry.
|
||||
|
||||
Prepared closure and pressure reject negative enthalpy. Positivity does not limit the tested n=3 direction (sampled enthalpy step bound about 18.5) or late rotating n=1 direction (about 4e6). No positivity rejection was recorded during the earlier n=1.5 production backtracking.
|
||||
|
||||
However, the **later cold window-40 n=1.5 endpoint direction does encounter a positivity boundary**: the combined sampled thermodynamic limit is alpha=0.18863 (pressure quadrature; closure gives 0.19517), and full/half trials are rejected. At alpha=0.1 preparation succeeds but F grows to 2.4033e-4; alpha=0.01 decreases it slightly to 1.6893e-4. Its measured Taylor remainder is approximately 0.008852 alpha^2, with gravity accounting for 99.734% of the squared remainder at alpha=0.01. This separates a thermodynamic ceiling from a still tighter residual-merit restriction. It also shows why rejection mechanisms must be identified per state and direction rather than ruled out for an entire index. These nonlinear trials did not test the window-160 correction. Positive Jacobian determinants do not bound residual curvature or ensure enthalpy positivity.
|
||||
|
||||
**Discriminating next experiment:** separate shape-only, field-only and full directional Taylor remainders at the same state. With shape held fixed, the gravity residual is linear in its field/density variables, so its remainder should vanish to arithmetic accuracy. Measure reduced surface response and the actual correction's spatial content before selecting trust-region or continuation changes.
|
||||
|
||||
### 2. The surface equation complement may weaken for n>1
|
||||
|
||||
Hydrostatic surface rows are replaced by h=0; shape equations come from volume mechanical virtual work pulled back through the prescribed extension. For exact smooth fields with rho=P=0 on the surface,
|
||||
|
||||
\[
|
||||
R_{mech}(w)=\int\rho\nabla B\cdot w
|
||||
=-\int B\,\nabla\cdot(\rho w).
|
||||
\]
|
||||
|
||||
Near a regular surface, h is proportional to inward distance d and rho to d^n. The induced Bernoulli test weight therefore behaves like d^(n-1): finite trace for n=1, vanishing trace for n>1. This suggests that mechanical shape tests may poorly complement the retained interior hydrostatic tests as n increases.
|
||||
|
||||
This is a **specific, unmeasured conditioning hypothesis**, not proof of a missing equation or zero shape stiffness. The extension reaches dense interior material, and independent discrete fields break the exact identity. Measure the reduced surface response and its near-null modes after coupled material/gravity completion. A later controlled formulation comparison could retain all weak Bernoulli rows and place h_surface=0 in shape rows, subject to checking matching boundary spaces. No such replacement was made here.
|
||||
|
||||
The power-2 extension also does not contain exact uniform volume dilation, so satisfying reduced mechanical equations does not algebraically guarantee scalar virial balance. The independent virial measurement must remain mandatory.
|
||||
|
||||
### 3. Central phase contamination is a physical issue, but not the sole low-spin stall mechanism
|
||||
|
||||
The central-density specification actually imposes a central enthalpy coefficient and adds lambda_c e_c to the hydrostatic equation. At rotating n=1,J=0.01, bordered F is 5.09e-10 but the unbordered norm is 1.87e-7. Removing the phase leaves global virials and bulk integrals almost unchanged, while the formerly constrained enthalpy coefficient drops by 6.83e-4, or 0.0683%. A localized error can therefore be invisible to the virial milestone.
|
||||
|
||||
The no-phase run still fails its late linear solve, so this border is not the sole cause of that Krylov failure. It nevertheless matters to internal correctness and to defining a physically compatible rotating sequence. At fixed K and mass, central density generally changes with rotation. For the n=1 reference model, an independent slow-rotation calculation gives delta M/M=(2/3-2/pi^2) Omega^2 at fixed K and rho_c; allowing the central density to decrease is required to retain equal mass. This agrees with the classic perturbation result in [Chandrasekhar's 1933 rotational-polytrope paper](https://articles.adsabs.harvard.edu/pdf/1933MNRAS..93..390C). The calculation is a local continuum argument, not proof that the bordered discrete system lacks a root.
|
||||
|
||||
At n=3,J=0 the central condition fixes a genuine homology freedom, so indiscriminately deleting it would be inappropriate. The physical parameterization of a rotating n=3 sequence deserves separate treatment. See the [formulation analysis](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/formulation_audit_notes.md) for the derivation and source references.
|
||||
|
||||
### 4. Translation modes remain a plausible, unmeasured contribution
|
||||
|
||||
The active surface descriptor retains translations; fixing the mesh origin is not equivalent to fixing the physical center of mass when fields are independent. At a smooth center, a central enthalpy condition has zero first-order response to physical translation. Three continuum translation symmetries exist at zero rotation; axial translation survives rotation about a fixed axis.
|
||||
|
||||
The finite-element mesh, compactification and border may lift these directions, and measured COM drift is only a few parts in 1e-6. There is no evidence here that gross translation caused the observed curvature. Existing shape-only dipole tests do not test a fully field-compensated physical translation. A useful next probe constructs that complete tangent, completes gravity, measures Jv and overlap with the failed correction, and compares axial/transverse responses. Do not add a centering constraint merely on the strength of the continuum argument.
|
||||
|
||||
## Verification, limits and next decisions
|
||||
|
||||
All **nine focused tests passed: 4,252 assertions, zero failures**, in 315 seconds. They cover the complete coupled core Jacobian; closure at n=1,1.5,3; nonlinear pressure derivatives; optimized/reference hydrostatic preparation; central-border composition; generated angular-velocity derivatives; two-sided normalization with the full inverse; frozen normalized coordinates; and direct reference-mass diagonals. The freshly rebuilt, formatted diagnostic target also compiles successfully. See the [test log](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/diagnostics/campaign_2026-09-16/focused_tests.log) and [exact test selection](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/diagnostics/campaign_2026-09-16/focused_tests_metadata.json).
|
||||
|
||||
The final diff comparison confirms that all tracked numerical source changes predated this audit; the only additional tracked-file edit is the diagnostic CMake target. Five new experiment source/documentation files were added. The test reporter's new HTML output was archived and the user's pre-existing September 9 report restored. [Provenance](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/diagnostics/campaign_2026-09-16/provenance.json) records the source check and final file hashes; a separate manifest records the actual campaign binary before formatting and its mesh hash.
|
||||
|
||||
Actual-state one-sided finite differences supplement manufactured tests. Higher-n error trends support the implemented derivative along the tested directions. At tiny n=1 residuals, differencing reaches an absolute arithmetic floor around 3e-14, so relative errors of nearly zero actions are not evidence of a Jacobian bug. These checks do not exhaust every mode, state, or near-vacuum behavior.
|
||||
|
||||
The entire test suite was not rerun. The prior archived full-suite result was 588/592 passing, with known refinement-map, projected n=3 seed-closure and two distributed-layout failures. This campaign is single-rank and does not resolve distributed partition restrictions. No rotating continuation to 50% or 99% critical has been demonstrated. Critical fraction must eventually be based on the rotating surface/equatorial effective gravity, not reference-unit Omega alone.
|
||||
|
||||
The most defensible sequence of subsequent work is:
|
||||
|
||||
1. Use these frozen physical right-hand sides as common comparisons for restart/recycling and existing coupled inverse policies. Compare true residual blocks, time and memory; do not select policies from isolated subsystem performance alone.
|
||||
2. Measure missing density–gravity completion and the reduced surface response, including compensated translation/homology directions. The historical experiments already show that “more coupling” is not automatically better in the full system.
|
||||
3. Separate geometric Taylor remainders and relate correction size to surface-response conditioning. Then choose among stronger coupled preconditioning, a different surface formulation, globalization or continuation based on the measured failure.
|
||||
4. Evaluate residual weighting with stellar/vacuum splits and physical error budgets. State-only scaling is not a standalone remedy for this right-preconditioned operator.
|
||||
5. Define a compatible physical sequence and monitor unbordered residuals and central profiles as J increases. Keep the central condition only where its role and physical effect are understood.
|
||||
|
||||
Validation should label **virial milestone**, **interior correctness**, and **algebraic convergence** separately. The next regression set should include both virial definitions with quadrature refinement; mass/J and COM; Bernoulli, EOS and gravity consistency by center/bulk/surface region; negative-density mass/pressure budgets; nonrotating n=1,1.5,3 profile and integral convergence under mesh/order refinement; and rotating symmetry/equatorial-force checks. Exterior refinement or weighting comparisons should be accepted according to their effect on those interior quantities. ESTER remains a later independent validation target.
|
||||
|
||||
## Artifacts
|
||||
|
||||
- [Campaign summary JSON](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/diagnostics/campaign_2026-09-16/campaign_summary.json), with per-case CSVs and logs in the same directory.
|
||||
- [Detailed preconditioner measurements](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/diagnostics/campaign_2026-09-16/preconditioner_analysis.md).
|
||||
- [Physical validation analysis](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/diagnostics/campaign_2026-09-16/physical_validation_analysis.md).
|
||||
- [Diagnostic executable source](/Users/tboudreaux/Programming/4DSTAR/MeanField/experiments/plateau_diagnostic.cpp) and [usage/methods](/Users/tboudreaux/Programming/4DSTAR/MeanField/experiments/plateau_diagnostic_README.md).
|
||||
243
reports/sources/original_audits/formulation_audit_notes.md
Normal file
243
reports/sources/original_audits/formulation_audit_notes.md
Normal file
@@ -0,0 +1,243 @@
|
||||
# Formulation and operator audit — 2026-09-16
|
||||
|
||||
Read-only examination of `/Users/tboudreaux/Programming/4DSTAR/MeanField`, plus an independent, inexpensive scalar Lane–Emden perturbation calculation. No production edits or full FEM solves were made by this sub-audit. Sources refer to the current working tree rather than HEAD alone. The main audit's fresh solves should take precedence when categorizing actual plateau behavior.
|
||||
|
||||
## Principal conclusion
|
||||
|
||||
The most consequential formulation hypothesis is target compatibility: the sandbox fixes the EOS constant K, total mass M, angular momentum J, and central enthalpy simultaneously. The central condition is implemented by adding an artificial, localized hydrostatic source, not by choosing a physical degree of freedom such as K. An unbordered rotating polytrope does not generally have all four independent freedoms. This merits measurement before assigning the plateau entirely to preconditioning. It is **not yet demonstrated that this causes the observed plateau**.
|
||||
|
||||
The operator composition and available tests provide meaningful evidence against an elementary missing rotation derivative or forgotten shape pullback term. Existing optimized-path checks remain narrower than an end-to-end Jacobian check at an actual plateau.
|
||||
|
||||
## What is implemented
|
||||
|
||||
The physical residual is:
|
||||
|
||||
- Mixed gravity in independent RT gradient and L2 potential fields.
|
||||
- Weak density closure, `integral q (rho-rho(h)) = 0`, in the DG density space.
|
||||
- Hydrostatic Bernoulli residual, `integral v (h+Phi-Psi-C) = 0`, in H1 enthalpy, except surface rows replaced by pointwise prescribed enthalpy.
|
||||
- Surface mechanical residual obtained by pulling back the full volume virtual-work residual through the surface-to-interior extension.
|
||||
- Mass and angular momentum constraints, whose scalar unknowns are C and angular speed.
|
||||
- Optional central enthalpy condition with a generated border scalar lambda.
|
||||
|
||||
Source: [physical composition](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_stellar_equilibrium.cpp:795), [hydrostatic imbalance](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_hydrostatic_equilibrium.cpp:863), [closure](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_barotropic_closure.cpp:652), [mechanical composition](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_displacement_operator.cpp:309).
|
||||
|
||||
Pressure force uses P(h), while gravitational and centrifugal forces use the independent rho. Hydrostatic balance uses the independent Phi, while force balance uses the independent gravity gradient. These are consistent continuum equations but need not be identical discrete statements. Their finite-dimensional compatibility and conditioning deserve attention as n increases. This is not a demonstrated algebraic error.
|
||||
|
||||
## Central-density compatibility: a quantitative check
|
||||
|
||||
[Sandbox lines 92–116](/Users/tboudreaux/Programming/4DSTAR/MeanField/sandbox.cpp:92) prescribe spherical n=1 K and rho_c and retain both fixed mass and fixed central density when J is changed. The commented n=3 replacement constants do the same for that index. [The phase implementation](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/prepared_central_density.cppm:71) is exactly
|
||||
|
||||
```
|
||||
R_c = h(0) - h(rho_c,target)
|
||||
R_h += lambda_c e_c
|
||||
```
|
||||
|
||||
The phase therefore changes the physical hydrostatic equation whenever lambda_c is nonzero. It does not literally constrain the independent DG density at the center. Repository [extension documentation](/Users/tboudreaux/Programming/4DSTAR/MeanField/docs/stellar_physics_extension_guide.md:188) itself distinguishes a phase condition that removes a degeneracy from a new physical invariant.
|
||||
|
||||
An independent continuum calculation sharpens this concern. Define
|
||||
|
||||
\[
|
||||
a^2=\frac{(n+1)K}{4\pi G}\rho_c^{1/n-1},\quad h=(n+1)K\rho_c^{1/n}\theta,
|
||||
\quad \xi=r/a,\quad v=\frac{\Omega^2}{2\pi G\rho_c}.
|
||||
\]
|
||||
|
||||
Taking the Laplacian of `h+Phi-Omega² s²/2=C` gives
|
||||
|
||||
\[
|
||||
\Delta_\xi\theta=-\theta^n+v.
|
||||
\]
|
||||
|
||||
At first order in v the angle-averaged correction psi satisfies
|
||||
|
||||
\[
|
||||
\psi''+2\psi'/\xi+n\theta_0^{n-1}\psi=1,
|
||||
\quad \psi(0)=\psi'(0)=0.
|
||||
\]
|
||||
|
||||
Because density vanishes at the unperturbed surface for n>=1, the first-order displacement of the integration boundary makes no contribution to mass. Consequently
|
||||
|
||||
\[
|
||||
M=4\pi a^3\rho_c\{m_n+v m'_n(0)+O(v^2)\},
|
||||
\quad m_n=-\xi_1^2\theta'_0(\xi_1),
|
||||
\quad m'_n(0)=\xi_1^3/3-\xi_1^2\psi'(\xi_1).
|
||||
\]
|
||||
|
||||
For n=1, theta_0=sin(xi)/xi and psi=1-theta_0, yielding the exact leading-order result
|
||||
|
||||
\[
|
||||
\frac{\delta M}{M}=\left(\frac{\pi^2}{3}-1\right)v+O(v^2).
|
||||
\]
|
||||
|
||||
For the sandbox's G=M=R=1 spherical K and rho_c, this becomes
|
||||
|
||||
\[
|
||||
\frac{\delta M}{M}=\left(\frac23-\frac{2}{\pi^2}\right)\Omega^2+O(\Omega^4)
|
||||
=0.4640242994\,\Omega^2+O(\Omega^4).
|
||||
\]
|
||||
|
||||
For example, Omega=0.015 in these units implies a leading-order mass shift of about 1.04e-4 if K and rho_c stay fixed. This is **not** a measured error from a code run, and Omega here is relative to the spherical reference Kepler frequency; it is not a measurement of fraction of mass-shedding critical rotation. At fixed K and M the physical central density should instead change at order Omega².
|
||||
|
||||
An independent RK4 solution of the radial perturbation equations gave:
|
||||
|
||||
| n | xi1 | m_n | d(log M)/dv at fixed K,rho_c |
|
||||
|---|---:|---:|---:|
|
||||
| 1 | 3.1415926655 | 3.1415926536 | 2.2898681711 (exact 2.2898681337) |
|
||||
| 1.5 | 3.6537537533 | 2.7140551201 | 2.8391061305 |
|
||||
| 2 | 4.3528746068 | 2.4110460121 | 3.5676985861 |
|
||||
| 2.5 | 5.3552754706 | 2.1871995655 | 4.5879534966 |
|
||||
| 3 | 6.8968486271 | 2.0182359510 | 6.1245958551 |
|
||||
|
||||
Radial steps 1e-3 and 5e-4 agree on the n=3 derivative to approximately 1.3e-11 absolute; n=1 agrees with its closed form at 4e-8. These calculations establish the local continuum compatibility concern without depending on the production FEM solver or seed integrator.
|
||||
|
||||
For n=3 the prefactor `a³ rho_c` is independent of rho_c. Central density can select the nonrotating homology family when K and M are compatible, but a rotating dimensionless solution has a different mass at the same K. Changing rho_c alone cannot cancel that difference at fixed v. A sequence retaining the nonrotating K and M is therefore especially delicate: the nearby positive-rotation branch is not obtained simply by selecting a new central density. This is separate from, and additional to, linear-system difficulty near the n=3 homology mode.
|
||||
|
||||
This derivation was subsequently checked against the primary paper [S. Chandrasekhar, “The Equilibrium of Distorted Polytropes: (I). The Rotational Problem,” MNRAS 93, 390–406 (1933)](https://articles.adsabs.harvard.edu/pdf/1933MNRAS..93..390C). Equation (48″), page 397, gives exactly the n=1 mass correction above. Equation (56), page 399, gives approximately 6.123v for n=3, consistent with the sign and magnitude of the independent modern integration. Section 12, pages 400–401, discusses changing central density to retain equal mass and the singular character of n=3. The derivation and numerical calculation above were performed independently; the primary paper is a cross-check, not the source of their numerical table.
|
||||
|
||||
For n different from 3, fixed-K mass scaling gives the leading equal-mass response
|
||||
|
||||
\[
|
||||
\frac{\delta\rho_c}{\rho_c}=-\frac{2n}{3-n}\frac{m'_n(0)}{m_n}\,v+O(v^2).
|
||||
\]
|
||||
|
||||
The factor `2n/(3-n)` also makes n near 3 particularly sensitive. These are nearby, slowly rotating continuum statements; they do not prove that the finite-dimensional bordered system lacks a root or that every rotating branch at every parameter value is impossible.
|
||||
|
||||
**Discriminating measurements:** lambda_c, normalized norm of `lambda_c e_c`, the unbordered residual, and central profiles throughout rotation continuation. Compare their order in Omega². A physically meaningful variant must either demonstrate negligible lambda or explicitly account for which physical target is allowed to change. A solver can reduce the bordered residual while concealing an unbordered hydrostatic defect, so residual convergence alone cannot settle this question. The archived n=1 J=0 solution is a favorable control: lambda=-4.64e-13, normalized border action=1.25e-9, and unbordered total residual=6.72e-9.
|
||||
|
||||
A bounded **n=1 diagnostic control** without the phase is especially informative if the original rotating run fails: central enthalpy should be allowed to depart from its spherical value, and the physical residual should converge without a localized artificial source. This would test formulation sensitivity, not constitute a promoted remedy. Do not extrapolate this control to n=3,J=0, where removing the phase exposes a genuine homology degeneracy. Furthermore, an n=1.5 or n=3 plateau at **J=0 with compatible spherical targets** cannot be explained by rotational target incompatibility; another mechanism or a distinct discretization/phase compatibility issue must be demonstrated there.
|
||||
|
||||
## Surface admissibility and material conditioning
|
||||
|
||||
[Prepared closure lines 614–633](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_barotropic_closure.cpp:614) require finite density but reject every negative enthalpy quadrature value. The standalone EOS's rho(h)=0 extension at h<0 is therefore not usable through this prepared path. High-order H1 interpolation can undershoot between nodes, including when the boundary values are zero. A positivity-driven line-search collapse is a credible, testable plateau mechanism.
|
||||
|
||||
For a frozen Newton direction in reference coordinates, the exact closure-sample positivity limit is
|
||||
|
||||
\[
|
||||
\alpha_h=\min_{\delta h_q<0}(-h_q/\delta h_q).
|
||||
\]
|
||||
|
||||
Compare alpha_h with geometric preflight and accepted step length, and record the limiting element, point, h and delta h. This distinguishes an enthalpy boundary from geometry and merit-only rejection. Since h samples depend on FE coefficients rather than the moving physical quadrature location, this diagnostic is inexpensive and directly interpretable.
|
||||
|
||||
Independent DG density can be negative locally while all preparation checks pass; the angular-momentum operator only rejects a negative *total* inertia, not negative local density. Record minimum rho and negative-density mass fraction independently.
|
||||
|
||||
The [EOS derivative](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/eos/polytropic.cppm:155) is nonzero at h=0 for n=1, but zero for n>1. Thus density/enthalpy coupling becomes weak in the outer layers. This is not automatically a singular complete Jacobian: hydrostatic rows retain their h mass term and density rows retain their rho mass term. Claims that the EOS is singular must distinguish a vanishing coupling from inversion of that coupling or actual rank loss.
|
||||
|
||||
EOS quadrature includes an n-dependent extra order, `(n-1)*enthalpyOrder`, rounded upward ([source](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_barotropic_closure.cpp:103)); there is no evidence here of the elementary mistake of keeping an n=1 closure quadrature rule for all n. Noninteger powers and deformed geometry still merit independent quadrature convergence checks.
|
||||
|
||||
## Mechanical residual and virial acceptance
|
||||
|
||||
The reduced shape residual is `D'(s)^T R_mech`, not the full volume mechanical residual. Its vanishing establishes equilibrium only against extension-generated virtual displacements. The default interior extension uses radial power 2 ([default composition](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/stellar_equilibrium_problem.cppm:317), [power default](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/deformation/radial_extensions.cppm:103), [radial weights](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/deformation/radial_extensions.cpp:752)). Uniform surface inflation therefore does not produce an exact volume dilation w=x on a spherical reference configuration. In particular, vanishing reduced mechanical residual does not algebraically guarantee a zero scalar virial residual.
|
||||
|
||||
The required 1e-5 virial milestone should be evaluated independently over the stellar volume. The existing validation integrals already compute energy and force versions and P(h) versus P(rho), but are explicitly n=1 formulas ([measurement source](/Users/tboudreaux/Programming/4DSTAR/MeanField/experiments/polytrope_validation_measurements.hpp:136)). Reusing this routine for n=3 without replacing these formulas would silently compute the wrong pressure. It is currently used only by an n=1-specialized harness, so this is a generalization warning, not an existing bug.
|
||||
|
||||
Interior pointwise tests should resolve Bernoulli variation, EOS mismatch, density sign, and gravity consistency. Exterior error is relevant insofar as it changes those internal quantities or virial balance; it should not be an independent acceptance obstacle under the user's stated priority.
|
||||
|
||||
## Jacobian correctness and optimization evidence
|
||||
|
||||
The root shape derivative contains both `D'(s)^T J_mech delta` and the derivative of the pullback itself ([source](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_stellar_equilibrium.cpp:891)). The generated angular-speed derivative reaches both the hydrostatic and shape rows, and the angular-momentum row differentiates inertia in density and geometry ([source](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/prepared_variadic_stellar_equilibrium.cppm:713)). Returning zero physical rotational derivative at Omega=0 is correct for a quadratic centrifugal potential.
|
||||
|
||||
Existing coverage includes:
|
||||
|
||||
- A complete core, block-resolved centered-difference test with n=3 and nonzero fixed rotation, tolerance 2e-6 ([test](/Users/tboudreaux/Programming/4DSTAR/MeanField/tests/operators/prepared_stellar_equilibrium.cpp:1225)).
|
||||
- A generated-Omega column finite-difference test at n=1, nonzero J, checking shape, hydrostatic, and angular-momentum rows ([test](/Users/tboudreaux/Programming/4DSTAR/MeanField/tests/operators/stellar_equilibrium_system.cpp:246)).
|
||||
- Separate angular-momentum density/displacement derivative tests and numerous displacement/thermodynamic component checks.
|
||||
- Optimized-versus-reference and finite-difference isolation results, with final batch metadata explicitly reporting n=1, K=1, 3 directions, deformation setting 0.7, and one rank ([metadata](/Users/tboudreaux/Programming/4DSTAR/MeanField/final_optimizations_01/metadata.txt)).
|
||||
|
||||
I found no demonstrated Jacobian defect in this read-only review. However, none of these facts substitutes for a fresh check at the actual higher-n/rotating stalled state, including simultaneous field, shape, Omega and border perturbations. Use an epsilon sweep and per-block relative errors, plus one-sided admissible perturbations where centered tests cross h=0. In particular, the n=1 optimization metadata is not evidence that nonlinear pressure/closure optimization is validated at every higher n.
|
||||
|
||||
## Ranked formulation-side hypotheses and falsifiers
|
||||
|
||||
1. **Physical target incompatibility / border contamination.** Strong analytical basis, but no stalled-state lambda measurement yet. Falsify as immediate cause if lambda and unbordered residual remain negligible while a compatible target family stalls identically.
|
||||
2. **Enthalpy admissibility prevents the Newton correction.** Explicit rejection mechanism in source; must be established from trial reasons and alpha_h. Falsify if full or large steps are accepted and no thermodynamic rejections occur.
|
||||
3. **Weak density/enthalpy coupling and approximate discrete mechanical compatibility worsen near n=3 or rotation.** Established structural change; causal role requires block diagnostics, homology-response measurement, and refinement comparison. Do not label projected-seed residual floors as proof that no discrete equilibrium exists.
|
||||
4. **Missing or incorrect Jv at the actual state.** Lower prior because of substantial derivative tests, but inexpensive relative to further unstructured solver tuning and not excluded by old checks. Falsify with current-source, per-block directional convergence at the stalled state.
|
||||
|
||||
No proposed remedy has been implemented in this audit.
|
||||
|
||||
## Diagnostic-driver and focused-test review
|
||||
|
||||
Reviewed the separate workspace `diagnostics/plateau_diagnostic.cpp` without compiling or running it. `Derive()` correctly calibrates M=R=1 using `rho_c=xi1³/(4*pi*mu1)` and `K=4*pi*G*rho_c^(1-1/n)/((n+1)*xi1²)`. The last derivative entry really is at the first zero: the production integrator appends the linearly interpolated root and immediately returns. There is no endpoint-index error. Calibration is consistent with the seed integrator, but its 1e-3 step and linearly interpolated root/derivative do not certify exact continuum constants to 1e-12. Unbordered-residual subtraction correctly uses full residual indices supplied by `PhysicalState`.
|
||||
|
||||
Recommended focused test names (not run by this sub-audit):
|
||||
|
||||
1. `Prepared Stellar Equilibrium Complete Jacobian Matches Every Coupled Centered Difference Block` — n=3 core, nonzero fixed rotation, all blocks.
|
||||
2. `Prepared Barotropic Closure Covers Multiple EOS And Geometry Conditions In Reduced Coordinates` — current tensor/reference comparisons and centered differences at n=1, 1.5, 3.
|
||||
3. `Prepared Pressure Force Jacobian Matches Full Stateless Columns Through FieldDof Restriction` — n=3 optimized versus retained/reference pressure paths.
|
||||
4. `Hydrostatic Tensor Preparation Matches Pointwise Preparation And Rebuilds On Mode Changes` — optimized preparation, all columns, geometry changes and switching paths.
|
||||
5. `Central Density Contribution Composes Through The Variadic Root` — n=3 border algebra and invalidation.
|
||||
6. `Fixed Angular Momentum Root Uses Its Generated Angular Velocity In Every Physical Row` — generated-Omega column at n=1 and nonzero J.
|
||||
7. `Two Sided Normalization Composes With The Full Coupled Stellar Preconditioner` — n=1, J=0.05, central phase, scaling and inverse composition.
|
||||
|
||||
Additional relevant checks: `Normalized Stellar Equilibrium Preserves Physical Residuals Jacobians And Frozen Solve Coordinates` and `Direct Reference Mass Diagonals Match Full True DOF Assembly`.
|
||||
|
||||
The higher-n optimized-source test coverage is stronger than the saved n=1-only isolation metadata alone suggests. However, its manufactured enthalpy profiles are bounded away from vacuum. Passing these checks would not establish correctness of near-surface derivative behavior at a real plateau. The historical `Prepared Stellar Equilibrium Has A Restoring Jacobian Around An N3 Polytrope` screen has a known projected-seed closure failure; keep its result distinct rather than silently including it in a passing focused-selection claim.
|
||||
|
||||
## Additional hypothesis: physical translation modes survive mesh anchoring
|
||||
|
||||
**Assessment:** structurally plausible and worth a targeted frozen-J diagnostic, but not yet demonstrated as a measured near-null direction of the current normalized operator or as the cause of late Newton linear difficulty.
|
||||
|
||||
The active radial-surface descriptor explicitly declares `translationTreatment=Retained` ([source](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/deformation/nodal_radial_surface.cpp:25)). The power-law extension forces the displacement at the origin to zero ([source](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/deformation/radial_extensions.cpp:752)). The old `PreparedCenteringConstraint` module still exists and is exported, but a source-wide search found no active instantiation/application in the physical or variadic root. It imposed zero center *mesh displacement*, not center of mass. No active COM, three-component enthalpy-gradient centering, reflection/parity, or l=1 exclusion condition was found. Center-of-mass integration infrastructure exists as analysis/quadrature support, not an active equilibrium constraint.
|
||||
|
||||
The historical [deformation design](/Users/tboudreaux/Programming/4DSTAR/MeanField/SURFACE_DEFORMATION_PRESCRIPTION_DESIGN.md:703) intentionally removed the old centering rows when restricting geometry; it explicitly left possible surface-space translation projection or COM control to future conditioning evidence. Its argument establishes that rigid translation of the *complete mesh* is excluded. It does not establish that a compensated translation of the *physical fields and stellar boundary* is excluded.
|
||||
|
||||
To see the distinction, write the physical mesh map as x(X) and its perturbation as v(X). A translated physical scalar field is `f_t(x)=f(x-t a)`. Its coefficient-field tangent on the changing mesh is
|
||||
|
||||
\[
|
||||
\delta\widehat f(X)=\nabla_x f(x(X))\cdot[v(X)-a].
|
||||
\]
|
||||
|
||||
The scalar fields are independent unknowns, so they can supply this composition term even when v(0)=0. On a spherical surface the translated shape has radial tangent `delta s=a dot e_r`; on a general star-shaped surface it is `(a dot n)/(e_r dot n)`. Both are representable approximately by the nodal radial surface space. Tangential relabeling of surface points need not be a root geometry degree of freedom to describe the same translated physical boundary.
|
||||
|
||||
At a smooth centered equilibrium, `grad h(0)=0`. Thus the central phase has first-order response
|
||||
|
||||
\[
|
||||
\delta R_c=\delta h(0)=-a\cdot\nabla h(0)=0.
|
||||
\]
|
||||
|
||||
It may select the center at nonlinear second order, but it does not provide a nonsingular first-order translation gauge at such a state. Even away from an exact extremum its single scalar row can constrain at most one linear combination of three translation directions. This differs fundamentally from its useful nonzero response to the n=3 homology scaling tangent.
|
||||
|
||||
For Omega=0, all three translations preserve the continuum unbordered equations, mass, and zero angular momentum. For nonzero rigid rotation about a fixed z axis, axial translation preserves the centrifugal potential, the axial inertia, and J. Transverse translations are physically lifted by the fixed rotation axis through the force/hydrostatic equations, although their first-order axial inertia change is zero at a centered model. A nonzero anchored lambda source can itself break translation symmetry; the near-symmetry argument is strongest where the unbordered defect and lambda are already negligible.
|
||||
|
||||
Finite-element interpolation, the particular radial geometry space, compactified exterior representation, and discrete departure from symmetry can lift these continuum directions. Consequently, this review does not claim an exact current algebraic nullspace. Fixed origin of the exterior compactification is likewise a coordinate choice in the continuum but may be a source of finite-resolution lifting.
|
||||
|
||||
### Existing mode evidence does not test this complete tangent
|
||||
|
||||
Current [surface-mode construction](/Users/tboudreaux/Programming/4DSTAR/MeanField/experiments/stellar_null_space.cppm:444) initially sets all root blocks to zero except surface shape. Its l=1 patterns are named translation-like dipoles. In [coupled mode construction](/Users/tboudreaux/Programming/4DSTAR/MeanField/experiments/coupled_gauge_modes.cpp:373), only homology receives extension-aware density and enthalpy tangents; nonuniform modes, including dipoles, retain their original shape-only material variation before gravity completion. Their nonzero hydrostatic response therefore cannot falsify a fully compensated physical translation near-null mode.
|
||||
|
||||
The older `gravity_completed_null_space_restricted.csv` contains near-null *full-displacement* translations: unpinned action about 2.99e-7, versus constrained action about 1 after old center-row replacement; z translation remains at that small response at reference rotation fraction 0.5. This is historically consistent with the symmetry argument, but it is not current reduced-root/normalization evidence and should not be presented as such.
|
||||
|
||||
### Suggested frozen-state probe, without modifying solver policy
|
||||
|
||||
1. For each axis, prescribe the radial translation tangent on the current surface. At the nearly spherical n=1 J=0 baseline, `a dot e_r` is a suitable first probe; retain the current-normal formula for stronger deformations.
|
||||
2. Lift it through the current domain-deformation Jacobian to v.
|
||||
3. Project `grad h dot (v-a)` into the supported enthalpy space and `grad rho dot (v-a)` into supported density. For DG density, compare a recovered/analytic physical gradient or `rho'(h) grad h` to the elementwise gradient, because a broken derivative alone is not an exact translation of a discontinuous finite-element function. Boundary enthalpy direction should be zero by tangency; verify this rather than introducing a false surface-pressure response.
|
||||
4. Complete the gravity-gradient and potential directions by solving the frozen restricted mixed gravity block with the negative residual generated by the prescribed density and shape tangents. Existing `GravityUnknownJacobian`/`solve_gravity_completion` in `experiments/coupled_gauge_modes.cpp` provides the model. This avoids hand-differentiating the RT Piola transform and correctly includes the fixed-infinity exterior response.
|
||||
5. Set delta C, delta Omega and delta lambda to zero for the translation symmetry probe. Apply the full normalized Jacobian to a unit normalized direction and report every block, the phase response, delta M, delta J, and the derivative of COM (which should approach a).
|
||||
6. Compare with uncompensated dipoles and generic normalized directions; then examine overlap of the actual problematic Newton correction with the compensated translation span. At nonzero rotation, compare axial with transverse response. A tiny response alone identifies poor conditioning; association with the failing correction/right-hand side is needed to assign causality.
|
||||
|
||||
No translation-mode code or solver change was implemented, and no new solve was run by this sub-audit.
|
||||
|
||||
## Additional hypothesis: mechanical rows weakly complement the omitted boundary Bernoulli tests
|
||||
|
||||
The active root first builds all H1 hydrostatic rows and then replaces the surface subset with h=0. Shape equations are separately supplied by reduced mechanical virtual work ([composition](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_stellar_equilibrium.cpp:803)). This is square and deliberate, not an equation-counting mistake. Nevertheless, the quality of the resulting surface complement may deteriorate with n.
|
||||
|
||||
For smooth exact fields, write `B=h+Phi-Psi-C`. Using `grad P=rho grad h` and P=0 on the surface gives
|
||||
|
||||
\[
|
||||
R_{mech}(w)=\int_\star \rho\nabla B\cdot w\,dV
|
||||
=-\int_\star B\,\nabla\cdot(\rho w)\,dV,
|
||||
\]
|
||||
|
||||
where the second equality also uses rho=0 at the surface. Thus a shape test w_s acts like a Bernoulli test `q_s=-div(rho w_s)`, rather than like one of the dropped H1 boundary basis functions. Near a regular free surface, h is proportional to inward distance d and rho is proportional to d^n. For a smooth test with nonzero normal surface motion, the leading induced weight behaves as `q_s ~ d^(n-1)`. It has nonzero limiting trace for n=1 but vanishing trace for n>1.
|
||||
|
||||
This gives a specific potential conditioning mechanism: as n increases, induced mechanical tests may overlap strongly with already retained interior hydrostatic tests while weakly controlling Bernoulli mismatch in the boundary layer. After eliminating material/gravity variables, the remaining shape response can become small or sensitive to projection mismatch. A heuristic boundary-layer calculation suggests suppression relative to unweighted boundary Bernoulli tests by an additional factor of layer-thickness^(n-1), but this is not a measured scaling law for this discretization.
|
||||
|
||||
There are essential limits to this argument:
|
||||
|
||||
- Vanishing surface density **does not imply a zero mechanical shape Jacobian**: the lifted test extends through the dense interior, and geometry, pressure, gravity and scalar-field readjustment all contribute.
|
||||
- In the continuum, interior Bernoulli tests are already dense enough to impose B=0; counting boundary test functions is a finite-dimensional argument, not proof of an underdetermined physical free boundary.
|
||||
- The discrete code uses independent rho and h and independent RT gravity and L2 potential. Pointwise EOS mismatch, noncommuting gravity representations, and DG jumps spoil the exact smooth-field identity. Those defects can supply a numerical complement, but its magnitude and conditioning must be measured.
|
||||
- Consequently, neither continuum redundancy nor surface vanishing by itself proves an implementation defect or identifies the observed plateau.
|
||||
|
||||
A direct diagnostic would eliminate the coupled material/gravity response for selected surface directions and compare the remaining mechanical-shape response with the omitted boundary Bernoulli residual response. Measure normalized singular/near-null responses, correction amplitudes, and refinement/index dependence. The reported n=1.5 behavior—small lambda, no thermodynamic rejection, acceptable linear residual and large geometric quadratic remainder—is compatible with a poorly conditioned shape direction, but is also compatible with other causes of an excessively large Newton correction.
|
||||
|
||||
A useful **future controlled formulation comparison**, not implemented here, is to retain all Nh weak Bernoulli rows and use h_surface=0 as the Nq shape-row equations, replacing mechanical shape rows. The current surface space is scalar H1 from the displacement collection (order 3), while enthalpy is also scalar H1 order 3 on the same mesh ([FEM construction](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/fem.cpp:214)); verify boundary count/topology before using a one-to-one arrangement. The design explicitly permits unequal future orders, so equality is not an architectural invariant. Retaining weak boundary Bernoulli tests avoids choosing a pointwise trace for the discontinuous potential. Independent virial and internal correctness remain acceptance criteria regardless of which discrete complement performs better.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Preconditioner and normalization audit — 2026-09-16
|
||||
|
||||
Read-only inspection of the current working source in `/Users/tboudreaux/Programming/4DSTAR/MeanField`. No solver fixes, source edits, builds, or new numerical runs were performed by this audit subtask. Existing numerical results below are explicitly historical. The repository is dirty and contains substantial performance work newer than HEAD `75cc638`; line references identify the inspected working source.
|
||||
|
||||
## Current default: exact implementation, not inferred intent
|
||||
|
||||
The sandbox selects `PhysicalRieszDiagonal{radius,G}`, default stellar preconditioning, and FGMRES(restart 40): [sandbox.cpp:118](/Users/tboudreaux/Programming/4DSTAR/MeanField/sandbox.cpp:118).
|
||||
|
||||
The physical unknowns grouped for preconditioning are material/surface `(rho,q,h)`, gravity `(g,Phi)`, then the generated scalar constraints. The preconditioner is a composition of three approximations:
|
||||
|
||||
1. **Material/surface is surface-first triangular.** Solve `q = Dq^-1 bq`, subtract the actual surface-to-material Jacobian actions, solve `h = Dh^-1 (bh-Ahq q)`, then solve `rho = Drho^-1 (brho-Arhoq q-Arhoh h)`. Thus the current EOS derivative and surface-to-material actions ARE included. Material-to-surface feedback is omitted. `Drho` is the closure density mass diagonal; `Dh` is the hydrostatic enthalpy mass diagonal, with replaced surface rows set to one. `Dq` is the raw positive boundary mass diagonal, without an operator-fitted coefficient or EOS/rotation-dependent stiffness. [default selection](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/material_surface.cppm:677), [action](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/material_surface.cppm:995), [diagonals](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/material_surface.cppm:1423), [surface assembly](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/material_surface.cppm:1439).
|
||||
|
||||
2. **Gravity is approximate LDU.** The mixed flux mass inverse is a degree-5 matrix-free Chebyshev action with 20 power iterations at setup; the positive potential-Schur surrogate is `B diag(Mg)^-1 B^T`, inverted approximately with three fixed BoomerAMG cycles. Gravity recovery makes two mass-inverse applications. Note that the Schur surrogate continues to use the mass DIAGONAL even though flux recovery uses the more accurate Chebyshev approximation; this is a deliberate approximation, not an exact factorization. [default](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/stellar_structure.cppm:851), [LDU](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/gravity_field.cppm:271), [surrogate](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/preconditioning/gravity_field.cpp:68), [fixed AMG](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/backend_implementations.cppm:47).
|
||||
|
||||
3. **Material/surface and gravity are independent before scalar bordering.** Their cross-couplings are available, but the default calls each subsystem inverse separately. A small dense border Schur `S = D-C Atilde^-1 B` is assembled by probing every scalar border column and inverted directly. For the stationary default the already-computed `W=Atilde^-1 B` is cached and used for recovery. This border is exact relative to the selected approximate structure inverse, not the exact stellar Jacobian. [independent action](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/stellar_structure.cppm:347), [border construction](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/specification_border.cppm:2333), [cached recovery](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/specification_border.cppm:2285).
|
||||
|
||||
Other available policies are material/surface LDU, reverse triangular order, calibrated surface mass, fitted surface mass-plus-stiffness, and both stellar cross-coupling triangular orders/LDU. Availability is not evidence of quality for rotating models.
|
||||
|
||||
Lifecycle checks are substantial: stale gravity and material inverses are rejected; changes to geometry rebuild their relevant diagonals and gravity surrogate. Material thermodynamic diagonals are reused when geometry is unchanged because the rho–rho and h–h derivatives are mass operators; the EOS derivative resides in a separately prepared live coupling. This reuse is not, by itself, evidence of a stale high-n EOS approximation. [material refresh](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/material_surface.cppm:1328), [gravity refresh](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/preconditioning/gravity_field.cppm:536), [closure density diagonal](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_barotropic_closure.cpp:705).
|
||||
|
||||
## Normalization: what is and is not established
|
||||
|
||||
Physical scales are derived from fixed target mass, branch reference radius, and G: rho*=M/R³, g*=GM/R², h*=GM/R, Omega*=sqrt(GM/R³), J*=M sqrt(GMR), F*=GM²/R². Neither target J nor Omega enters a denominator; zero rotation is not singular in these scale formulas. [scale derivation](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/physical_riesz.cppm:95).
|
||||
|
||||
The Gram diagonals are reference finite-element volume mass diagonals for rho,h,Phi; reference RT mass diagonal for g; and a boundary mass diagonal for q. For a field block with scale s and diagonal d, state normalization is `sqrt(d)/s`, while weak residual normalization is `1/(s sqrt(d))`. Replaced pressure-surface enthalpy rows use point metric one; generated scalar constraints use metric one. The central-density residual is correctly classified as an enthalpy residual, despite its density target. [assembly and block assignment](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/stellar_equilibrium.cppm:513), [factor formulas](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/operators.cppm:325), [hybrid rows](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/operators.cppm:247), [scalar dimensional declaration](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/models/specifications.cppm:772).
|
||||
|
||||
These maps are frozen throughout Newton unless explicitly refreshed. They do not adapt to central concentration, EOS derivatives, effective surface gravity, or rotation. They define the merit/Krylov norm; they are not a Jacobian approximation. Reference exterior weighting is a computational norm choice and does not by itself mean the exterior must be physically accurate everywhere. The important diagnostic is whether exterior residuals consume the solve budget while interior structure and virial balance are already accurate.
|
||||
|
||||
Let physical state `x=R xhat`, residual `Fhat=L F`, and physical approximate inverse `P^-1`. The wrappers implement exactly `Jhat=LJR` and `Phat^-1=R^-1 P^-1 L^-1`. Therefore
|
||||
|
||||
`Jhat Phat^-1 = L (J P^-1) L^-1`.
|
||||
|
||||
This is an especially useful diagnostic inference: **changing only state scaling cancels from the consistently right-preconditioned Krylov operator in exact arithmetic.** Row scaling changes the Euclidean residual geometry and nonlinear merit; it does not remove an actual null direction. A claim that variable scaling alone fixes the present solver would require an identified finite-precision or inconsistent-transform mechanism. [Jacobian wrapper](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/operators.cppm:398), [inverse wrapper](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/normalization/operators.cppm:571).
|
||||
|
||||
The source includes round-trip, scaled-operator, synthetic conditioning, and direct-versus-assembled Gram diagonal tests. They establish algebra and assembly expectations when run; they do not establish mesh-independent merit weighting for every n/rotation or full physical-unit invariance. Raw reference measures are used without total-volume/area normalization, surface point rows are counted individually, and the phase border is inserted directly into a weak enthalpy coefficient. Before making broad claims about dimensional invariance, test a physically equivalent length/mass unit change through the complete discretization, not only the characteristic-scale formulas. This is an audit gap, not demonstrated causation of the plateau at the current fixed units.
|
||||
|
||||
## Existing numerical evidence: historical, not a new convergence experiment
|
||||
|
||||
The September 3 campaign is explicitly a **nonrotating n=3 projected Lane–Emden seed**. Its full-system results precede the current normalized Newton stack. Surface-first, uncalibrated mass and independent stellar subsystems won the available full-system comparisons. Scalar surface calibration and material LDU improved isolated solves but did not transfer to the complete operator; the surface action varied over approximately three orders of magnitude across sampled modes. The fitted H1 mass-plus-stiffness surrogate was also unreliable. [campaign](/Users/tboudreaux/Programming/4DSTAR/MeanField/docs/preconditioning_campaign_2026-09-03.md:5).
|
||||
|
||||
Chebyshev-5/AMG-3 achieved true relative residual 1.19e-4 after a 36-iteration fixed-budget manufactured full-system solve; the historical residual was 93.8% gravity-gradient and 6.2% Poisson by squared norm. However, a physical RHS experiment with restart 20 stagnated near relative residual 0.9998 after 48 iterations, motivating equation normalization and restart studies. These are strong reasons to test actual physical RHSs and recompute true residuals, but cannot be presented as measurements of today's normalized plateau. [campaign results](/Users/tboudreaux/Programming/4DSTAR/MeanField/docs/preconditioning_campaign_2026-09-03.md:56).
|
||||
|
||||
## Hypotheses to discriminate, without changing the algorithm
|
||||
|
||||
1. **Global coupled modes are poorly represented by independent structure blocks.** The code omits the rho→gravity→h and shape↔gravity feedback loops from its principal approximate inverse; the scalar Schur inherits those omissions. High n changes the strength and localization of these loops. This is a strong structural hypothesis, but there is no present proof that it dominates a recorded plateau. Test the physical Newton RHS at one frozen plateau with identical total Jacobian budgets and longer restart; record which residual blocks remain. Only after diagnosis compare opt-in cross-factorization policies, using true residual reduction per time. Earlier stronger coupling policies were worse, so “more coupling” alone is not a recommendation.
|
||||
|
||||
2. **Surface restoring action becomes poorly matched by the raw surface mass diagonal.** Default Dq has no state-dependent stiffness, whereas the true surface residual contains material, gravity, and rotation dependence. This is particularly plausible approaching mass shedding, but cannot explain a low-rotation threshold without state-specific mode evidence. Probe smooth radial, oblate quadrupole, and a few high-frequency surface modes through the full normalized Jacobian and approximate inverse; include induced material/gravity completion when interpreting a surface Schur mode. Do not extrapolate isolated Aqq tuning to the coupled model.
|
||||
|
||||
3. **Nonlinear admissibility rather than linear conditioning can control high-n progress.** For n=1, dρ/dh is constant. For n>1 it tends to zero as h→0, and the closure's preparation rejects any negative h at its quadrature points. The standalone EOS itself clips negative h to zero, so merely inspecting its public formula misses this solver-domain restriction. Record minimum h, trial failure source, step length, and predicted versus actual reduction. Repeated h-domain rejection with accurate linear solves would rank this above preconditioner tuning. [EOS derivative](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/eos/polytropic.cppm:142), [closure rejection](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/impl/operators/prepared_barotropic_closure.cpp:627).
|
||||
|
||||
4. **Frozen residual weighting can make the reported plateau differ from the physical milestone.** Separate full normalized norm, each normalized block norm, interior gravity defects, and virial error. If almost all remaining norm is exterior gravity while virial/interior quantities satisfy their tolerances, the computational stopping target may be the issue. If virial remains bad, exterior inaccuracies cannot simply be dismissed: their influence on interior gravity must be assessed.
|
||||
|
||||
5. **Border/constraint compatibility needs explicit measurement.** Fixed-central-density adds `lambda_c e_c` to the weak enthalpy equation, alongside its phase condition; a small total residual does not imply the unmodified hydrostatic equation if lambda_c is appreciable. Export lambda_c, its actual normalized contribution, the tiny approximate Schur matrix, and its singular values in normalized coordinates. A well-conditioned approximate border Schur does not prove the exact coupled system is well-conditioned. [central border](/Users/tboudreaux/Programming/4DSTAR/MeanField/libmeanfield/interface/operators/prepared_central_density.cppm:72).
|
||||
|
||||
## Economical frozen-state instrumentation
|
||||
|
||||
At every accepted state, report `||F||`, normalized block norms, true `||J dx+F||/||F||`, solver-reported residual, iteration/restart count, accepted alpha, rejection reasons, minimum h/rho/Jacobian determinant, virial balances, mass/J errors, and phase-border contribution. Two Jacobian finite-difference directions (actual Newton direction and an oblate/shape direction), with several step sizes that remain admissible, would separate an inconsistent derivative from a poor solve.
|
||||
|
||||
Public access through the default context is available without editing production code:
|
||||
|
||||
```cpp
|
||||
state.physicalInverse->Refresh(); // only when the physical problem is prepared
|
||||
const auto &grouped = state.physicalInverse->GetGroupedPreconditioner();
|
||||
const auto &S = grouped.GetFactorization().GetSchurComplement();
|
||||
const auto &structure = grouped.GetStructurePreconditioner();
|
||||
const auto &material = structure.GetMaterialSurfacePreconditioner();
|
||||
const auto &gravity = structure.GetGravityPreconditioner();
|
||||
const auto &coordinates = state.physicalInverse->GetCoordinateMap();
|
||||
const auto &normalization = state.normalizedOperator->GetNormalization();
|
||||
mfem::Vector L(state.physicalInverse->Height());
|
||||
mfem::Vector V(state.physicalInverse->Height());
|
||||
coordinates.PackResidual(normalization.ResidualFactors(), L);
|
||||
coordinates.PackCorrection(normalization.StateFactors(), V);
|
||||
const int start = grouped.GetCouplings().StructureSize();
|
||||
mfem::DenseMatrix Shat(S.Height(), S.Width());
|
||||
for (int i=0; i<S.Height(); ++i)
|
||||
for (int j=0; j<S.Width(); ++j)
|
||||
Shat(i,j) = L(start+i) * S(i,j) / V(start+j);
|
||||
```
|
||||
|
||||
Compute SVD of `Shat`, not raw dimensional `S`. This is tiny and cheap; serial runs avoid distributed scalar ownership complications. Exporting the entries for external SVD is sufficient. Material diagonal min/max/floor/regularized-count getters are already public, as are gravity mass inverse, potential Schur surrogate, and factorization statistics. The current context refreshes the inverse during `PrepareTrialCommit`, and `WithState` requires a ready context, so the final accepted-state Schur is current. An explicit no-op refresh in an independent diagnostic remains harmless; preparations performed outside the context must respect the lifecycle.
|
||||
|
||||
The later experiment-only helper [preconditioner_diagnostics.hpp](/Users/tboudreaux/.codex/.chatgpt-projects/g-p-6a6b3f2194ec8191bebcd59075897f1d/diagnostics/preconditioner_diagnostics.hpp) implements these exports plus a variable-scaling invariance check and full-Jacobian actions on border-completed directions. It does not change state, instantiate alternate preconditioner policies, or solve any extra equations. Its expected cost is three Jv plus one Jv per generated scalar border coordinate. Compilation and execution are coordinated by the root task.
|
||||
|
||||
No hypothesis above is presented as the established cause before the root task's new runs are available. Virial <=1e-5 is the primary model acceptance milestone; pointwise interior accuracy and checks for nonphysical constraint forcing remain necessary companions. Exterior error is relevant through interior gravitational influence and numerical conditioning, not as an independent accuracy target.
|
||||
Reference in New Issue
Block a user