SuperDex Physics C++ API
Loading...
Searching...
No Matches
nonlinear_solver_params.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19// PLEASE DO NOT ADD OTHER INCLUDES HERE. This header is included in the mochi_physics public API.
23
24#include <limits>
25
26namespace superdex {
27/** @brief Convergence status of the non-linear solver. */
28enum struct ConvergenceStatus {
29 // WARNING: Values are ordered by severity: None < Converged < Stopped < Diverged. This ordering
30 // enables worst-status accumulation via Max.
31
32 /** @brief Convergence status has not been set. */
34
35 /** @brief Solver converged to the requested tolerance. */
37
38 /**
39 * @brief Solver met at least one stopping criterion without converging to the requested
40 * tolerance.
41 *
42 * @note This does not necessarily indicate a problem: the residual tolerances may be stricter
43 * than required. If the maximum-iteration limit (@ref NonLinearSolverParams::maxIter) caused the
44 * status, increase it only if additional iterations materially change the results.
45 */
47
48 /** @brief Solver diverged. Some form of solution reset may have been used. */
50
51 /** @brief Number of convergence status enum values. */
53};
54static_assert(
55 static_cast<int>(ConvergenceStatus::Count) == 4 &&
59 "ConvergenceStatus must be ordered by severity.");
60} // namespace superdex
61
64MOCHI_ENUM_ITEM(Converged)
65MOCHI_ENUM_ITEM(Stopped)
66MOCHI_ENUM_ITEM(Diverged)
69
70namespace superdex {
71/** @brief Positive Semi-Definite (PSD) projection modes for the dresidual matrix. */
72// clang-format off
74 Never, ///< Never project to PSD.
75 Always, ///< Always project to PSD.
76 IfFailRetry, ///< If one non-linear iteration fails, retry the iteration projecting to PSD.
77 IfFailAlways, ///< If one non-linear iteration fails, retry the iteration projecting to PSD and continue projecting in all the remaining iterations of the solve.
78 Count, ///< Number of PSD projection mode enum values.
79 Default = Always ///< Default PSD projection mode.
80};
81// clang-format on
82} // namespace superdex
83
85MOCHI_ENUM_ITEM(Never)
86MOCHI_ENUM_ITEM(Always)
87MOCHI_ENUM_ITEM(IfFailRetry)
88MOCHI_ENUM_ITEM(IfFailAlways)
91
92namespace superdex {
93/** @brief Non-linear solver types. */
95 /** @brief Newton's method. */
97
98 /**
99 * @brief Broyden-Fletcher-Goldfarb-Shanno (BFGS) method.
100 *
101 * @note The initial approximation of the dresidual is the actual dresidual (i.e., the first
102 * iteration matches Newton's method).
103 * @note The algorithm is restarted with the actual dresidual every @ref
104 * NonLinearSolverParams::dResidualAssemblyPeriod iterations, or immediately if the line search
105 * fails to improve the figure of merit it monitors or the linear solver fails to converge.
106 *
107 * @see NonLinearSolverParams::dResidualAssemblyPeriod
108 */
110
111 /**
112 * @brief Symmetric Rank-One (SR1) method.
113 *
114 * @note The initial approximation of the dresidual is the actual dresidual (i.e., the first
115 * iteration matches Newton's method).
116 * @note The algorithm is restarted with the actual dresidual every @ref
117 * NonLinearSolverParams::dResidualAssemblyPeriod iterations, or immediately if the line search
118 * fails to improve the figure of merit it monitors or the linear solver fails to converge.
119 *
120 * @see NonLinearSolverParams::dResidualAssemblyPeriod
121 */
123
124 /** @brief Number of non-linear solver type enum values. */
126
127 /** @brief Default non-linear solver type. */
129};
130} // namespace superdex
131
133MOCHI_ENUM_ITEM(Newton)
134MOCHI_ENUM_ITEM(BFGS)
136MOCHI_ENUM_COUNT(Count)
138
139namespace superdex {
140/**
141 * @brief Line search methods for the non-linear solver.
142 *
143 * @note In the line searches that test the objective (@ref LineSearchType::Simple,
144 * @ref LineSearchType::Armijo, @ref LineSearchType::WolfeWeak, @ref LineSearchType::WolfeStrong and
145 * @ref LineSearchType::ArmijoOrResidualNorm), a step that fails the test but changes the objective
146 * by no more than an estimate of its rounding error is tested on the slope of the objective along
147 * the step instead.
148 */
149enum struct LineSearchType {
150 /** @brief No line search. May substantially degrade stability. */
152
153 /**
154 * @brief Simple line search. Accepts a step if the objective function does not increase by more
155 * than a specified relative tolerance.
156 *
157 * @see NonLinearSolverParams::lineSearchMaxRelIncrease. */
159
160 /**
161 * @brief Line search with Armijo condition.
162 *
163 * @see NonLinearSolverParams::lineSearchWolfe1
164 */
166
167 /**
168 * @brief Line search with weak Wolfe conditions.
169 *
170 * @see NonLinearSolverParams::lineSearchWolfe1, NonLinearSolverParams::lineSearchWolfe2
171 */
173
174 /**
175 * @brief Line search with strong Wolfe conditions.
176 *
177 * @see NonLinearSolverParams::lineSearchWolfe1, NonLinearSolverParams::lineSearchWolfe2
178 */
180
181 /**
182 * @brief Line search with residual norm condition. Accepts a step if the residual norm decreases.
183 *
184 * @note More robust than objective-based line searches (@ref LineSearchType::Simple, @ref
185 * LineSearchType::Armijo, @ref LineSearchType::WolfeWeak, @ref LineSearchType::WolfeStrong) but
186 * may degrade non-linear solver convergence in non-convex problems. In highly non-convex regions
187 * where the residual norm cannot be reduced, it may cause objects to move at slower velocity than
188 * they should due to the inability to take valid steps. Consider using an objective-based line
189 * search in that case.
190 */
192
193 /**
194 * @brief Line search that accepts either the Armijo or the residual norm condition.
195 *
196 * @note It combines the robustness of objective-based criteria when the iteration is far from the
197 * solution, with residual-based criteria when it is near the solution (particularly useful with
198 * single precision). It requires slightly higher cost per line-search iteration.
199 */
201
202 /** @brief Number of line search type enum values. */
204
205 /** @brief Default line search type. */
207};
208} // namespace superdex
209
211MOCHI_ENUM_ITEM(None)
212MOCHI_ENUM_ITEM(Simple)
213MOCHI_ENUM_ITEM(Armijo)
214MOCHI_ENUM_ITEM(WolfeWeak)
215MOCHI_ENUM_ITEM(WolfeStrong)
216MOCHI_ENUM_ITEM(ResidualNorm)
217MOCHI_ENUM_ITEM(ArmijoOrResidualNorm)
218MOCHI_ENUM_COUNT(Count)
220
221namespace superdex {
222/** @brief Strategies to select the relative tolerance of the linear solver (aka forcing term). */
224 /** @brief Constant relative tolerance. */
226
227 /**
228 * @brief Eisenstat-Walker strategy no. 1.
229 *
230 * @note Should be used with @ref LinearSolverConvergenceNorm::ResidualL2. Other norms may yield
231 * suboptimal forcing terms.
232 * @note Not recommended for use with quasi-Newton methods (e.g., @ref NonLinearSolverType::BFGS,
233 * @ref NonLinearSolverType::SR1).
234 *
235 * @see [Choosing the Forcing Terms in an Inexact Newton Method, Choice 1 (Eisenstat and Walker,
236 * 1994)](https://softlib.rice.edu/pub/CRPC-TRs/reports/CRPC-TR94463.pdf)
237 */
239
240 /**
241 * @brief Eisenstat-Walker strategy no. 2.
242 *
243 * @note Not recommended for use with quasi-Newton methods (e.g., @ref NonLinearSolverType::BFGS,
244 * @ref NonLinearSolverType::SR1).
245 *
246 * @see [Choosing the Forcing Terms in an Inexact Newton Method, Choice 2 (Eisenstat and Walker,
247 * 1994)](https://softlib.rice.edu/pub/CRPC-TRs/reports/CRPC-TR94463.pdf)
248 */
250
251 /**
252 * @brief Custom Eisenstat-Walker strategy: eta = max(min(1/(2+k), sqrt(|r|)), eta_0), where `k`
253 * is the non-linear iteration number, `|r|` is the L2-norm of the nonlinear residual, and
254 * `eta_0` is @ref LinearSolverParams::relTol.
255 *
256 * @note Should be used with @ref LinearSolverConvergenceNorm::ResidualL2. Other norms may yield
257 * suboptimal forcing terms.
258 * @note Not recommended for use with quasi-Newton methods (e.g., @ref NonLinearSolverType::BFGS,
259 * @ref NonLinearSolverType::SR1).
260 */
262
263 /** @brief Number of linear tolerance strategy enum values. */
265
266 /** @brief Default linear tolerance strategy. */
268};
269} // namespace superdex
270
272MOCHI_ENUM_ITEM(Constant)
273MOCHI_ENUM_ITEM(EisenstatWalker1)
274MOCHI_ENUM_ITEM(EisenstatWalker2)
275MOCHI_ENUM_ITEM(EisenstatWalker3)
276MOCHI_ENUM_COUNT(Count)
278
279namespace superdex {
280/**
281 * @brief Convergence monitoring mode for the non-linear solver residual.
282 *
283 * @note Convergence is evaluated per simulation island, not scene-wide. Each island is solved
284 * independently, and the selected mode determines how convergence is assessed within that island.
285 * @note The norm used to monitor divergence via @ref NonLinearSolverParams::absDivTol and @ref
286 * NonLinearSolverParams::relDivTol is always the L2 norm, irrespective of this setting.
287 * @note The norm used to monitor stagnation via @ref NonLinearSolverParams::relStepTol is always
288 * the L2 norm, irrespective of this setting.
289 *
290 * @see NonLinearSolverParams::absTol, NonLinearSolverParams::relTol
291 */
293 /**
294 * @brief Use global, unweighted residual norm for convergence checks within each simulation
295 * island.
296 *
297 * @details Convergence is determined by the global residual norm within each simulation island:
298 * |r| <= absTol or |r| <= relTol * |r0|
299 */
301
302 /**
303 * @brief Use per-actor weighted residual norms for convergence checks.
304 *
305 * @details Each actor uses a per-actor weighted L2 norm |r_a|_W = sqrt(Σᵢ wᵢ·rᵢ²), where
306 * weights normalize force/torque residuals by characteristic force/torque. All actors must
307 * satisfy their individual criteria: |r_a|_W <= absTol or |r_a|_W <= relTol * |r0_a|_W
308 *
309 * @note Weights are derived from inertia properties. Actors with zero inertia receive uniform
310 * weights, which provide no physical normalization. For quasi-static problems, @ref
311 * NonLinearSolverConvergenceMode::Global mode is recommended.
312 */
314
315 /** @brief Number of convergence monitoring mode enum values. */
317
318 /** @brief Default convergence monitoring mode. */
320};
321} // namespace superdex
322
324MOCHI_ENUM_ITEM(Global)
325MOCHI_ENUM_ITEM(PerActorWeighted)
326MOCHI_ENUM_COUNT(Count)
328
329namespace superdex {
330/**
331 * @brief Default tolerance for the L2 norm of the non-linear solver's raw linear-solve increment.
332 * Avoids attempting to solve beyond the floating-point noise floor.
333 *
334 * @see NonLinearSolverParams::relStepTol.
335 */
336constexpr real kDefaultRelStepTol = 10_r * std::numeric_limits<real>::epsilon();
337
338/** @brief Parameters for the non-linear solver. */
340 /** @brief Non-linear solver type. */
342
343 /**
344 * @brief Every how many non-linear iterations to assemble the dresidual matrix.
345 *
346 * @note For Newton's method, set to >1 to reuse the dresidual across iterations.
347 * @note For quasi-Newton methods (e.g., BFGS, SR1), it must be >1 and indicates every how many
348 * iterations to restart the algorithm with the actual dresidual.
349 */
351
352 // Stopping criteria. The solver terminates when any of the criteria is satisfied.
353
354 /** @brief Maximum number of non-linear iterations. */
355 int maxIter = 4;
356
357 /**
358 * @brief Maximum elapsed time [s].
359 *
360 * @note The solve terminates if the elapsed time exceeds this threshold.
361 * @note 0 means no time limit.
362 */
364
365 /**
366 * @brief Convergence monitoring mode.
367 *
368 * @note Applies to @ref absTol and @ref relTol.
369 */
371
372 /** @brief Absolute residual norm tolerance for convergence. */
373 real absTol = 1e-3_r;
374
375 /** @brief Relative residual norm tolerance for convergence, relative to the initial residual. */
376 real relTol = 1e-6_r;
377
378 /**
379 * @brief Relative tolerance on the L2 norm of the raw linear-solve increment before line search
380 * scaling.
381 *
382 * @note The solve terminates with @ref ConvergenceStatus::Stopped status if |dx|/|x| is below
383 * this threshold (i.e., the step norm is below this fraction of the current solution norm).
384 * @note 0 disables this criterion.
385 * @note Default is @ref kDefaultRelStepTol.
386 */
388
389 /** @brief Stop the solve if the line search figure of merit does not improve from the previous
390 * iteration. */
392
393 // Retries
394
395 /** @brief Positive Semi-Definite (PSD) projection mode for the dresidual matrix. */
397
398 // Explosion control
399
400 /** @brief Enable heuristic explosion prevention. */
401 bool explosionControl = true;
402
403 /**
404 * @brief Absolute divergence tolerance.
405 *
406 * @note Triggers explosion control if residual norm exceeds this value.
407 * @note Used only if @ref explosionControl is true.
408 */
410
411 /**
412 * @brief Relative divergence tolerance, relative to the initial residual.
413 *
414 * @note Triggers explosion control if relative residual norm exceeds this value.
415 * @note Used only if @ref explosionControl is true.
416 */
418
419 // Line search
420
421 /**
422 * @brief Maximum number of line search iterations.
423 *
424 * @note Must be >= 1 unless @ref lineSearchType is @ref LineSearchType::None.
425 */
427
428 /**
429 * @brief Step length reduction factor for line search.
430 *
431 * @note Must be in (0, 1).
432 */
434
435 /**
436 * @brief Wolfe condition parameter c1 (sufficient decrease).
437 *
438 * @note Must be in (0, 1).
439 * @note Used only by @ref LineSearchType::Armijo, @ref LineSearchType::WolfeWeak, @ref
440 * LineSearchType::WolfeStrong, and @ref LineSearchType::ArmijoOrResidualNorm line search types.
441 */
443
444 /**
445 * @brief Wolfe condition parameter c2 (curvature).
446 *
447 * @note Must be in (@ref lineSearchWolfe1, 1).
448 * @note Used only by @ref LineSearchType::WolfeWeak and @ref LineSearchType::WolfeStrong line
449 * search types.
450 */
452
453 /**
454 * @brief Maximum relative increase in the objective to accept the step.
455 *
456 * @note Only applies to @ref LineSearchType::Simple.
457 * @note An increase beyond this maximum but within an estimate of the objective's rounding error
458 * is tested on the slope of the objective along the step instead (see @ref LineSearchType).
459 */
461
462 /** @brief Line search type. */
464
465 // Linear tolerance strategy
466
467 /** @brief Strategy for adaptive linear solver tolerance (forcing term). */
469
470 // Other
471
472 /** @brief Verbosity level for logging output. */
474
475#if MOCHI_LANGUAGE_CPP20
476 bool operator==(NonLinearSolverParams const&) const = default;
477#endif
478
502};
503
504} // namespace superdex
LinearToleranceStrategy
Strategies to select the relative tolerance of the linear solver (aka forcing term).
@ EisenstatWalker2
Eisenstat-Walker strategy no.
@ EisenstatWalker1
Eisenstat-Walker strategy no.
@ Default
Default linear tolerance strategy.
@ EisenstatWalker3
Custom Eisenstat-Walker strategy: eta = max(min(1/(2+k), sqrt(|r|)), eta_0), where k is the non-linea...
@ Constant
Constant relative tolerance.
VerbosityLevel
Verbosity levels for solvers and optimizers.
@ Warning
Errors and warnings.
ConvergenceStatus
Convergence status of the non-linear solver.
@ None
Convergence status has not been set.
@ Stopped
Solver met at least one stopping criterion without converging to the requested tolerance.
@ Converged
Solver converged to the requested tolerance.
@ Count
Number of convergence status enum values.
NonLinearSolverType
Non-linear solver types.
@ BFGS
Broyden-Fletcher-Goldfarb-Shanno (BFGS) method.
@ SR1
Symmetric Rank-One (SR1) method.
@ Default
Default non-linear solver type.
LineSearchType
Line search methods for the non-linear solver.
@ ArmijoOrResidualNorm
Line search that accepts either the Armijo or the residual norm condition.
@ WolfeStrong
Line search with strong Wolfe conditions.
@ ResidualNorm
Line search with residual norm condition.
@ Default
Default line search type.
@ Armijo
Line search with Armijo condition.
@ WolfeWeak
Line search with weak Wolfe conditions.
PsdProjectionMode
Positive Semi-Definite (PSD) projection modes for the dresidual matrix.
@ IfFailAlways
If one non-linear iteration fails, retry the iteration projecting to PSD and continue projecting in a...
@ IfFailRetry
If one non-linear iteration fails, retry the iteration projecting to PSD.
@ Default
Default PSD projection mode.
constexpr real kDefaultRelStepTol
Default tolerance for the L2 norm of the non-linear solver's raw linear-solve increment.
@ None
Invalid actor type.
Definition mochi_enums.h:26
@ Count
Number of actor type enum values.
Definition mochi_enums.h:38
NonLinearSolverConvergenceMode
Convergence monitoring mode for the non-linear solver residual.
@ PerActorWeighted
Use per-actor weighted residual norms for convergence checks.
@ Global
Use global, unweighted residual norm for convergence checks within each simulation island.
@ Default
Default convergence monitoring mode.
#define MOCHI_ENUM_COUNT(name)
Definition reflection.h:275
#define MOCHI_ENUM_END()
Definition reflection.h:276
#define MOCHI_STRUCT_END()
Definition reflection.h:279
#define MOCHI_ENUM_BEGIN(name)
Definition reflection.h:273
#define MOCHI_FIELD(name)
Definition reflection.h:293
#define MOCHI_STRUCT_BEGIN(name)
Definition reflection.h:278
#define MOCHI_ENUM_ITEM(name)
Definition reflection.h:274
Parameters for the non-linear solver.
real lineSearchMaxRelIncrease
Maximum relative increase in the objective to accept the step.
real lineSearchWolfe1
Wolfe condition parameter c1 (sufficient decrease).
bool operator==(NonLinearSolverParams const &) const =default
bool explosionControl
Enable heuristic explosion prevention.
real relDivTol
Relative divergence tolerance, relative to the initial residual.
double maxElapsedTimeSeconds
Maximum elapsed time [s].
real lineSearchWolfe2
Wolfe condition parameter c2 (curvature).
VerbosityLevel verbosity
Verbosity level for logging output.
PsdProjectionMode psdProjMode
Positive Semi-Definite (PSD) projection mode for the dresidual matrix.
real relTol
Relative residual norm tolerance for convergence, relative to the initial residual.
real absTol
Absolute residual norm tolerance for convergence.
NonLinearSolverType solverType
Non-linear solver type.
bool stopIfNoImprovement
Stop the solve if the line search figure of merit does not improve from the previous iteration.
real relStepTol
Relative tolerance on the L2 norm of the raw linear-solve increment before line search scaling.
real absDivTol
Absolute divergence tolerance.
NonLinearSolverConvergenceMode convergenceMode
Convergence monitoring mode.
real lineSearchAlpha
Step length reduction factor for line search.
LinearToleranceStrategy linearToleranceStrategy
Strategy for adaptive linear solver tolerance (forcing term).
LineSearchType lineSearchType
Line search type.
int maxIter
Maximum number of non-linear iterations.
int lineSearchMaxIter
Maximum number of line search iterations.
int dResidualAssemblyPeriod
Every how many non-linear iterations to assemble the dresidual matrix.