pysolvegn.solve_batch#

solve_batch(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 batch of k independent least squares problems using the Gauss-Newton method with robust cost functions.

This is the batched counterpart of pysolvegn.solve(). The parameters of the k problems are stored in an array with shape (k, n_parameters) and each problem \(k\) solves:

\[\min_{\mathbf{p}_{in,k}} \frac{1}{2} \sum_{i} w_{i,k} \sum_j \rho_i\left(\| \mathbf{r}_{i,j}\left(P(\mathbf{p}_{in,k}), k\right) \|^2\right)\]

where each term \(i\) is a pysolvegn.BatchTerm with its own residual function, Jacobian function, weight \(w_{i,k}\) (scalar or one value per problem) and loss function \(\rho_i\).

Here \(\mathbf{p}_{in,k}\) represents the parameters of the problem \(k\) actually optimized by the solver, and \(P\) is a parametric transformation (pysolvegn.BatchParametrization), the same for all the problems, such that:

\[\mathbf{p}_{out,k} = P(\mathbf{p}_{in,k})\]

represents the parameters passed to the residual and Jacobian functions of each terms. If no parametrization is provided, the identity transformation is implicitly used:

\[P(\mathbf{p}_{in,k}) = \mathbf{p}_{in,k}\]

The stopping criteria are applied to each problem independently: a problem satisfying a criterion is removed from the processing and its parameters are frozen, while the other problems keep iterating. The terms are therefore only evaluated on the m <= k problems still in processing: m is NOT fixed and changes during the optimization (see pysolvegn.BatchTerm for the (parameters, indices) convention). Each problem gives exactly the same result as if it was solved alone with pysolvegn.solve().

See also

For more details on the notations for the optimization problem, please refer to the mathematical section of the documentation.

Parameters:
  • terms (Union[BatchTerm, Sequence[BatchTerm]]) – The list of terms defining the least squares problems. Each term should be an instance of the BatchTerm class containing the residual function, Jacobian function, weight, and loss function defining the term. A term with a vector weight must have a weight with shape (k,). The residual and Jacobian functions of each term are evaluated using the output parametric parameters \(\mathbf{p}_{out} = P(\mathbf{p}_{in})\) of the problems in processing, with shape (m, n_p_outputs), and their indices.

  • p0 (ArrayLike) – The initial guess for the parameters optimized by the solver, with shape (k, n_parameters). If a parametrization is provided, p0 represents 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, p0 directly 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[BatchParametrization], optional (default=None)) – The parametrization defining the transformation from the parameters optimized by the solver to the parameters passed to the terms (the same for all the problems). If provided, the solver optimizes the input parameters \(\mathbf{p}_{in}\) with shape (k, n_parameters) of this parametrization.

  • max_iteration (Optional[Integral], optional (default=None)) – Maximum number of optimization iterations. If provided, all the problems still in processing are stopped after at most max_iteration iterations. 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. All the problems still in processing are stopped when the time elapsed since the beginning of the optimization exceeds max_time seconds. If None, no limit on the computation time is considered. The time is also checked between the trial steps of the Levenberg-Marquardt damping and of the line search (the trial steps being tested are then not applied).

  • ftol (Optional[Real], optional (default=None)) – Stop criterion by the change of the cost function value. A problem is stopped when 0 <= dF < ftol * F where F is its cost function value and dF = F_previous - F is the decrease of its 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 a gH term has no cost_func (ValueError).

  • xtol (Optional[Real], optional (default=None)) – Stop criterion by the change of the optimized parameters. A problem is stopped when ||dp|| < xtol * (xtol + ||p||) where p is its input parameters \(\mathbf{p}_{in,k}\) and dp is the change of its input parameters between two iterations. If None, this criterion is not considered.

  • gtol (Optional[Real], optional (default=None)) – Stop criterion by the optimality value. A problem is stopped when its optimality verifies norm(g, ord=numpy.inf) < gtol where \(g\) is its scaled second term. If None, this criterion is not considered.

  • atol (Optional[Real], optional (default=None)) – Stop criterion by the absolute cost function value. A problem is stopped when F < atol where F is its cost function value. If None, this criterion is not considered. Not allowed if a gH term has no cost_func (ValueError).

  • ptol (Optional[Real], optional (default=None)) – Stop criterion by the change of the optimized parameters. A problem is stopped when norm(dp, ord=numpy.inf) < ptol where dp is the change of its input parameters \(\mathbf{p}_{in,k}\). If None, this criterion is not considered.

  • callback_func (Optional[Callable[[Dict], Union[bool, ArrayLike]]], 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 "indices" (indices of the m problems in processing, shape (m,)), "parameters" (m, n_parameters), "delta_parameters" (m, n_parameters) (None at the first iteration), "cost" (m,), "second_term" (m, n_parameters) and "hessian" (m, n_parameters, n_parameters) of the current iteration, and must return either a boolean (applied to all the problems in processing) or an array of booleans with shape (m,): True to continue, False to stop the problem (success=False). If None, no callback function is used.

    Warning

    "hessian" is not a copy: do not modify it in place (copy it first with hessian.copy()), as it is used afterwards to compute the update.

  • update_func (Optional[Callable[[numpy.ndarray, 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 updates \(\Delta\mathbf{p}_{in}\) (solutions of \(\mathbf{H} \Delta\mathbf{p}_{in} = -\mathbf{g}\)) of m problems, both with shape (m, n_parameters), and the indices of these problems with shape (m,), and return the updates \(\Delta\mathbf{p}_{in}^{*}\) actually applied, with shape (m, n_parameters), such that \(\mathbf{p}_{in}^{k+1} = \mathbf{p}_{in}^{k} + \Delta\mathbf{p}_{in}^{*}\). The returned updates are the ones stored in the history ("delta_parameters"). With Levenberg-Marquardt (damping not None), update_func is 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}\) of each problem:

    • 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.

    Each problem has its own damping \(\lambda\). With "lm" and "lm-diag", a trial step is accepted only if it does not increase the cost of the problem: otherwise its \(\lambda\) is multiplied by 10 and its system is solved again. After an accepted step, \(\lambda\) is divided by 10. If no acceptable step is found after 50 consecutive rejections, the problem is stopped with success=False. The values of \(\lambda\) are available in the history ("damping") and their mean is displayed with verbosity >= 2.

    Note

    With Levenberg-Marquardt, the cost of every term must be computable to test the steps: all gH terms must define a cost_func.

  • lm_conf (Optional[Mapping[str, Real]], optional (default=None)) – Used only if damping is "lm" or "lm-diag". Dictionary to change the default settings of the Levenberg-Marquardt damping ("initial_scale", "factor", "max_rejections", "diag_floor" and "noise", see pysolvegn.solve()). The missing keys keep their default value. The same settings are used for all the problems.

  • line_search (bool, optional (default=False)) – Used only if damping is None (Gauss-Newton). If False (default), the full Gauss-Newton step of each problem is always applied, nothing more. If True, an Armijo backtracking line search is applied to each problem independently along its update \(\Delta\mathbf{p}_{in,k}^{*}\) (each problem has its own step length \(\alpha_k\), see pysolvegn.solve() for the details). Only the problems still looking for an acceptable step are evaluated at each trial (residuals and cost_func only). A problem is stopped with success=False if its update is not a descent direction (stop code "not_descent") or if no step satisfies the condition (stop code "line_search"). Requires a cost_func for every gH term and cannot be combined with damping (ValueError).

  • line_search_conf (Optional[Mapping[str, Real]], optional (default=None)) – Used only if line_search is True. Dictionary to change the default settings of the line search ("c1", "factor", "max_backtracks" and "noise", see pysolvegn.solve()). The same settings are used for all the problems.

  • 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. The logged values are averaged over the problems in processing at the current iteration (the total cost of the batch has no meaning).

  • history (bool, optional (default=False)) – If True, the history of the optimization process is stored in the history attribute of the returned BatchSolveResult. See the Notes section for more details.

  • history_details (Optional[Union[str, Sequence[str]]], optional (default=None)) – Used only if history is 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", "n_processing", "parameters", "delta_parameters", "delta_cost", "cost", and "optimality".

  • history_length (Optional[Integral], optional (default=None)) – Used only if history is True. Controls the number of iterations included in the history. If None, all iterations are included in the output history. If a positive integer N is given, only the first N iterations are included in the output history (from 0 to \(N-1\)). If zero is given, no iterations are included. If a negative integer M is 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.BatchSolveResult), with the following attributes:

  • parameters (numpy.ndarray): the optimized input parameters \(\mathbf{p}_{in}\) with shape (k, 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 if history is False).

  • success (numpy.ndarray): array of booleans with shape (k,), True for each problem for which a convergence criterion (ftol, atol, gtol, xtol or ptol) was satisfied and which was not stopped by a NaN or Inf value, a singular linear system, the callback function or a failure of the Levenberg-Marquardt step (see BatchSolveResult for the priority rules).

  • stop_code (numpy.ndarray): the stopping criteria of each problem (bit mask). The methods result.stopped_by(name), result.reasons(k) and the property result.message describe them.

  • n_iterations (numpy.ndarray): the number of updates applied to each problem.

  • cost (Optional[numpy.ndarray]): the cost of each problem at the returned parameters.

  • optimality (numpy.ndarray): norm(g_k, ord=numpy.inf) of each problem at the returned parameters.

  • term_parameters (Optional[numpy.ndarray]): \(\mathbf{p}_{out}\) at the returned parameters.

  • elapsed_time (float): the total time of the optimization in seconds.

  • n_rejected (numpy.ndarray): the number of rejected Levenberg-Marquardt trial steps of each problem.

  • config (Dict): the stopping criteria, damping and lm_conf requested.

Return type:

BatchSolveResult

Notes

The solver always checks for NaN or Inf values in the initial parameters p0, the output parameters p_out and the update Δp_in* (and, with damping="lm", in the costs used to accept the steps) of each problem: the problem is then stopped with success=False and its last valid parameters are returned.

The step of each loop iteration is as follows (each step is applied to the m problems in processing, and “stop” means that the concerned problems are removed from the processing):

0.  [STOP check] Stop the problems for which ``p0`` contains NaN or Inf values.
    If all the problems are stopped, return immediately.

While at least one problem is in processing:
    1.  Compute the output parameters ``p_out = P(p_in)`` (``p_out = p_in`` if no parametrization).
    2.  [STOP check] Stop the problems for which ``p_out`` contains NaN or Inf values.
    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 m systems ``H Δp_in = -g`` with ``H = sum(w_i H_i)`` and
        ``g = sum(w_i g_i)``, and the costs ``C = sum(w_i c_i)``.
    6.  [STOP checks] Store the history, check the stopping criteria of each problem
        (``ftol``, ``atol``, ``gtol``, ``xtol``, ``ptol``, ``max_iteration`` and ``max_time``)
        and call the ``callback_func`` with the current state (``indices``, ``parameters``,
        ``delta_parameters``, ``cost``, ``second_term`` and ``hessian``).
    7.  Remove the stopped problems from the processing (their parameters are frozen,
        see :class:`BatchSolveResult` for the value of ``success``). Exit the loop if
        no problem remains.
    8.  For the remaining problems, compute the update ``Δp_in``:

        - ``damping=None``: solve ``H Δp_in = -g``. Stop the problems with a
          singular system.
        - ``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 the problems for which ``C`` or
          ``C_new`` contains NaN or Inf values, or for which no step is accepted
          after 50 rejections.
    9.  (Gauss-Newton only) Compute the applied update ``Δp_in* = update_func(p_in, Δp_in, indices)``
        (``Δp_in* = Δp_in`` if no ``update_func``).
        With ``line_search=True``, for each problem: stop it 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*`` (stop it if none is found).
    10. [STOP check] Stop the problems for which ``Δp_in*`` contains NaN or Inf values
        WITHOUT applying the update (their last valid ``p_in`` is returned).
    11. Update the input parameters ``p_in = p_in + Δp_in*`` of the remaining problems.

The history contains the following keys (if requested in history_details). All the per-problem arrays have a first dimension of size k (all the problems of the batch). For the problems not in processing at the current iteration, the values of the last iteration during which they were processed are kept (frozen values), except for "delta_parameters", "delta_cost" and "damping" which are set to NaN.

  • “iteration”: Integer representing the iteration number.

  • “elapsed_time”: Float representing the time elapsed since the beginning of the optimization process in seconds.

  • “n_processing”: Integer representing the number of problems in processing at the current iteration.

  • “is_processing”: Numpy array of booleans with shape (k,), True for the problems in processing at the current iteration.

  • “parameters”: Numpy array with shape (k, n_parameters) representing the input parameters \(\mathbf{p}_{in}\) at the current iteration.

  • “delta_parameters”: Numpy array with shape (k, n_parameters) representing the updates \(\Delta\mathbf{p}_{in}^{*}\) applied between the previous and the current iteration (after update_func if provided), None at the first iteration.

  • “costs”: List of numpy arrays with shape (k,) representing the cost function value (without weight) of each term at the current iteration: the cost_func of the term if provided, otherwise \(\frac{1}{2} \sum_j \rho_i(\| \mathbf{r}_{i,j}(\mathbf{p}_{out,k}) \|^2)\) for rJ terms and 0.0 for gH terms.

  • “cost”: Numpy array with shape (k,) representing the cost function value of each problem at the current iteration, computed as \(\frac{1}{2} \sum_i w_{i,k} \sum_j \rho_i(\| \mathbf{r}_{i,j}(\mathbf{p}_{out,k}) \|^2)\).

  • “delta_cost”: Numpy array with shape (k,) representing the change of the cost function value of each problem between the previous and the current iteration (C - C_previous), None at the first iteration.

  • “optimality”: Numpy array with shape (k,) representing the optimality value of each problem at the current iteration computed as norm(g, ord=numpy.inf) where \(g\) is the scaled second term.

  • “residuals”: A list of numpy arrays with shape (k, n_residuals_i) representing the raw residuals of each term at the current iteration, before the robust loss modification (None for gH terms).

  • “jacobians”: A list of numpy arrays with shape (k, n_residuals_i, n_p_outputs) representing the raw Jacobians 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 gH terms).

  • “second_term”: Numpy array with shape (k, n_parameters) representing the scaled second term \(\mathbf{g}\) of each linear system at the current iteration.

  • “hessian”: Numpy array with shape (k, n_parameters, n_parameters) representing the Hessian approximation \(\mathbf{H}\) of each linear system at the current iteration.

  • “damping”: Numpy array with shape (k,) representing the Levenberg-Marquardt damping \(\lambda\) used for the accepted step leading to the current iteration (None at the first iteration and if damping is None).

  • “gain_ratio”: Numpy array with shape (k,) representing the gain ratio of the accepted Levenberg-Marquardt step of each problem leading to the current iteration (see pysolvegn.solve(); NaN for the problems not updated, None at the first iteration and if damping is None). Diagnostic only.

  • “step_length”: Numpy array with shape (k,) 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_search is False).

  • “all”: include all the keys.

The cost of each term can be compute only for rJ terms and is defined by :

\[\frac{1}{2} \sum_j \rho_i\left( \left\| \mathbf{r}_{i,j}(P(\mathbf{p}_{in,k})) \right\|^2 \right)\]

Important

For terms defined directly by a Hessian and gradient (gH terms), 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 to 0.0 by default. If the term contains a cost_func function, it will be used to compute the cost of the term.

A UserWarning is emitted for every call with a gH term without cost_func (the reported cost does not include it), and the cost criteria atol and ftol raise a ValueError in this case (with only such terms, atol would be satisfied at once without updating the parameters, and ftol never).