pysolver_view.roots.solver module#
- class pysolver_view.roots.solver.NonlinearSystemSolver(problem, method='hybr', tolerance=1e-06, max_iterations=100, options={}, derivative_method='2-point', derivative_abs_step=1e-06, print_convergence=True, plot_convergence=False, plot_scale='log', logger=None, update_on='function', callback_func=None, *, library='scipy')[source]#
Bases:
objectSolve nonlinear equations with native SciPy or controlled custom methods.
- Parameters:
- problemNonlinearSystemProblem
Model with
residual(x)and optional analyticgradient(x).- methodstr, optional
Default
hybr. SciPy supportslm/hybrand their full aliaseslevenberg_marquardt/powell_hybrid. The custom backend additionally supportsnewton_raphson/newtonandgauss_newton/gn.- tolerancefloat, optional
Default 1e-6. SciPy’s existing residual acceptance is 10*tolerance. Custom options use this as residual_tol unless explicitly overridden.
- max_iterationsint, optional
Default 100. Sets native maxfev (hybr) or maxiter (lm). For custom solvers, fills the trial-attempt budget unless explicitly overridden; accepted iterations, trials, and residual evaluations are distinct.
- optionsdict or root-options dataclass, optional
Native SciPy options, or StepControlOptions/NewtonOptions for custom solvers. Explicit custom dictionary fields override constructor defaults; a matching dataclass supplies every option. See result.effective_options.
- derivative_methodstr, optional
2-point,3-point, orcsfor a missing analytic Jacobian. The selected backend owns differentiation, avoiding nested probes.- derivative_abs_stepfloat or array, optional
Physical probe distance, default 1e-6. Custom options may override this or select scaled probes using finite_diff_step instead.
- print_convergence, plot_convergencebool, optional
Enable console and live figure output; defaults True and False.
- plot_scalestr, optional
Residual axis scale; default
log.- loggerlogging.Logger, optional
Destination for convergence messages.
- update_onstr, optional
function(default),gradient, or custom-onlyiteration. Function observations can include rejected trials; iteration observations contain the initial state and accepted moves only. Probes never add rows.- callback_funccallable, optional
Receives detached
(x, callback_count). Native SciPy calls it for selected observations. Custom solvers call it at the initial state and accepted moves, independently of update_on; False or StopIteration stops.- librarystr, keyword-only
scipy(default) orpysolver. Custom roots are independent Python algorithms using SciPy linear algebra, not native MINPACK wrappers.
- Attributes:
- backend_result, resultscipy.optimize.OptimizeResult or None
Detached backend result and enriched public result. Final coordinates come from the backend. Custom success requires the residual target; result.fun is None when the initial residual is undefined.
- convergence_historydict
Selected observations, with scalar values even in summary history mode. A displacement between function observations is not an accepted step.
- iteration_historylist
Custom initial/accepted records. Native LM/hybrid expose no iterations, so their list is empty and iteration_count is None.
- iteration_countint or None
Accepted custom moves, excluding the initial record and derivative probes.
Notes
solve(x0) continues to return a solution vector. Custom history_level selects full coordinate storage, scalar summary records, or no stored histories. Model-domain recovery uses pysolver_view.DomainError; unrelated programming exceptions propagate. A new solve resets all per-run counters and histories.
- property derivative_func_count#
- property failed_grad_count#
- property func_count#
- property func_count_tot#
- property grad_count#
- gradient(x)[source]#
Evaluate one Jacobian request at a point-consistent residual base.
Numerical differences use residual values at the requested point, never the most recent probe or an unrelated observation. A request increments
grad_countonce, regardless of how many probes it uses; failed requests also incrementfailed_grad_count.
- plot_convergence_history(savefile=False, filename=None, output_dir='output', *, showfig=True)[source]#
Plot the residual two-norm against function or Jacobian evaluations.
Numerical derivative probes are excluded from the function-observation axis and remain included in total model-call counters. Native accepted iteration counts are not available from SciPy’s LM/hybrid interface.
This method should be called only after the optimization problem has been solved, as it relies on data generated by the solving process.
- Parameters:
- savefilebool, optional
If True, the plot is saved to a file instead of being displayed. Default is False.
- filenamestr, optional
The name of the file to save the plot to. If not specified, the filename is automatically generated using the problem name and the start datetime. The file extension is not required.
- output_dirstr, optional
The directory where the plot file will be saved if savefile is True. Default is “output”.
- Returns:
- matplotlib.figure.Figure
The Matplotlib figure object for the plot. This can be used for further customization or display.
- Raises:
- ValueError
If this method is called before the problem has been solved.
- print_convergence_history(savefile=False, filename=None, output_dir='output')[source]#
Print the convergence history of the problem.
- The convergence history includes:
Number of function evaluations
Number of gradient evaluations
Two-norm of the residual vector
Two-norm of the solution step
- The method provides a detailed report on:
Exit message
Success status
Execution time
This method should be called only after the optimization problem has been solved, as it relies on data generated by the solving process.
- Parameters:
- savefilebool, optional
If True, the convergence history will be saved to a file, otherwise printed to standard output. Default is False.
- filenamestr, optional
The name of the file to save the convergence history. If not specified, the filename is automatically generated using the problem name and the start datetime. The file extension is not required.
- output_dirstr, optional
The directory where the plot file will be saved if savefile is True. Default is “output”.
- Raises:
- ValueError
If this method is called before the problem has been solved.
- residual(x, called_from_jac=False)[source]#
Evaluate residuals, counting derivative probes without recording them.
Every actual model evaluation increments
func_count_tot. Calls made for numerical derivatives also incrementderivative_func_countbut never change ordinary observation state or invoke user callbacks. Inputs, returned values, and stored snapshots do not share writable arrays with a model or callback.
- property residuals_last#
- solve(x0)[source]#
Return the selected backend’s final point and retain detailed results.
backend_resultis a detached backend result.resultadds package-level evaluation accounting and residual-based acceptance. Native LM/hybrid iteration counts are unavailable; evaluations and Jacobian requests are never relabeled as iterations. Reusing this solver starts a fresh history and resets its per-run counters.