pysolvegn.solve#
- solve(terms, p0, parametrization=None, *, max_iteration=None, max_time=None, ftol=None, xtol=None, gtol=None, atol=None, ptol=None, callback_func=None, update_func=None, damping=None, lm_conf=None, line_search=False, line_search_conf=None, verbosity=0, history=False, history_details=None, history_length=None)[source]#
Function to solve a least squares problem using the Gauss-Newton method with robust cost functions.
The function accepts multiple terms in the least squares problem, each with its own residual function \(r_i\), Jacobian function \(J_i = \frac{\partial r_i}{\partial \mathbf{p}}, weight :math:`w_i\), and loss function :math`rho_i`, solving the following optimization problem:
\[\min_{\mathbf{p}_{in}} \frac{1}{2} \sum_{i} w_i \sum_j \rho_i\left(\| \mathbf{r}_{i,j}\left(P(\mathbf{p}_{in})\right) \|^2\right)\]Here \(\mathbf{p}_{in}\) represents the parameters actually optimized by the solver, and \(P\) is a parametric transformation such that:
\[\mathbf{p}_{out} = P(\mathbf{p}_{in})\]represents the parameters passed to the residual and Jacobian functions of each terms. The input parameters \(\mathbf{p}_{in}\) have shape
(n_parameters,). If no parametrization is provided, the identity transformation is implicitly used:\[P(\mathbf{p}_{in}) = \mathbf{p}_{in}\]See also
For more details on the notations for the optimization problem, please refer to the mathematical section of the documentation.
- Parameters:
terms (Union[Term, Sequence[Term]]) – The list of terms defining the least squares problem. Each term should be an instance of the
Termclass containing the residual function, Jacobian function, weight, and loss function defining the term. The residual and Jacobian functions of each term are evaluated using the output parametric parameters \(\mathbf{p}_{out} = P(\mathbf{p}_{in})\).p0 (ArrayLike) – The initial guess for the parameters optimized by the solver, with shape
(n_parameters,). If a parametrization is provided,p0represents the initial input parameters \(\mathbf{p}_{in}\) of the parametrization. The initial output parameters passed to the terms are obtained as \(\mathbf{p}_{out} = P(\mathbf{p}_{in})\). If no parametrization is provided,p0directly represents the parameters passed to the terms. The array will not be modified by this function. A copy of the parameters will be used for the optimization process.parametrization (Optional[Parametrization], optional (default=None)) – The parametrization defining the transformation from the parameters optimized by the solver to the parameters passed to the terms. If provided, the solver optimizes the input parameters \(\mathbf{p}_{in}\) with shape
(n_parameters,)of this parametrization.max_iteration (Optional[Integral], optional (default=None)) – Maximum number of optimization iterations. If provided, the optimization process is stopped after at most
max_iterationiterations. If None, no limit on the number of iterations is imposed.max_time (Optional[Real], optional (default=None)) – Stop criterion by the elapsed time of optimization. The optimization process is stopped when the time elapsed since the beginning of the optimization exceeds
max_timeseconds. If None, no limit on the computation time is considered. The time is checked after the evaluation of each iteration and between the trial steps of the Levenberg-Marquardt damping and of the line search (the trial step being tested is then not applied).ftol (Optional[Real], optional (default=None)) – Stop criterion by the change of the cost function value. The optimization process is stopped when
0 <= dF < ftol * Fwhere F is the cost function value anddF = F_previous - Fis the decrease of the cost function value between two iterations (an increase of the cost never satisfies this criterion). If None, this criterion is not considered. Not allowed if agHterm has nocost_func(ValueError).xtol (Optional[Real], optional (default=None)) – Stop criterion by the change of the optimized parameters. The optimization process is stopped when
||dp|| < xtol * (xtol + ||p||)where p is the input parameters \(\mathbf{p}_{in}\) and dp is the change of the input parameters between two iterations. If None, this criterion is not considered.gtol (Optional[Real], optional (default=None)) – Stop criterion by the optimality value. The optimization process is stopped when the optimality verifies
norm(g, ord=numpy.inf) < gtolwhere \(g\) is the scaled second term. If None, this criterion is not considered.atol (Optional[Real], optional (default=None)) – Stop criterion by the absolute cost function value. The optimization process is stopped when
F < atolwhere F is the cost function value. If None, this criterion is not considered. Not allowed if agHterm has nocost_func(ValueError).ptol (Optional[Real], optional (default=None)) – Stop criterion by the change of the optimized parameters. The optimization process is stopped when
norm(dp, ord=numpy.inf) < ptolwhere dp is the change of the input parameters \(\mathbf{p}_{in}\). If None, this criterion is not considered.callback_func (Optional[Callable[[Dict], bool]], optional (default=None)) –
A function called at each iteration, after the built-in stopping criteria, to implement custom stopping criteria. It receives a dictionary with the keys
"parameters","delta_parameters"(None at the first iteration),"cost","second_term"and"hessian"of the current iteration, and must return a boolean: True to continue, False to stop the optimization (success=False). If None, no callback function is used.Warning
"hessian"is not a copy: do not modify it in place (copy it first withhessian.copy()), as it is used afterwards to compute the update.update_func (Optional[Callable[[numpy.ndarray, numpy.ndarray], ArrayLike]], optional (default=None)) – A function that is called at the end of each iteration of the optimization process to modify the update of the parameters. The function should take (copies of) the current input parameters \(\mathbf{p}_{in}^{k}\) and the Gauss-Newton update \(\Delta\mathbf{p}_{in}\) (solution of \(\mathbf{H} \Delta\mathbf{p}_{in} = -\mathbf{g}\)), both with shape
(n_parameters,), and return the update \(\Delta\mathbf{p}_{in}^{*}\) actually applied, with shape(n_parameters,), such that \(\mathbf{p}_{in}^{k+1} = \mathbf{p}_{in}^{k} + \Delta\mathbf{p}_{in}^{*}\). The returned update is the one stored in the history ("delta_parameters"). With Levenberg-Marquardt (dampingnot None),update_funcis applied to each trial step before its cost is tested, so the applied update is the tested one. If None, the Gauss-Newton update is directly applied: \(\Delta\mathbf{p}_{in}^{*} = \Delta\mathbf{p}_{in}\).damping (Optional[str], optional (default=None)) –
The method used to compute the update \(\Delta\mathbf{p}_{in}\):
None: Gauss-Newton, the update is the solution of \(\mathbf{H} \Delta\mathbf{p}_{in} = -\mathbf{g}\) and is always applied.
"lm": Levenberg-Marquardt, the update is the solution of \((\mathbf{H} + \lambda \mathbf{I}) \Delta\mathbf{p}_{in} = -\mathbf{g}\), with the initial value \(\lambda = 10^{-3} \max(\mathrm{diag}(\mathbf{H}))\)."lm-diag": Levenberg-Marquardt with the Marquardt scaling, the update is the solution of \((\mathbf{H} + \lambda \mathbf{D}) \Delta\mathbf{p}_{in} = -\mathbf{g}\) where \(\mathbf{D} = \mathrm{diag}(\mathbf{H})\) (with a floor of \(10^{-12} \max(\mathrm{diag}(\mathbf{H}))\)), with the initial value \(\lambda = 10^{-3}\). Unlike"lm", the damping is insensitive to the scale of each parameter.
With
"lm"and"lm-diag", a trial step is accepted only if it does not increase the cost beyond its rounding noise (\(C_{new} \leq C + \eta\) with \(\eta = \text{noise} \times |C|\), seelm_conf): otherwise \(\lambda\) is multiplied by 10 and the system is solved again. After an accepted step, \(\lambda\) is divided by 10 (down to \(\varepsilon_m\) times its initial scale, below which \(\lambda \mathbf{D}\) is lost in the rounding of \(\mathbf{H}\)). If no acceptable step is found after 50 consecutive rejections, the optimization is stopped withsuccess=False. The value of \(\lambda\) is available in the history ("damping") and displayed withverbosity >= 2. These default values can be changed withlm_conf.Note
With Levenberg-Marquardt, the cost of every term must be computable to test the steps: all
gHterms must define acost_func.lm_conf (Optional[Mapping[str, Real]], optional (default=None)) –
Used only if
dampingis"lm"or"lm-diag". Dictionary to change the default settings of the Levenberg-Marquardt damping. The missing keys keep their default value:"initial_scale"(default1e-3): initial value of \(\lambda\) ("lm-diag"), or factor of \(\max(\mathrm{diag}(\mathbf{H}))\) ("lm")."factor"(default10.0, must be > 1): \(\lambda\) is multiplied by this factor after a rejected step and divided by it after an accepted step."max_rejections"(default50): maximum number of consecutive rejected steps before stopping withsuccess=False."diag_floor"(default1e-12): ("lm-diag"only) floor of \(\mathrm{diag}(\mathbf{H})\) relative to its maximum."noise"(default1e-13,>= 0): relative rounding noise of the cost \(\eta / |C|\) tolerated to accept a step (0.0for the strict condition \(C_{new} \leq C\)). At the machine precision the cost cannot decrease anymore, and this tolerance avoids rejecting steps (and increasing \(\lambda\)) in vain.
The complete configuration used is stored in
result.config["lm_conf"].line_search (bool, optional (default=False)) –
Used only if
dampingis None (Gauss-Newton). If False (default), the full Gauss-Newton step is always applied: \(\mathbf{H} \Delta\mathbf{p}_{in} = -\mathbf{g}\) and \(\mathbf{p}_{in}^{k+1} = \mathbf{p}_{in}^{k} + \Delta\mathbf{p}_{in}^{*}\), nothing more. If True, an Armijo backtracking line search is applied along the update \(\Delta\mathbf{p}_{in}^{*}\) (afterupdate_func): the step \(\alpha \Delta\mathbf{p}_{in}^{*}\) is applied with the first \(\alpha = 1, \beta, \beta^2, ...\) such that\[C(\mathbf{p}_{in} + \alpha \Delta\mathbf{p}_{in}^{*}) \leq C(\mathbf{p}_{in}) + c_1 \alpha \, \mathbf{g}^T \Delta\mathbf{p}_{in}^{*} + \eta\]where \(\eta = \text{noise} \times |C(\mathbf{p}_{in})|\) is the tolerated rounding noise of the cost (
line_search_conf["noise"], default1e-13): at the machine precision the cost cannot decrease anymore, and the steps that do not increase it beyond its rounding error are accepted at once instead of being shortened in vain. A trial step with NaN or Inf output parameters or cost is rejected (smaller \(\alpha\)). Each trial step only evaluates the residuals (and thecost_func): no Jacobian, Hessian or linear system. The residuals of the accepted step are reused at the next iteration, so a full step accepted at once (\(\alpha = 1\)) costs exactly the same as the pure Gauss-Newton iteration. The optimization is stopped withsuccess=Falseif the update is not a descent direction (\(\mathbf{g}^T \Delta\mathbf{p}_{in}^{*} > \eta\), stop code"not_descent", e.g. an indefinite Hessian of agHterm or anupdate_func) or if no step satisfies the condition (stop code"line_search"). The value of \(\alpha\) is available in the history ("step_length") and displayed withverbosity >= 2.Note
The line search requires the cost of every term: all
gHterms must define acost_func(ValueError otherwise). It cannot be combined withdamping(ValueError).line_search_conf (Optional[Mapping[str, Real]], optional (default=None)) –
Used only if
line_searchis True. Dictionary to change the default settings of the line search. The missing keys keep their default value:"c1"(default1e-4, in(0, 1)): the sufficient decrease constant \(c_1\)."factor"(default0.5, in(0, 1)): the backtracking factor \(\beta\)."max_backtracks"(default30): maximum number of rejected trial steps in one iteration before stopping withsuccess=False."noise"(default1e-13,>= 0): relative rounding noise of the cost \(\eta / |C|\) tolerated by the condition (0.0for the strict condition).
The complete configuration used is stored in
result.config["line_search_conf"].verbosity (Integral, optional (default=0)) – The level of verbosity for logging the optimization process. 0: No logging 1: Log only the final results of the optimization process. 2: Log the results at each iteration of the optimization process. 3: Details logging for debugging purposes.
history (bool, optional (default=False)) – If True, the history of the optimization process is stored in the
historyattribute of the returnedSolveResult. See the Notes section for more details.history_details (Optional[Union[str, Sequence[str]]], optional (default=None)) – Used only if
historyis True. Specifies the details to include in the history of the optimization process. It can be either a single string or a sequence of strings. See the Notes section for the available details. If None, the history will include the following details by default:"iteration","elapsed_time","parameters","delta_parameters","delta_cost","cost", and"optimality"(see_DEFAULT_SOLVE_HISTORY).history_length (Optional[Integral], optional (default=None)) – Used only if
historyis True. Controls the number of iterations included in the history. If None, all iterations are included in the output history. If a positive integerNis given, only the firstNiterations are included in the output history (from 0 to \(N-1\)). If zero is given, no iterations are included. If a negative integerMis given, only the last|M|iterations are included in the output history. If the requested history length is greater than the number of iterations performed, the history will contain fewer entries than requested.
- Returns:
result – The result of the optimization (see
pysolvegn.SolveResult), with the following attributes:parameters(numpy.ndarray): the optimized input parameters \(\mathbf{p}_{in}\) with shape(n_parameters,). If a parametrization is provided, the corresponding output parameters are obtained as \(\mathbf{p}_{out} = P(\mathbf{p}_{in})\).history(List[Dict]): the history of the optimization process, one dictionary per iteration containing the keys described below (empty ifhistoryis False).success(bool): True if a convergence criterion (ftol,atol,gtol,xtolorptol) was satisfied and the optimization was not stopped by a NaN or Inf value, a singular linear system, the callback function or a failure of the Levenberg-Marquardt step or of the line search (seeSolveResultfor the priority rules).stop_code(int): the stopping criteria triggered at the last iteration (bit mask). The methodresult.stopped_by(name)and the propertiesresult.reasonsandresult.messagedescribe them.n_iterations(int): the number of updates applied to the parameters.cost(Optional[float]): the cost at the returned parameters (always available ifsuccessis True).optimality(Optional[float]):norm(g, ord=numpy.inf)at the returned parameters.term_parameters(Optional[numpy.ndarray]): \(\mathbf{p}_{out} = P(\mathbf{p}_{in})\) at the returned parameters.elapsed_time(float): the total time of the optimization in seconds.n_rejected(int): the number of rejected trial steps (Levenberg-Marquardt or line search).config(Dict): the stopping criteria,dampingandlm_confrequested.
- Return type:
Notes
The solver always checks for NaN or Inf values in the initial parameters
p0, the output parametersp_outand the updateΔp_in*(and, withdamping="lm", in the costs used to accept the steps): the optimization is then stopped withsuccess=Falseand the last valid parameters are returned.The step of each loop iteration is as follows:
0. [STOP check] If ``p0`` contains NaN or Inf values, return immediately with ``success=False``. While NOT stopped: 1. Compute the output parameters ``p_out = P(p_in)`` (``p_out = p_in`` if no parametrization). 2. [STOP check] If ``p_out`` contains NaN or Inf values, stop with ``success=False``. 3. For ``rJ`` terms, compute ``r_i``, ``J_i`` and the cost ``c_i``, apply the robust loss (``r_i -> r~_i``, ``J_i -> J~_i``) and the chain rule ``J~_i -> J~_i @ J_P``, then build ``H_i = J~_i.T J~_i`` and ``g_i = J~_i.T r~_i``. 4. For ``gH`` terms, compute ``H_i``, ``g_i`` and the cost ``c_i`` (``0.0`` without ``cost_func``), then apply the chain rule ``H_i -> J_P.T H_i J_P`` and ``g_i -> J_P.T g_i``. 5. Assemble the full system ``H Δp_in = -g`` with ``H = sum(w_i H_i)`` and ``g = sum(w_i g_i)``, and the cost ``C = sum(w_i c_i)``. 6. [STOP checks] Store the history, check the stopping criteria (``ftol``, ``atol``, ``gtol``, ``xtol``, ``ptol``, ``max_iteration`` and ``max_time``) and call the ``callback_func`` with the current state (``parameters``, ``delta_parameters``, ``cost``, ``second_term`` and ``hessian``). 7. If STOP, exit the loop and return the current ``p_in`` and the history (see :class:`SolveResult` for the value of ``success``). 8. If CONTINUE, compute the update ``Δp_in``: - ``damping=None``: solve ``H Δp_in = -g``. If the system is singular, stop with ``success=False``. - ``damping="lm"`` or ``"lm-diag"``: solve ``(H + λ D) Δp_in = -g`` (``D = I`` or ``diag(H)``), apply ``update_func`` and compute the cost ``C_new`` at ``p_in + Δp_in*``. While ``C_new > C``, multiply ``λ`` by 10 and solve again (a trial step with a singular system or NaN/Inf output parameters is also rejected). Then divide ``λ`` by 10. Stop with ``success=False`` if ``C`` or ``C_new`` contains NaN or Inf values, or if no step is accepted after 50 rejections. 9. (Gauss-Newton only) Compute the applied update ``Δp_in* = update_func(p_in, Δp_in)`` (``Δp_in* = Δp_in`` if no ``update_func``). With ``line_search=True``: stop with ``success=False`` if ``g^T Δp_in* >= 0``, otherwise replace ``Δp_in*`` by ``α Δp_in*`` with the first ``α = 1, β, β^2, ...`` such that ``C(p_in + α Δp_in*) <= C + c1 α g^T Δp_in*`` (only the cost is evaluated; stop with ``success=False`` if none is found). 10. [STOP check] If ``Δp_in*`` contains NaN or Inf values, stop with ``success=False`` WITHOUT applying the update (the last valid ``p_in`` is returned). 11. Update the input parameters ``p_in = p_in + Δp_in*``.The history contains the following keys (if requested in
history_details):“iteration”: Integer representing the iteration number.
“elapsed_time”: Float representing the time elapsed since the beginning of the optimization process in seconds.
“parameters”: Numpy array representing the input parameters \(\mathbf{p}_{in}\) at the current iteration.
“delta_parameters”: Numpy array representing the update \(\Delta\mathbf{p}_{in}^{*}\) applied between the previous and the current iteration (after
update_funcif provided), None at the first iteration.“costs”: List of floats representing the cost function value (without weight) of each term at the current iteration: the
cost_funcof the term if provided, otherwise \(\frac{1}{2} \sum_j \rho_i(\| \mathbf{r}_{i,j}(\mathbf{p}_{out}) \|^2)\) forrJterms and0.0forgHterms.“cost”: Float representing the cost function value at the current iteration, computed as \(\frac{1}{2} \sum_i w_i \sum_j \rho_i(\| \mathbf{r}_{i,j}(\mathbf{p}_{out}) \|^2)\).
“delta_cost”: Float representing the change of the cost function value between the previous and the current iteration (
C - C_previous), None at the first iteration.“optimality”: Float representing the optimality value at the current iteration computed as
norm(g, ord=numpy.inf)where \(g\) is the scaled second term.“residuals”: A list of numpy arrays representing the raw residuals \(\mathbf{r}_i(\mathbf{p}_{out})\) of each term at the current iteration, before the robust loss modification (None for
gHterms).“jacobians”: A list of arrays representing the raw Jacobians \(\mathbf{J}_i = \partial \mathbf{r}_i / \partial \mathbf{p}_{out}\) of each term at the current iteration, with respect to the output parameters (before the robust loss modification and the chain rule of the parametrization; None for
gHterms).“second_term”: The scaled second term \(\mathbf{g}\) of the linear system at the current iteration.
“hessian”: The Hessian approximation \(\mathbf{H}\) of the linear system at the current iteration.
“damping”: Float representing the Levenberg-Marquardt damping \(\lambda\) used for the accepted step leading to the current iteration (None at the first iteration and if
dampingis None).“gain_ratio”: Float representing the gain ratio of the accepted Levenberg-Marquardt step leading to the current iteration: the actual decrease of the cost divided by the decrease predicted by the Gauss-Newton model \(-\mathbf{g}^T \Delta\mathbf{p}_{in}^{*} - \frac{1}{2} \Delta\mathbf{p}_{in}^{*T} \mathbf{H} \Delta\mathbf{p}_{in}^{*}\) (close to 1: the model is reliable; close to 0 or negative: the model is poor). NaN if the predicted decrease is not positive, None at the first iteration and if
dampingis None. Diagnostic only: it does not change the update of \(\lambda\).“step_length”: Float representing the step length \(\alpha\) of the line search for the step leading to the current iteration (None at the first iteration and if
line_searchis False).“all”: include all the keys.
The cost of each term can be compute only for
rJterms and is defined by :\[\frac{1}{2} \sum_j \rho_i\left( \left\| \mathbf{r}_{i,j}(P(\mathbf{p}_{in})) \right\|^2 \right)\]Important
For terms defined directly by a Hessian and gradient (
gHterms), only a local quadratic model of the cost is available. Since this model is defined up to an arbitrary constant and submit to cumulative errors, an absolute cost value cannot be uniquely determined. For reporting consistency, the cost contribution of these terms is set to0.0by default. If the term contains acost_funcfunction, it will be used to compute the cost of the term.A
UserWarningis emitted for every call with agHterm withoutcost_func(the reported cost does not include it), and the cost criteriaatolandftolraise aValueErrorin this case (with only such terms,atolwould be satisfied at once without updating the parameters, andftolnever).