import numpy as np
from scipy.optimize import minimize
def maximize_function(func, x0, bounds=None, constraints=None, method='SLSQP', options=None):
"""
Maximize a given function using scipy.optimize.minimize.
Parameters:
func (callable): The function to be maximized.
x0 (array-like): The initial guess for the optimization.
bounds (tuple of tuples, optional): Bounds for the variables (x1, x2, ...), e.g., [(x1_min, x1_max), (x2_min, x2_max), ...].
constraints (dict or list of dicts, optional): Constraints definition (see scipy.optimize.minimize documentation).
method (str, optional): The optimization method to use (default is 'SLSQP').
options (dict, optional): Additional options for the optimizer (see scipy.optimize.minimize documentation).
Returns:
OptimizeResult: The result of the optimization, containing the optimal solution, function value, etc.
"""
# Negate the function to minimize it
neg_func = lambda x: -func(x)
# Perform the minimization
result = minimize(neg_func, x0, bounds=bounds, constraints=constraints, method=method, options=options)
# Return the maximized result by negating the minimized function value
return result.fun * -1, result.x
In this example, we maximize the quadratic function -x^2 + 4x - 5 with the initial guess [0] and bounds (0, 5). The function returns the maximum value 9.0 at the optimal point [2.].