pysolver_view.optimization.solver module#

class pysolver_view.optimization.solver.OptimizationSolver(problem, library='scipy', method='slsqp', tolerance=1e-06, max_iterations=100, extra_options={}, derivative_method='2-point', derivative_abs_step=None, problem_scale=None, print_convergence=True, plot_convergence=False, plot_scale_objective='linear', plot_scale_constraints='linear', logger=None, update_on='gradient', callback_functions=None, plot_improvement_only=False, tolerance_check_cache=None, check_kkt=True, backend_callback=None)[source]#

Bases: object

Solver class for general nonlinear programming problems.

The solver is designed to handle constrained optimization problems of the form:

Minimize:

\[f(\mathbf{x}) \; \mathrm{with} \; \mathbf{x} \in \mathbb{R}^n\]

Subject to:

\[c_{\mathrm{eq}}(\mathbf{x}) = 0\]
\[c_{\mathrm{in}}(\mathbf{x}) \leq 0\]
\[\mathbf{x}_l \leq \mathbf{x} \leq \mathbf{x}_u\]

where:

  • \(\mathbf{x}\) is the vector of decision variables (i.e., degree of freedom).

  • \(f(\mathbf{x})\) is the objective function to be minimized. Maximization problems can be casted into minimization problems by changing the sign of the objective function.

  • \(c_{\mathrm{eq}}(\mathbf{x})\) are the equality constraints of the problem.

  • \(c_{\mathrm{in}}(\mathbf{x})\) are the inequality constraints of the problem. Constraints of type \(c_{\mathrm{in}}(\mathbf{x}) \leq 0\) can be casted into \(c_{\mathrm{in}}(\mathbf{x}) \geq 0\) type by changing the sign of the constraint functions.

  • \(\mathbf{x}_l\) and \(\mathbf{x}_u\) are the lower and upper bounds on the decision variables.

The class interfaces with various optimization methods provided by libraries such as scipy and pygmo to solve the problem and provides a structured framework for initialization, solution monitoring, and post-processing.

This class employs a caching mechanism to avoid redundant evaluations. For a given set of independent variables, x, the optimizer requires the objective function, equality constraints, and inequality constraints to be provided separately. When working with complex models, these values are typically calculated all at once. If x hasn’t changed from a previous evaluation, the caching system ensures that previously computed values are used, preventing unnecessary recalculations.

Parameters:
problemOptimizationProblem

An instance of the optimization problem to be solved. The problem should be defined in physical space, with its own bounds and (optionally) analytic derivatives.

librarystr, optional

The library to use for solving the optimization problem (default is ‘scipy’).

methodstr, optional

The optimization method to use from the specified library (default is ‘slsqp’).

tolerancefloat, optional

Tolerance for termination. The minimization algorithm sets some solver-specific tolerances equal to tol. (default is 1e-6)

max_iterationsint, optional

Maximum number of iterations for the optimizer (default is 100).

extra_optionsdict, optional

A dictionary of solver-specific options that prevails over ‘tolerance’ and ‘max_iterations’

derivative_methodstr, optional

Method to use for derivative calculation (default is ‘2-point’).

derivative_abs_stepfloat, optional

Finite difference absolute step size to be used when the problem Jacobian is not provided. Default depends on calculation method.

problem_scalefloat or None, optional

Scaling factor used to normalize the problem. This parameter controls the transformation of physical variables into a normalized domain. Specifically, for a physical variable x, with lower and upper bounds lb and ub, the normalized variable is computed as:

x_norm = problem_scale * (x - lb) / (ub - lb)

  • If a numeric value is provided (e.g. 1.0, 10.0, etc.), the problem is scaled accordingly. Increasing problem_scale reduces the relative step sizes in the normalized space during line searches, which can improve convergence by making the optimization less aggresive. The rationale for the scaling is that the initial line search step size of many solvers is 1.0.

  • If set to None, no scaling is applied and the problem is solved in its original physical units. This might be preferred if the problem is already well-conditioned or if the user wishes to preserve the exact scale of the original formulation.

print_convergencebool, optional

If True, displays the convergence progress (default is True).

plot_convergencebool, optional

If True, plots the convergence progress (default is False).

plot_scale_objectivestr, optional

Specifies the scale of the objective function axis in the convergence plot (default is ‘linear’).

plot_scale_constraintsstr, optional

Specifies the scale of the constraint violation axis in the convergence plot (default is ‘linear’).

loggerlogging.Logger, optional

Logger object to which logging messages will be directed. Logging is disabled if logger is None.

update_onstr, optional

Selects ‘gradient’ (default), ‘function’, or native ‘iteration’ events. SciPy callbacks denote major iterations with unknown acceptance; custom SLSQP records accepted points. Pounce records native observations with reconstructed coordinates and unknown acceptance. Derivative probes never generate observations.

callback_functionslist of callable or callable, optional

Callbacks receive (copied_solver_coordinates, callback_count). The count is not a solver iteration number. SciPy uses the selected observation stream; custom SLSQP uses initial/accepted points only and supports cancellation with StopIteration or a False return. Final synchronization does not invoke callbacks. Pounce callbacks receive regular native iteration observations independently of update_on and support the same cancellation signals; they do not receive restoration subproblems.

plot_improvement_onlybool, optional

If True, plots only display iterations that improve the objective function value (useful for gradient-free optimizers) (default is False).

check_kktbool, optional

Enable automatic KKT diagnostics (default True). If False, histories have unavailable optimality and no multiplier estimation runs automatically. Custom SLSQP success then requires native success and feasibility only. Explicit evaluate_kkt_conditions or requested KKT/multiplier reports still perform an on-demand assessment, outside the automatic solve policy. Pounce checks its authoritative final point with independent first-order KKT diagnostics and requires that check for frontend success. Its extra_options accept separate feasibility_tol and optimality_tol (each defaults to 50*tolerance). stop_on_kkt=True makes a passing assessment sufficient to request native termination. A native exit always ends the solve, even before those criteria pass. With checks disabled it still verifies original-model feasibility.

backend_callbackcallable, optional

With library="pysolver", receive a detached copy of each initial or accepted SLSQP record, including KKT diagnostics and recovery counters. Records use normalized solver coordinates and the backend’s constraint convention: equalities are zero and inequalities are nonnegative, as in backend_result.history. This differs from the frontend’s public nonpositive inequalities and equality multiplier signs. Rejected trials, derivative probes, and final synchronization do not invoke this hook. Return False or raise StopIteration to stop at the accepted point. With library="pounce", receive native records in public constraint signs, including internally scaled native_metrics. Regular x coordinates come from the last objective evaluation, and acceptance is unknown. Restoration records have x=None and fitness=None. Returning False or raising StopIteration requests a native stop; other application errors propagate after Pounce releases control.

Methods

solve(x0):

Solve the optimization problem using the specified initial guess x0.

fitness(x):

Evaluates the optimization problem objective function and constraints at a given point x.

gradient(x):

Evaluates the Jacobians of the optimization problem at a given point x.

print_convergence_history():

Print the final result and convergence history of the optimization problem.

plot_convergence_history():

Plot the convergence history of the optimization problem.

property cache#
property derivative_func_count#
property diagnostic_func_count#
property diagnostic_grad_count#
evaluate_kkt_conditions(x_norm, tol)[source]#

Evaluate the raw quantities required for KKT condition checks.

This method performs all necessary calculations to evaluate:

  • Lagrangian gradient

  • Constraint violations (equality and inequality)

  • Lagrange multipliers for active constraints

  • Complementary slackness products

Uses the shared sign-constrained multiplier estimate and applies tol to feasibility and optimality. Metrics use solver coordinates and the supplied objective/constraint units; stationarity uses the infinity norm.

Returns:
dict

A dictionary containing raw values needed to assess the KKT conditions.

property failed_grad_count#
fitness(x_norm, called_from_grad=False)[source]#

Evaluate combined responses; derivative probes never publish observations.

Inputs use solver coordinates. Total model calls include numerical derivative work; func_count includes ordinary model calls only.

property func_count#
property func_count_tot#
get_constraint_data(x_norm, tol)[source]#

Return constraint evaluation data for the current optimization problem.

This method returns a list of dictionaries describing the satisfaction status of all equality and inequality constraints at a given normalized design point.

If self.problem.constraint_data exists and is valid, it is returned directly after key validation.

Parameters:
x_normarray_like

Normalized design variable vector.

tolfloat

Tolerance for constraint satisfaction.

Returns:
list of dict

Each dictionary contains:

  • name : str Constraint identifier.

  • type : str Either “=” for equality or “<” for inequality constraints.

  • target : float Desired target value (0.0 for all constraints).

  • value : float Actual evaluated constraint value.

  • satisfied : bool Whether the constraint is satisfied (based on tol).

Optionally, each dictionary may also include:

  • normalized_mismatch : float Mismatch scaled by the normalization factor.

  • mismatch : float Raw constraint violation (value - target).

  • normalize : float Normalization factor (if defined).

Raises:
TypeError

If self.problem.constraint_data exists but is not a list of dictionaries, or if required keys are missing from any entry.

property grad_count#
gradient(x_norm)[source]#

Obtain one full Jacobian and optionally record its base-point observation.

property kkt_count#
property kkt_time#
make_constraint_report(x_norm, tol, *, width=80)[source]#

Format named constraints within width characters (minimum 60).

make_kkt_optimality_report(x_norm, tol, *, width=80)[source]#

Generate a detailed KKT condition satisfaction report.

This report includes five key Karush-Kuhn-Tucker (KKT) checks:

\[\begin{split}\|\nabla L(x, \lambda)\| \leq \mathrm{tol} \quad &\text{(First order optimality)} \\ \max |c_{\text{eq}}(x)| \leq \mathrm{tol} \quad &\text{(Equality feasibility)} \\ \max(0, c_{\text{ineq}}(x)) \leq \mathrm{tol} \quad &\text{(Inequality feasibility)} \\ \min(\lambda_{\text{ineq}}) \geq 0 \quad &\text{(Dual feasibility)} \\ \max |\lambda_i \cdot c_i| \leq \mathrm{tol} \quad &\text{(Complementary slackness)}\end{split}\]

For each condition, the report shows:

  • Actual computed value

  • Comparison direction and target (tolerance or 0)

  • Satisfaction status

Parameters:
x_normarray-like

Normalized decision variable vector to evaluate the KKT conditions at.

tolfloat

Numerical tolerance used for comparisons in optimality and feasibility checks.

widthint, optional

Maximum line width, at least 60; notes wrap as needed.

Returns:
str

A formatted report string summarizing KKT condition satisfaction.

make_lagrange_multipliers_report(x_norm, tol, *, width=80)[source]#

Generate a report of all Lagrange multipliers: - Equalities: always included - Inequalities and finite bounds: all independently estimated multipliers. - Unavailable estimates: NaN with an explicit reason.

width is the maximum line width (at least 60). Complete names wrap onto aligned continuation lines instead of being shortened.

Returns:
str

The formatted multipliers report as a single string.

make_variables_report(x_norm, normalized=True, *, width=80)[source]#

Generate design variable report as a string.

Parameters:
x_normarray-like

Normalized design variables (input to the solver).

normalizedbool, optional

Whether to report in normalized or physical values. Default is True.

widthint, optional

Maximum line width, at least 60; complete names wrap as needed.

Returns:
str

Formatted string report.

plot_convergence_history(savefile=False, filename=None, output_dir='output', showfig=True)[source]#

Plot the convergence history of the problem.

This method plots progress against the selected evaluation or native-iteration count:
  • Objective function value (left y-axis)

  • Maximum constraint violation (right y-axis)

Constraint violation is displayed for nonlinear constraints or finite variable bounds.

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', to_console=True)[source]#

Print or save the convergence history of the optimization process.

This function prints (or saves) a the report of the optimization convergence progress. It includes information collected at each iteration, including:

  • Number of gradient evaluations

  • Number of function evaluations

  • Objective function value

  • Maximum constraint violation

  • Two-norm of the update step

It also includes a summary at the end of the run with:

  • Exit message

  • Success flag

  • Total solution time (in seconds)

Note

This method must be called after solve() has been executed. Otherwise, the convergence report is unavailable and a ValueError is raised.

Parameters:
savefilebool, optional

If True, the report is saved to a file. Otherwise, it is printed to the screen. Default is False.

filenamestr or None, optional

The name of the file to save the report to. If None, a default name is generated based on the problem class name and the optimization start datetime.

output_dirstr, optional

Directory where the report file is saved if savefile=True. Default is “output”.

Raises:
ValueError

If the method is called before the optimization problem has been solved.

print_optimization_report(x=None, tol=None, include_design_variables=True, include_constraints=True, include_kkt_conditions=False, include_multipliers=False, savefile=False, filename=None, output_dir='output', to_console=True, width=80)[source]#

Print or save selected variables, constraints, KKT and multipliers.

With the custom pysolver backend, omitting both x and tol renders detached data for the authoritative final point. Its cached KKT certificate retains the solve’s separate feasibility and optimality tolerances. Unavailable or disabled diagnostics remain unassessed; no model evaluation, derivative probe, or multiplier fit is requested.

Supplying physical x or an explicit tol requests a diagnostic assessment using the legacy common tolerance for feasibility and optimality. Those explicit requests may add counted diagnostic work. Other backends retain this diagnostic behavior. When needed, the default diagnostic tolerance is five times the native solver tolerance.

Parameters:
xarray-like or None

Physical point to assess; None selects the final solution.

tolfloat or None

Common tolerance for an explicitly requested diagnostic report.

include_design_variables, include_constraintsbool

Include physical/normalized variables and named constraints.

include_kkt_conditions, include_multipliersbool

Include KKT residuals and the corresponding public-sign multipliers.

savefilebool

Save the assembled report as text in output_dir.

filenamestr or None

Explicit filename, or None for a generated report filename.

output_dirstr or path-like

Directory receiving the saved report.

to_consolebool

Print the report independently of live convergence display settings.

widthint, optional

Maximum line width in characters, at least 60. Default is 80. Extra space expands name columns. Long names and notes wrap onto continuation lines instead of being shortened. Applies equally to console, logger, and saved final reports; live convergence is separate.

solve(x0)[source]#

Solve from physical coordinates and return the backend’s final point.

backend_result retains native fields in solver coordinates. result adds the physical solution, explicit solver coordinates, and facade call counts. Observation caches and callbacks never select the solution.