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 The line searches @ref LineSearchType::Simple, @ref LineSearchType::Armijo, @ref
144 * LineSearchType::WolfeWeak and @ref LineSearchType::WolfeStrong test a merit: the objective,
145 * except that terms without a potential may count their work along the step instead of their
146 * energy. A step that fails the test is tested on the slope of the merit along the step instead
147 * if its merit change is within an estimate of the merit's rounding error or the step is so short
148 * that rounding error can dominate the change.
149 */
150enum struct LineSearchType {
151 /** @brief No line search. May substantially degrade stability. */
153
154 /**
155 * @brief Simple line search. Accepts a step if the merit does not increase by more than a
156 * specified relative tolerance.
157 *
158 * @see NonLinearSolverParams::lineSearchMaxRelIncrease. */
160
161 /**
162 * @brief Line search with Armijo condition.
163 *
164 * @see NonLinearSolverParams::lineSearchWolfe1
165 */
167
168 /**
169 * @brief Line search with weak Wolfe conditions.
170 *
171 * @details Steps are no longer than the full step. A trial that meets the 1st condition, but
172 * along which the merit still decreases too steeply for the 2nd, is accepted if it is the
173 * full step and otherwise leads to longer trials. If no trial meets both conditions, the line
174 * search takes the longest such trial, if any, at the cost of one more assembly unless it was
175 * the last.
176 *
177 * @see NonLinearSolverParams::lineSearchWolfe1, NonLinearSolverParams::lineSearchWolfe2
178 */
180
181 /**
182 * @brief Line search with strong Wolfe conditions.
183 *
184 * @details Like @ref LineSearchType::WolfeWeak, but also rejects a trial along which the
185 * merit increases too steeply for the strong 2nd condition.
186 *
187 * @see NonLinearSolverParams::lineSearchWolfe1, NonLinearSolverParams::lineSearchWolfe2
188 */
190
191 /**
192 * @brief Line search with residual norm condition. Accepts a step if the residual norm does not
193 * increase.
194 *
195 * @note Does not use the merit. When the residual norm cannot be reduced, e.g., in highly
196 * non-convex regions, failed searches keep short steps, which can make objects move slower than
197 * they should.
198 */
200
201 /** @brief Number of line search type enum values. */
203
204 /** @brief Default line search type. */
206};
207} // namespace superdex
208
210MOCHI_ENUM_ITEM(None)
211MOCHI_ENUM_ITEM(Simple)
212MOCHI_ENUM_ITEM(Armijo)
213MOCHI_ENUM_ITEM(WolfeWeak)
214MOCHI_ENUM_ITEM(WolfeStrong)
215MOCHI_ENUM_ITEM(ResidualNorm)
216MOCHI_ENUM_COUNT(Count)
218
219namespace superdex {
220/** @brief Strategies to select the relative tolerance of the linear solver (aka forcing term). */
222 /** @brief Constant relative tolerance. */
224
225 /**
226 * @brief Eisenstat-Walker strategy 1.
227 *
228 * @note Should be used with @ref LinearSolverConvergenceNorm::ResidualL2 or @ref
229 * LinearSolverConvergenceNorm::ResidualPerActorWeighted. Other norms may yield suboptimal forcing
230 * terms.
231 * @note Not recommended for use with quasi-Newton methods (e.g., @ref NonLinearSolverType::BFGS,
232 * @ref NonLinearSolverType::SR1).
233 *
234 * @see [Choosing the Forcing Terms in an Inexact Newton Method, Choice 1 (Eisenstat and Walker,
235 * 1994)](https://softlib.rice.edu/pub/CRPC-TRs/reports/CRPC-TR94463.pdf)
236 */
238
239 /**
240 * @brief Eisenstat-Walker strategy 2.
241 *
242 * @note Not recommended for use with quasi-Newton methods (e.g., @ref NonLinearSolverType::BFGS,
243 * @ref NonLinearSolverType::SR1).
244 *
245 * @see [Choosing the Forcing Terms in an Inexact Newton Method, Choice 2 (Eisenstat and Walker,
246 * 1994)](https://softlib.rice.edu/pub/CRPC-TRs/reports/CRPC-TR94463.pdf)
247 */
249
250 /** @brief Number of linear tolerance strategy enum values. */
252
253 /** @brief Default linear tolerance strategy. */
255};
256} // namespace superdex
257
259MOCHI_ENUM_ITEM(Constant)
260MOCHI_ENUM_ITEM(EisenstatWalker1)
261MOCHI_ENUM_ITEM(EisenstatWalker2)
262MOCHI_ENUM_COUNT(Count)
264
265namespace superdex {
266/**
267 * @brief Convergence monitoring mode for the non-linear solver residual.
268 *
269 * @note Convergence is evaluated per simulation island, not scene-wide. Each island is solved
270 * independently, and the selected mode determines how convergence is assessed within that island.
271 * @note The norm used to monitor divergence via @ref NonLinearSolverParams::absDivTol and @ref
272 * NonLinearSolverParams::relDivTol is always the L2 norm, irrespective of this setting.
273 * @note The norm used to monitor stagnation via @ref NonLinearSolverParams::relStepTol is always
274 * the L2 norm, irrespective of this setting.
275 *
276 * @see NonLinearSolverParams::absTol, NonLinearSolverParams::relTol
277 */
279 /**
280 * @brief Use global, unweighted residual norm for convergence checks within each simulation
281 * island.
282 *
283 * @details Convergence is determined by the global residual norm within each simulation island:
284 * |r| <= absTol or |r| <= relTol * |r0|
285 *
286 * @note The default @ref NonLinearSolverParams::absTol and @ref NonLinearSolverParams::relTol are
287 * not generally appropriate for this mode: set them for the problem's residual scale.
288 */
290
291 /**
292 * @brief Use per-actor weighted residual norms for convergence checks.
293 *
294 * @details Each actor uses a per-actor weighted L2 norm |r_a|_W = sqrt(Σᵢ wᵢ·rᵢ²), where
295 * weights normalize force/torque residuals by characteristic force/torque. All actors must
296 * satisfy their individual criteria: |r_a|_W <= absTol or |r_a|_W <= relTol * |r0_a|_W
297 *
298 * @note Weights are derived from inertia properties. Actors with zero inertia receive uniform
299 * weights, which provide no physical normalization. For quasi-static problems, @ref
300 * NonLinearSolverConvergenceMode::Global mode is recommended.
301 */
303
304 /** @brief Number of convergence monitoring mode enum values. */
306
307 /** @brief Default convergence monitoring mode. */
309};
310} // namespace superdex
311
313MOCHI_ENUM_ITEM(Global)
314MOCHI_ENUM_ITEM(PerActorWeighted)
315MOCHI_ENUM_COUNT(Count)
317
318namespace superdex {
319/**
320 * @brief Default tolerance for the L2 norm of the non-linear solver's raw linear-solve increment.
321 * Avoids attempting to solve beyond the floating-point noise floor.
322 *
323 * @see NonLinearSolverParams::relStepTol.
324 */
325constexpr real kDefaultRelStepTol = 10_r * std::numeric_limits<real>::epsilon();
326
327/** @brief Parameters for the non-linear solver. */
329 /** @brief Non-linear solver type. */
331
332 /**
333 * @brief Every how many non-linear iterations to assemble the dresidual matrix.
334 *
335 * @note For Newton's method, set to >1 to reuse the dresidual across iterations.
336 * @note For quasi-Newton methods (e.g., BFGS, SR1), it must be >1 and indicates every how many
337 * iterations to restart the algorithm with the actual dresidual.
338 */
340
341 // Stopping criteria. The solver terminates when any of the criteria is satisfied.
342
343 /** @brief Maximum number of non-linear iterations. */
344 int maxIter = 4;
345
346 /**
347 * @brief Maximum elapsed time [s].
348 *
349 * @note The solve terminates if the elapsed time exceeds this threshold.
350 * @note 0 means no time limit.
351 */
353
354 /**
355 * @brief Convergence monitoring mode.
356 *
357 * @note Applies to @ref absTol and @ref relTol.
358 */
360
361 /**
362 * @brief Absolute residual norm tolerance for convergence.
363 *
364 * @note Also the residual below which @ref LinearSolverConvergenceNorm::ResidualPerActorWeighted
365 * stops normalizing an actor by its own residual.
366 * @note With a negative @ref LinearSolverParams::absTol, it also determines the linear solver's
367 * absolute tolerance where supported (see @ref LinearSolverParams::absTol).
368 */
369 real absTol = 1e-3_r;
370
371 /**
372 * @brief Relative residual norm tolerance for convergence, relative to the initial residual.
373 *
374 * @note With a negative @ref LinearSolverParams::absTol, it also determines the linear solver's
375 * absolute tolerance where supported (see @ref LinearSolverParams::absTol).
376 * @note 0 disables this criterion.
377 */
379
380 /**
381 * @brief Relative tolerance on the L2 norm of the raw linear-solve increment before line search
382 * scaling.
383 *
384 * @note The solve terminates with @ref ConvergenceStatus::Stopped status if |dx|/|x| is below
385 * this threshold (i.e., the step norm is below this fraction of the current solution norm).
386 * @note 0 disables this criterion.
387 * @note Default is @ref kDefaultRelStepTol.
388 */
390
391 /** @brief Stop the solve if the line search figure of merit does not improve from the previous
392 * iteration. */
394
395 // Retries
396
397 /** @brief Positive Semi-Definite (PSD) projection mode for the dresidual matrix. */
399
400 // Explosion control
401
402 /** @brief Enable heuristic explosion prevention. */
403 bool explosionControl = true;
404
405 /**
406 * @brief Absolute divergence tolerance.
407 *
408 * @note Triggers explosion control if residual norm exceeds this value.
409 * @note Used only if @ref explosionControl is true.
410 */
412
413 /**
414 * @brief Relative divergence tolerance, relative to the initial residual.
415 *
416 * @note Triggers explosion control if relative residual norm exceeds this value.
417 * @note Used only if @ref explosionControl is true.
418 */
420
421 // Line search
422
423 /**
424 * @brief Maximum number of line search iterations.
425 *
426 * @note Must be >= 1 unless @ref lineSearchType is @ref LineSearchType::None.
427 */
429
430 /**
431 * @brief Step length reduction factor for line search.
432 *
433 * @note Must be in (0, 1).
434 */
436
437 /**
438 * @brief Wolfe condition parameter c1 (sufficient decrease).
439 *
440 * @note Must be in (0, 1).
441 * @note Used only by @ref LineSearchType::Armijo, @ref LineSearchType::WolfeWeak, and @ref
442 * LineSearchType::WolfeStrong line search types.
443 */
445
446 /**
447 * @brief Wolfe condition parameter c2 (curvature).
448 *
449 * @note Must be in (@ref lineSearchWolfe1, 1).
450 * @note Used only by @ref LineSearchType::WolfeWeak and @ref LineSearchType::WolfeStrong line
451 * search types.
452 */
454
455 /**
456 * @brief Maximum relative increase in the merit to accept the step.
457 *
458 * @note Only applies to @ref LineSearchType::Simple.
459 * @note An increase beyond this maximum is tested on the slope of the merit along the step
460 * instead if it is within an estimate of the merit's rounding error or the step is so short that
461 * rounding error can dominate the increase (see @ref LineSearchType).
462 */
464
465 /** @brief Line search type. */
467
468 // Linear tolerance strategy
469
470 /** @brief Strategy for adaptive linear solver tolerance (forcing term). */
472
473 // Other
474
475 /** @brief Verbosity level for logging output. */
477
478#if MOCHI_LANGUAGE_CPP20
479 bool operator==(NonLinearSolverParams const&) const = default;
480#endif
481
505};
506
507} // namespace superdex
LinearToleranceStrategy
Strategies to select the relative tolerance of the linear solver (aka forcing term).
@ EisenstatWalker2
Eisenstat-Walker strategy 2.
@ EisenstatWalker1
Eisenstat-Walker strategy 1.
@ Default
Default linear tolerance strategy.
@ 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.
@ 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:329
#define MOCHI_ENUM_END()
Definition reflection.h:330
#define MOCHI_STRUCT_END()
Definition reflection.h:333
#define MOCHI_ENUM_BEGIN(name)
Definition reflection.h:327
#define MOCHI_FIELD(name)
Definition reflection.h:351
#define MOCHI_STRUCT_BEGIN(name)
Definition reflection.h:332
#define MOCHI_ENUM_ITEM(name)
Definition reflection.h:328
Parameters for the non-linear solver.
real lineSearchMaxRelIncrease
Maximum relative increase in the merit 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.