Skip to content

Anisotropic mesh adaptation part 1: feature-based metric tensor - #2613

Open
bmunguia wants to merge 64 commits into
su2code:developfrom
bmunguia:dev/aniso_metric
Open

bmunguia wants to merge 64 commits into
su2code:developfrom
bmunguia:dev/aniso_metric

Conversation

@bmunguia

@bmunguia bmunguia commented Nov 3, 2025 •

Copy link
Copy Markdown
Member

Proposed Changes

This PR is part of a joint effort with Alberto Perlini (@xla27) and Andrea Rausa (@rois1995) to implement anisotropic mesh adaptation in SU2. Part 1 (this PR) computes adaptive metric fields for feature-based adaptation in SU2's post-processing. Part 2 will add the Python adaptation loop with the open-source MMG remesher, including conversion between SU2 restarts/meshes and the .meshb format.

For each sensor, SU2 computes the Green-Gauss gradient and Hessian, and builds an adaptive metric from the absolute value of the Hessian (integrated in time with the trapezoidal rule for unsteady flows), optionally normalized in the Lp norm (see references). Implementation details:

  • Sensors are resolved case-insensitively from ADAPTIVE_METRIC_SENSOR, and can be:
    • primitive variables of the flow solver (e.g. PRESSURE, DENSITY, VELOCITY_X)
    • computed quantities (VELOCITY magnitude; MACH for compressible solvers)
    • solution variables of other solvers (NU_TILDE; TKE, DISSIPATION; INTERMITTENCY, RE_THETA_T; SPECIES_<i>)
    • custom sensors set through the Python wrapper (SU2.adaptive_metric.CustomSensorRegistry, listed in ADAPTIVE_METRIC_CUSTOM_SENSOR)
  • Every sensor gets its own metric; size and aspect ratio constraints can be set per sensor
  • The matrix absolute value and eigenvalue floor are applied in eigenspace during integration and normalization only, and the size and aspect ratio constraints set the final sizes (degenerate, e.g. rank-one, Hessians give finite SPD metrics)
  • Unsteady flows: the trapezoidal rule uses the actual (possibly variable) time step, and the metric is normalized when the run stops (including MAX_TIME and time convergence); Python scripts that drive the time loop call driver.FinalizeAdaptiveMetric()
  • Volume outputs (groups): SENSOR_VALUE, SENSOR_GRADIENT, SENSOR_HESSIAN, ADAPTIVE_METRIC (AdaptiveMetric_<Sensor>_*); the ParaView writers (XML and legacy) write the Hessians/metrics as symmetric tensors and only group vector/tensor components that form a complete adjacent set
  • Currently supported only with the single-zone primal driver; periodic boundaries, multizone, harmonic balance and the discrete adjoint are rejected in the config. Only Green-Gauss Hessians and a single adaptation sub-interval are supported for now

New config options (see config_template.cfg):

  • COMPUTE_ADAPTIVE_METRIC (bool, default NO): compute the adaptive metric in post-processing; this does not adapt the mesh
  • NORMALIZE_ADAPTIVE_METRIC (bool, default YES): perform the Lp-norm normalization
  • NUM_METHOD_HESS (default GREEN_GAUSS): Hessian method
  • ADAPTIVE_METRIC_SENSOR (list): sensors, each with its own metric
  • ADAPTIVE_METRIC_CUSTOM_SENSOR (list): sensors set through the Python wrapper
  • ADAPTIVE_METRIC_NORM (default 2): p of the Lp norm
  • ADAPTIVE_METRIC_COMPLEXITY (default 10000): target mesh complexity
  • ADAPTIVE_METRIC_HMIN / ADAPTIVE_METRIC_HMAX / ADAPTIVE_METRIC_ARMAX (defaults 1e-8 / 100 / 1e6): minimum/maximum cell size and maximum aspect ratio; one value for all sensors, or one per sensor
  • ADAP_TIME_SUBINTERVAL (default 1): unsteady adaptation sub-intervals (only 1 for now)

Examples are in TestCases/mesh_adaptation/adaptive_metric (built-in sensors on an inviscid NACA0012, and a custom total-pressure sensor through the Python wrapper on RANS), using the QuickStart mesh.

Unit tests are in UnitTests/SU2_CFD/adaptive_metric.cpp (2D and 3D, including the Green-Gauss Hessian of a quadratic field).

PR Checklist

  • I am submitting my contribution to the develop branch.
  • My contribution generates no new compiler warnings (try with --warnlevel=3 when using meson).
  • My contribution is commented and consistent with SU2 style (https://su2code.github.io/docs_v7/Style-Guide/).
  • I used the pre-commit hook to prevent dirty commits and used pre-commit run --all to format old commits.
  • I have added a test case that demonstrates my contribution, if necessary.
  • I have updated appropriate documentation (Tutorials, Docs Page, config_template.cpp), if necessary.

References

  1. Loseille and Alauzet. "Continuous mesh framework part I: well-posed continuous interpolation error," 2011.
  2. Alauzet and Loseille. "A decade of progress on anisotropic mesh adaptation for computational fluid dynamics," 2016.
  3. Perlini. "Mesh adaptation in SU2: current status and perspectives," 2025.
  4. Munguía. "Towards a deep learning framework for time-accurate anisotropic mesh adaptation," 2025.

@pcarruscag

Copy link
Copy Markdown
Member

Is the mesh adaptation code itself open source?

@bmunguia

bmunguia commented Nov 3, 2025

Copy link
Copy Markdown
Member Author

If you mean MMG, it's on Github https://github.com/MmgTools/mmg

If you mean the SU2-MMG interface, it's in Alberto's fork https://github.com/xla27/SU2/tree/feat_adap_mmg

@pcarruscag pcarruscag left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent. Next question, what do you need from the python wrapper to do all of this outside of the SU2 core?

@bmunguia

bmunguia commented Nov 3, 2025

Copy link
Copy Markdown
Member Author

The python script basically just coordinates calls to SU2 and MMG in 2 nested loops, the inner loop being a series of adaptations at a given target mesh size and the outer loop being over a list of sizes. It also handles file conversions since MMG uses libmeshb for both the mesh and metric field.

For the file conversion, Alberto has a straight python implementation that I think only handles tris/tets, and I have a separate repo with a C++ implementation/python API that I used for my results that I presented in Varenna https://github.com/bmunguia/limon

@pcarruscag

Copy link
Copy Markdown
Member

Cool, the functionality would be more flexible if the sensor was also configurable via python, what you have here has a list of hardcoded possible variables, in python it would be very easy to target other solvers, create custom mixes of variables etc.
So maybe a helper to compute a generic gradient/hessian in c++?

Comment thread SU2_CFD/src/solvers/CSolver.cpp Fixed
Comment thread SU2_CFD/src/solvers/CSolver.cpp Fixed
Comment thread SU2_CFD/src/solvers/CSolver.cpp Fixed
Comment thread SU2_CFD/src/solvers/CSolver.cpp Fixed
Comment thread Common/src/CConfig.cpp Fixed
Comment thread SU2_CFD/src/output/CFlowOutput.cpp Fixed
@bigfooted

Copy link
Copy Markdown
Contributor

Hi Brian, what's the status?

@bmunguia

Copy link
Copy Markdown
Member Author

Hey Nijso, sorry for the delay. I've been a bit swamped lately with a deadline and the holidays so this has been on the backburner, but I'll look at it again this week or next. I know a lot of people have been asking about adaptation on slack so I want to get this in develop ASAP.

I still need to implement Pedro's suggestions to use the python wrapper to make the choice of metric sensor more flexible, then I just need to add an example (or maybe a few for different solvers) to test the implementation.

@bigfooted

Copy link
Copy Markdown
Contributor

Hi @bmunguia, any update on this?

@bmunguia

bmunguia commented Apr 8, 2026

Copy link
Copy Markdown
Member Author

Sorry for the massive delay. I made the implementation a bit more flexible by resolving the indices using CPrimitiveIndices rather than hardcoding per-solver. So now if you specify a list of sensors

COMPUTE_METRIC= YES
NORMALIZE_METRIC= YES
METRIC_SENSOR= DENSITY, PRESSURE, TEMPERATURE
METRIC_NORM= 2
WRT_RESTART_COMPACT= NO
VOLUME_OUTPUT= (COORDINATES, SOLUTION, PRIMITIVE, SENSOR_GRADIENT, SENSOR_HESSIAN, METRIC)

it should set them all as sensors

void CSolver::SetPrimitive_Adapt(CGeometry *geometry, const CConfig *config) {
  const auto nSensors = MetricSensorIndices.size();

  /*--- Copy each resolved sensor variable into Sensor_Adapt ---*/
  for (size_t iSensor = 0; iSensor < nSensors; iSensor++) {
    const auto var_idx = MetricSensorIndices[iSensor];

    SU2_OMP_FOR_STAT(omp_chunk_size)
    for (unsigned long iPoint = 0; iPoint < nPoint; iPoint++) {
      const su2double prim_var = base_nodes->GetPrimitive(iPoint, var_idx);
      base_nodes->SetSensor_Adapt(iPoint, iSensor, prim_var);
    }
    END_SU2_OMP_FOR
  }
}

and calculate gradients/Hessians for all of them, as well as a Lp-norm normalized metric field for the first entry. I still need to add the python wrapper bit so we can compute metrics of derived quantities like Mach number. This is currently my top priority since I actually need the Mach metric soon for my own work. I'm hoping to get it implemented today or tomorrow.

…s struct

- Add AdaptiveMetric_ParsedOptions; replace individual CConfig members/getters
- Rename config keys to COMPUTE_ADAPTIVE_METRIC, NORMALIZE_ADAPTIVE_METRIC, ADAPTIVE_METRIC_*
- Rename metrics/ headers, Python package and test case directory to adaptive_metric
- Rename output group/fields to ADAPTIVE_METRIC / AdaptiveMetric_*
- Store one adaptive metric per sensor; output AdaptiveMetric_<Sensor>_*
- Take the Hessian absolute value and eigenvalue floor in eigenspace within each pass instead of storing a floored SPD Hessian (fixes NaN for rank-one Hessians); error on a zero normalization integral
- Respect NORMALIZE_ADAPTIVE_METRIC for steady runs
- Finalize the unsteady time integral when the run actually stops (MAX_TIME, time convergence); add FinalizeAdaptiveMetric() to the Python driver API
- Move the metric kernels to computeAdaptiveMetric.cpp, passive double only
- Keep the stored Hessian raw; remove unused SetGradient_Adapt
- Error when COMPUTE_ADAPTIVE_METRIC has no ADAPTIVE_METRIC_SENSOR entries
- Error on periodic boundaries, which the adaptive metric does not support yet
- ADAPTIVE_METRIC_HMIN/HMAX/ARMAX take one value for all sensors or one value per sensor; check hmin > 0, hmax >= hmin, armax >= 1
- Match the GOAL sensor case-insensitively
- Default NORMALIZE_ADAPTIVE_METRIC to YES
- Remove the redundant Hessian-method check and the unreachable empty-sensor warning in the driver
- Classify output fields once: a vector or tensor requires names ending in _x/_xx followed by the remaining components with the same prefix; everything else is a scalar
- Fixes scalar sensors such as VELOCITY_X being written as vectors, and dropped or misaligned arrays when sensor names contain _x/_y
- Remove the duplicated substring checks and running field counter from the header and data passes
- Add addSymOuterProduct helper shared by the interior-edge and boundary loops of computeHessiansGreenGauss; fold the boundary sign into the flux
- Use auto loop indices in the adaptive metric code
- Document that custom sensor names match case-insensitively in CustomSensorRegistry
…uickStart mesh in the examples

- Add UnitTests/SU2_CFD/adaptive_metric.cpp: identity, rank-one, and zero Hessians on a unit cube, checking the analytic uniform metric, a finite SPD rank-one metric within the size and aspect ratio constraints, and the eigenvector alignment
- Document the adaptive metric options in config_template.cfg
- Point both adaptive metric examples at QuickStart/mesh_NACA0012_inv.su2
@bmunguia

Copy link
Copy Markdown
Member Author

@bigfooted sorry for the delay. I've finished going through the comments. Some of the main changes I made based on @EvertBunschoten's comments:

  • Renamed classes/config keys/outputs from "Metric" to "AdaptiveMetric" for clarity
  • Added per-sensor metric normalization and size constraints

and based on @rois1995's comments:

  • Rejected periodic boundary conditions for adaptation for now
  • Rather than adding a scale-aware floor, I followed Adrien Loseille's suggestion (based on how Inria handles their normalization): the matrix absolute value + floor are applied inline during integration/normalization, rather than storing the floored SPD Hessian, whose floor was lost on recomposition (which is what caused Andrea's NaNs), and hmin/hmax/ARmax act as the final guards on the prescribed mesh sizes; Andrea's [[1,1],[1,1]] now gives a finite SPD metric, and a zero Hessian gives a uniform isotropic metric
  • Added a unit test (rather than regressions) for the Lp-norm normalization cases described in the previous point
  • Fixed NORMALIZE_ADAPTIVE_METRIC being ignored for steady runs, and finalized the unsteady metric when the run stops early (e.g. MAX_TIME)
  • Fixed VTK grouping of sensors that are components of vectors (e.g. VELOCITY_X)

@bigfooted bigfooted left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, @rois1995 would be good to have a page on the website when this is completed (or wait until the second PR is merged?)

@rois1995

Copy link
Copy Markdown
Contributor

@bigfooted, I agree. I will create one based on this PR once it is fully approved.

@rois1995 rois1995 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the earlier points are fixed. One MPI type issue left, plus two small checks.

Comment thread SU2_CFD/src/solvers/CSolver.cpp Resolved
Comment thread Common/src/CConfig.cpp Resolved
@rois1995

rois1995 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

The six earlier points are fixed, with one leftover.

  • The legacy ParaView writers (PARAVIEW_LEGACY, ASCII) still use find("_x"). They export Hessian parts as vectors with duplicate names. Please reuse the new XML grouping there, or support only XML output.
  • Tests: the unit test is 3D only and skips the Green-Gauss Hessian. A quadratic-field check in 2D and 3D would cover it.
  • The PR description still uses the old option names.

…ptive metric

- The adaptive metric is only computed by CSinglezoneDriver; error out in CConfig instead of silently writing zero fields
- Repeat the multizone check in the zone constructor, since zone configs inherit the multizone flag after SetPostprocessing
…able, time step

- Use the time step the solver actually takes (GetDelta_UnstTimeND) instead of the TIME_STEP input, which is zero with UNST_CFL_NUMBER
- Accumulate dt/2 (|H_prev| + |H|) per interval, so the trapezoidal rule is exact for variable time steps and the endpoints get half weight without knowing which sample is last
- Remove the last-step half-weight subtraction from FinalizeAdaptiveMetric and warn when the metric has a single sample
… 2D and 3D

- Add a quadratic-field test checking that the Green-Gauss Hessian is exact at points at least two layers inside a uniform Cartesian mesh, in 2D and 3D
- Run the normalization test (identity, rank-one, and zero Hessians) in 2D and 3D on the same 9-node mesh
…e tensors as TENSORS

- PARAVIEW_ASCII and PARAVIEW_LEGACY group vector components only for complete adjacent sets, instead of matching "_x" anywhere in the name
- Write Hessians and adaptive metrics as legacy TENSORS (full symmetric 3x3, padded in 2D like the XML writer) instead of vectors with duplicate names
- Add CFileWriter::GetSymmetricTensor, shared by both writers
- SU2_MPI with MPI_DOUBLE expects su2double, which is an AD type in AD and direct differentiation builds; reducing passivedouble buffers read and wrote past their end there
@bmunguia

bmunguia commented Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Ok here's a summary of my recent changes:

  • MPI type of the integral reduction: SelectMPIWrapper<passivedouble> is only specialized for CODI_REVERSE_TYPE, so in DD builds it still goes through MeDiPack, which maps MPI_DOUBLE to AMPI_ADOUBLE. With a DD + AddressSanitizer build, the previous reduction reads 48 bytes from the 24-byte integral vector (3 sensors):
    ERROR: AddressSanitizer: heap-buffer-overflow
    READ of size 48 ...
        #4 MPI_Allreduce
        #5 medi::AMPI_Allreduce_global<medi::MpiTypeInterface>(...)
        #6 integrateAdaptiveMetric(CGeometry const&, CConfig const&, ...)
    ... is located 0 bytes after 24-byte region allocated in integrateAdaptiveMetric
    
    Instead of the suggested fix, the integrals are now copied (since they're small anyway) into su2double buffers for the SU2_MPI reduction and converted back; that runs clean under AddressSanitizer (serial and 2 ranks) with the same integrals as the normal build
  • Time step: the unsteady metric now uses the step the solver actually takes (GetDelta_UnstTimeND()), so UNST_CFL_NUMBER without TIME_STEP now works, and the trapezoidal temporal integration now handles variable time steps
  • Unsupported drivers: multizone, harmonic balance, and the discrete adjoint are now rejected in CConfig, like periodic boundaries
  • Legacy ParaView writers: the field grouping is now shared by all ParaView writers (CFileWriter::ClassifyFields). PARAVIEW_ASCII and PARAVIEW_LEGACY group vectors only for complete adjacent component sets, and write the Hessians/metrics as TENSORS, like the XML writer
  • Tests: the unit tests now run in 2D and 3D, and include a Green-Gauss Hessian check on a quadratic field
  • PR description: updated with the new option names and behavior

FYI @bigfooted: the same DD + AddressSanitizer build also reports this pattern in develop in CDriver::InitializeGeometryFVM (added in #2863), on every FVM run:

ERROR: AddressSanitizer: stack-buffer-overflow
READ of size 16 ...
    #4 MPI_Allreduce
    #5 medi::AMPI_Allreduce_global<medi::MpiTypeInterface>(...)
    #6 CDriver::InitializeGeometryFVM(CConfig*, CGeometry**&)::{lambda(CGeometry const*)#1}::operator()
    [160, 168) 'vmin' (line 812) <== Memory access at offset 168 overflows this variable

Maybe it's harmless, though.

@bigfooted @rois1995 regarding the website page, I'd be happy to help. I can do a quick write-up of my examples, including visualizing the sizing tensor field in ParaView (via a Programmable Filter for now, but I could also directly output it from SU2, either as part of this PR or a separate one if you just want to merge this one), and move them to the Tutorials repo. Andrea/Alberto could then cover the adaptation loop once their implementation is in, if that works for you?

@rois1995 rois1995 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, all points are fixed. Good catch on the DD case of the MPI wrapper.

Comment thread SU2_CFD/src/solvers/CSolver.cpp Resolved
@bigfooted

Copy link
Copy Markdown
Contributor

@bmunguia if you do one last check for the final points of @rois1995 I think you can merge (I think you have permissions set for that).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants