def obj_f_c(X): try: y = np.asarray([0.4655, 0., 0.]) array_type = ct.c_double * y.size n = len(X) for i in range(n): if X[i] == 0: continue # bang-bang type switches starting with w(t) = 1. w = (i + 1) % 2 ry = integrateF8_C(array_type(*y), w, X[i], 0.1) y = np.array(np.fromiter(ry, dtype=np.float64, count=y.size)) freemem(ry) val0 = np.sum(X) penalty = np.sum(np.abs(y)) # estimated fixed weight for penalty val = 0.1 * val0 + penalty global f_evals f_evals.value += 1 global best_f if best_f.value > val: best_f.value = val # monitor value and constraint violation print( "val = {0:.8f} penalty = {1:.8f} f(xmin) = {2:.5f} nfev = {3}". format(val0, penalty, val, f_evals.value)) return val except Exception as e: return 1E10 # fail
def minimize(fun, dim=None, bounds=None, popsize=None, max_evaluations=100000, stop_fitness=None, keep=200, f=0.5, cr=0.9, rg=Generator(MT19937()), runid=0): """Minimization of a scalar function of one or more variables using a C++ Differential Evolution implementation called via ctypes. Parameters ---------- fun : callable The objective function to be minimized. ``fun(x, *args) -> float`` where ``x`` is an 1-D array with shape (n,) and ``args`` is a tuple of the fixed parameters needed to completely specify the function. dim : int dimension of the argument of the objective function bounds : sequence or `Bounds`, optional Bounds on variables. There are two ways to specify the bounds: 1. Instance of the `scipy.Bounds` class. 2. Sequence of ``(min, max)`` pairs for each element in `x`. None is used to specify no bound. popsize : int, optional Population size. max_evaluations : int, optional Forced termination after ``max_evaluations`` function evaluations. stop_fitness : float, optional Limit for fitness value. If reached minimize terminates. keep = float, optional changes the reinitialization probability of individuals based on their age. Higher value means lower probablity of reinitialization. f = float, optional The mutation constant. In the literature this is also known as differential weight, being denoted by F. Should be in the range [0, 2]. cr = float, optional The recombination constant. Should be in the range [0, 1]. In the literature this is also known as the crossover probability. rg = numpy.random.Generator, optional Random generator for creating random guesses. runid : int, optional id used to identify the run for debugging / logging. Returns ------- res : scipy.OptimizeResult The optimization result is represented as an ``OptimizeResult`` object. Important attributes are: ``x`` the solution array, ``fun`` the best function value, ``nfev`` the number of function evaluations, ``nit`` the number of iterations, ``success`` a Boolean flag indicating if the optimizer exited successfully. """ n, lower, upper = de._check_bounds(bounds, dim) if popsize is None: popsize = 31 if lower is None: lower = [0] * n upper = [0] * n if stop_fitness is None: stop_fitness = math.inf array_type = ct.c_double * n c_callback = call_back_type(callback(fun)) seed = int(rg.uniform(0, 2**32 - 1)) try: res = optimizeDE_C(runid, c_callback, n, seed, array_type(*lower), array_type(*upper), max_evaluations, keep, stop_fitness, popsize, f, cr) x = np.array(np.fromiter(res, dtype=np.float64, count=n)) val = res[n] evals = int(res[n + 1]) iterations = int(res[n + 2]) stop = int(res[n + 3]) freemem(res) return OptimizeResult(x=x, fun=val, nfev=evals, nit=iterations, status=stop, success=True) except Exception as ex: return OptimizeResult(x=None, fun=sys.float_info.max, nfev=0, nit=0, status=-1, success=False)
def minimize(fun, dim = None, bounds = None, popsize = None, max_evaluations = 100000, stop_fitness = None, pbest = 0.7, f0 = 0.0, cr0 = 0.0, rg = Generator(MT19937()), runid=0, workers = None): """Minimization of a scalar function of one or more variables using a C++ GCL Differential Evolution implementation called via ctypes. Parameters ---------- fun : callable The objective function to be minimized. ``fun(x, *args) -> float`` where ``x`` is an 1-D array with shape (n,) and ``args`` is a tuple of the fixed parameters needed to completely specify the function. dim : int dimension of the argument of the objective function bounds : sequence or `Bounds` Bounds on variables. There are two ways to specify the bounds: 1. Instance of the `scipy.Bounds` class. 2. Sequence of ``(min, max)`` pairs for each element in `x`. popsize : int, optional Population size. max_evaluations : int, optional Forced termination after ``max_evaluations`` function evaluations. stop_fitness : float, optional Limit for fitness value. If reached minimize terminates. pbest = float, optional use low value 0 < pbest <= 1 to narrow search. f0 = float, optional The initial mutation constant. In the literature this is also known as differential weight, being denoted by F. Should be in the range [0, 2]. cr0 = float, optional The initial recombination constant. Should be in the range [0, 1]. In the literature this is also known as the crossover probability. rg = numpy.random.Generator, optional Random generator for creating random guesses. runid : int, optional id used to identify the run for debugging / logging. workers : int or None, optional If not workers is None, function evaluation is performed in parallel for the whole population. Useful for costly objective functions but is deactivated for parallel retry. Returns ------- res : scipy.OptimizeResult The optimization result is represented as an ``OptimizeResult`` object. Important attributes are: ``x`` the solution array, ``fun`` the best function value, ``nfev`` the number of function evaluations, ``nit`` the number of iterations, ``success`` a Boolean flag indicating if the optimizer exited successfully. """ n, lower, upper = de._check_bounds(bounds, dim) if popsize is None: popsize = int(n*8.5+150) if lower is None: lower = [0]*n upper = [0]*n if stop_fitness is None: stop_fitness = math.inf parfun = None if workers is None else parallel(fun, workers) array_type = ct.c_double * n c_callback_par = call_back_par(callback_par(fun, parfun)) seed = int(rg.uniform(0, 2**32 - 1)) try: res = optimizeGCLDE_C(runid, c_callback_par, n, seed, array_type(*lower), array_type(*upper), max_evaluations, pbest, stop_fitness, popsize, f0, cr0) x = np.array(np.fromiter(res, dtype=np.float64, count=n)) val = res[n] evals = int(res[n+1]) iterations = int(res[n+2]) stop = int(res[n+3]) freemem(res) if not parfun is None: parfun.stop() # stop all parallel evaluation processes return OptimizeResult(x=x, fun=val, nfev=evals, nit=iterations, status=stop, success=True) except Exception as ex: if not workers is None: fun.stop() # stop all parallel evaluation processes return OptimizeResult(x=None, fun=sys.float_info.max, nfev=0, nit=0, status=-1, success=False)
def minimize(fun, bounds=None, x0=None, input_sigma=0.166, popsize=0, max_evaluations=100000, stop_fittness=None, rg=Generator(MT19937()), runid=0): """Minimization of a scalar function of one or more variables using a C++ SCMA implementation called via ctypes. Parameters ---------- fun : callable The objective function to be minimized. ``fun(x, *args) -> float`` where ``x`` is an 1-D array with shape (n,) and ``args`` is a tuple of the fixed parameters needed to completely specify the function. bounds : sequence or `Bounds`, optional Bounds on variables. There are two ways to specify the bounds: 1. Instance of the `scipy.Bounds` class. 2. Sequence of ``(min, max)`` pairs for each element in `x`. None is used to specify no bound. x0 : ndarray, shape (n,) Initial guess. Array of real elements of size (n,), where 'n' is the number of independent variables. input_sigma : ndarray, shape (n,) or scalar Initial step size for each dimension. popsize = int, optional CMA-ES population size. max_evaluations : int, optional Forced termination after ``max_evaluations`` function evaluations. stop_fittness : float, optional Limit for fitness value. If reached minimize terminates. rg = numpy.random.Generator, optional Random generator for creating random guesses. runid : int, optional id used to identify the run for debugging / logging. Returns ------- res : scipy.OptimizeResult The optimization result is represented as an ``OptimizeResult`` object. Important attributes are: ``x`` the solution array, ``fun`` the best function value, ``nfev`` the number of function evaluations, ``nit`` the number of CMA-ES iterations, ``status`` the stopping critera and ``success`` a Boolean flag indicating if the optimizer exited successfully. """ lower, upper, guess = _check_bounds(bounds, x0, rg) n = guess.size if lower is None: lower = [0] * n upper = [0] * n if np.ndim(input_sigma) == 0: input_sigma = [input_sigma] * n if stop_fittness is None: stop_fittness = -math.inf array_type = ct.c_double * n c_callback = call_back_type(callback(fun)) try: res = optimizeCsma_C(runid, c_callback, n, int(rg.uniform(0, 2**32 - 1)), array_type(*guess), array_type(*lower), array_type(*upper), array_type(*input_sigma), max_evaluations, stop_fittness, popsize) x = np.array(np.fromiter(res, dtype=np.float64, count=n)) val = res[n] evals = int(res[n + 1]) iterations = int(res[n + 2]) stop = int(res[n + 3]) freemem(res) return OptimizeResult(x=x, fun=val, nfev=evals, nit=iterations, status=stop, success=True) except Exception as ex: return OptimizeResult(x=None, fun=sys.float_info.max, nfev=0, nit=0, status=-1, success=False)
def minimize(fun, dim, bounds=None, popsize=None, max_evaluations=100000, stop_fitness=None, rg=Generator(MT19937()), runid=0): """Minimization of a scalar function of one or more variables using a C++ Harris hawks implementation called via ctypes. Parameters ---------- fun : callable The objective function to be minimized. ``fun(x, *args) -> float`` where ``x`` is an 1-D array with shape (n,) and ``args`` is a tuple of the fixed parameters needed to completely specify the function. dim : int dimension of the argument of the objective function bounds : sequence or `Bounds`, optional Bounds on variables. There are two ways to specify the bounds: 1. Instance of the `scipy.Bounds` class. 2. Sequence of ``(min, max)`` pairs for each element in `x`. None is used to specify no bound. max_evaluations : int, optional Forced termination after ``max_evaluations`` function evaluations. stop_fitness : float, optional Limit for fitness value. If reached minimize terminates. rg = numpy.random.Generator, optional Random generator for creating random guesses. runid : int, optional id used to identify the run for debugging / logging. Returns ------- res : scipy.OptimizeResult The optimization result is represented as an ``OptimizeResult`` object. Important attributes are: ``x`` the solution array, ``fun`` the best function value, ``nfev`` the number of function evaluations, ``nit`` the number of iterations, ``success`` a Boolean flag indicating if the optimizer exited successfully. """ lower = np.asarray(bounds.lb) upper = np.asarray(bounds.ub) n = dim if popsize is None: popsize = 31 if lower is None: lower = [0] * n upper = [0] * n if stop_fitness is None: stop_fitness = math.inf array_type = ct.c_double * n c_callback = call_back_type(callback(fun)) seed = int(rg.uniform(0, 2**32 - 1)) try: res = optimizeHH_C(runid, c_callback, n, seed, array_type(*lower), array_type(*upper), max_evaluations, stop_fitness, popsize) x = np.array(np.fromiter(res, dtype=np.float64, count=n)) val = res[n] evals = int(res[n + 1]) iterations = int(res[n + 2]) stop = int(res[n + 3]) freemem(res) return OptimizeResult(x=x, fun=val, nfev=evals, nit=iterations, status=stop, success=True) except Exception as ex: return OptimizeResult(x=None, fun=sys.float_info.max, nfev=0, nit=0, status=-1, success=False)