Calculate an optimum argument of an objective function.
424955
def optimize(self, angles0, target):
        """"""
        def new_objective(angles):
            return self.f(angles, target)

        return scipy.optimize.minimize(
            new_objective,
            angles0,
            **self.optimizer_opt).x
567711
private function _optArg($i, $a)
    {
        if (-1 == ($ind = $this->_argindex($i, $a))) {
            return 0;
        }
        return $a[$ind];
    }
83788
def max_or_none(val1, val2):
    """"""
    return max(val1, val2, key=lambda x: -sys.maxint if x is None else x)
648241
def round_optimum(self, x):
        
        x = np.array(x)
        if not ((x.ndim == 1) or (x.ndim == 2 and x.shape[0] == 1)):
            raise ValueError("Unexpected dimentionality of x. Got {}, expected (1, N) or (N,)".format(x.ndim))

        if x.ndim == 2:
            x = x[0]

        x_rounded = []
        value_index = 0
        for variable in self.space_expanded:
            var_value = x[value_index : value_index + variable.dimensionality_in_model]
            var_value_rounded = variable.round(var_value)

            x_rounded.append(var_value_rounded)
            value_index += variable.dimensionality_in_model

        return np.atleast_2d(np.concatenate(x_rounded))
1324557
def softmax(x):
    """"""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=1)[:, None]
950796
def _max_args(self, f):
        
        if f.func_defaults is None:
            return f.func_code.co_argcount

        return f.func_code.co_argcount + len(f.func_defaults)
402524
def get_max_return(self, weights, returns):
        

        def func(weights):
            """The objective function that maximizes returns."""
            return np.dot(weights, returns.values) * -1

        constraints = ({'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)})
        solution = self.solve_minimize(func, weights, constraints)
        max_return = solution.fun * -1

        # NOTE: `max_risk` is not used anywhere, but may be helpful in the future.
        # allocation = solution.x
        # max_risk = np.matmul(
        #     np.matmul(allocation.transpose(), cov_matrix), allocation
        # )

        return max_return
360705
def _minimize_constraints_fun_summation(x):
    '''
    
    '''
    summation = sum([x[i] for i in CONSTRAINT_PARAMS_IDX])
    return CONSTRAINT_UPPERBOUND >= summation >= CONSTRAINT_LOWERBOUND
1129710
def optimize(self, G, params0=None, n_times=10, verbose=False, vmax=5, perturb=1e-3, factr=1e7):
        
        # set params0 from null if params0 is None
        if params0 is None:
            if self.null is None:
                if verbose:     print(".. fitting null model")
                self.fitNull()
            if self.bgRE:
                params0 = sp.concatenate([self.null['params0_g'], self.null['params0_n']])
            else:
                params0 = self.null['params0_n']
            params_was_None = True
        else:
            params_was_None = False
        G *= sp.sqrt(self.N/(G**2).sum())
        self._gp.covar.G = G
        start = TIME.time()
        for i in range(n_times):
            if params_was_None:
                n_params = self.Cr.getNumberParams()
                _params0 = {'covar': sp.concatenate([1e-3*sp.randn(n_params), params0])}
            else:
                _params0 = {'covar': params0}
            self._gp.setParams(_params0)
            conv, info = self._gp.optimize(factr=factr, verbose=verbose)
            conv *= self.Cr.K().diagonal().max()<vmax
            conv *= self.getLMLgrad() < 0.1
            if conv or not params_was_None: break
        self.infoOpt = info
        if not conv:
            warnings.warn("not converged")
        # return value
        RV = {}
        if self.P>1:
            RV['Cr']  = self.Cr.K()
            if self.bgRE: RV['Cg']  = self.Cg.K()
            RV['Cn']  = self.Cn.K()
        RV['time']  = sp.array([TIME.time()-start])
        RV['params0'] = _params0
        RV['nit'] = sp.array([info['nit']])
        RV['funcalls'] = sp.array([info['funcalls']])
        RV['var']    = self.getVariances()
        RV['conv']  = sp.array([conv])
        RV['NLLAlt']  = sp.array([self.getNLLAlt()])
        RV['LLR']    = sp.array([self.getLLR()])
        RV['LMLgrad'] = sp.array([self.getLMLgrad()])
        return RV
1187457
def run(self):
        
        if self.verbose:
            self.selftest()
        self.count = 0
        if self.verbose:
            logging.info('initial value of the objective function is %f'
                         % self.function(self.initial))
        theta0 = self.initial
        theta, f, d = fmin_l_bfgs_b(self.function_and_gradient, theta0, fprime=None, args=(),
                                    approx_grad=False, bounds=self.bounds, factr=self.tol,
                                    pgtol=1.0E-11, disp=0, maxiter=self.maxiter, maxfun=self.maxiter, maxls=100)
        if self.verbose:
            logging.info('l_bfgs_b says: '+str(d))
            logging.info('objective function value reached: %f' % f)
        if d['warnflag'] != 0:
            raise_or_warn(str(d), on_error=self.on_error, warning=NotConvergedWarning, exception=NotConvergedError)

        K = np.zeros((self.N, self.N))
        K[self.I, self.J] = theta / self.pi[self.I]
        K[self.J, self.I] = theta / self.pi[self.J]
        np.fill_diagonal(K, -np.sum(K, axis=1))
        self.K = K
        return K
853539
def print_objective(x):
    """"""
    value = 0
    for minp, maxp in rectangles:
        x_proj = np.minimum(np.maximum(x, minp), maxp)
        value += (x - x_proj).norm()
    print('Point = [{:.4f}, {:.4f}], Value = {:.4f}'.format(x[0], x[1], value))
1142355
def _max_helper(self, arr, approximate=False,
                    interp_kwargs=None, minimize_kwargs=None):
        
        assert self.norbits == 1
        assert self.t[-1] > self.t[0] # time must increase

        _ix = argrelmax(arr.value, mode='wrap')[0]
        _ix = _ix[(_ix != 0) & (_ix != (len(arr)-1))] # remove edges
        t = self.t.value

        approx_arr = arr[_ix]
        approx_t = t[_ix]

        if approximate:
            return approx_arr, approx_t * self.t.unit

        if interp_kwargs is None:
            interp_kwargs = dict()

        if minimize_kwargs is None:
            minimize_kwargs = dict()

        # default scipy function kwargs
        interp_kwargs.setdefault('k', 3)
        interp_kwargs.setdefault('ext', 3) # don't extrapolate, use boundary
        minimize_kwargs.setdefault('method', 'powell')

        # Interpolating function to upsample array:
        # Negative sign because we assume we're always finding the maxima
        interp_func = InterpolatedUnivariateSpline(t, -arr.value,
                                                   **interp_kwargs)

        better_times = np.zeros(_ix.shape, dtype=float)
        for i, j in enumerate(_ix):
            res = minimize(interp_func, t[j], **minimize_kwargs)
            better_times[i] = res.x

        better_arr = -interp_func(better_times)
        return better_arr * arr.unit, better_times * self.t.unit
669909
function getMaximum() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        return Math.max.apply(Math, args);
    }
1334287
def get_maximum(self, other):
        """"""
        return Point(max(self.x, other.x), max(self.y, other.y))
194570
def optimized(fn):
    

    def _optimized(self, *args, **kwargs):
        """ This method calls the pycastC function if
        optimization is enabled and the pycastC function
        is available.

        :param: PyCastObject self: reference to the calling object.
                                    Needs to be passed to the pycastC function,
                                    so that all uts members are available.
        :param: list *args: list of arguments the function is called with.
        :param: dict **kwargs: dictionary of parameter  names and values the function has been called with.

        :return result of the function call either from pycast or pycastC module.
        :rtype: function
        """
        if self.optimizationEnabled:
            class_name = self.__class__.__name__
            module     = self.__module__.replace("pycast", "pycastC")
            try:
                imported = __import__("%s.%s" % (module, class_name), globals(), locals(), [fn.__name__])
                function = getattr(imported, fn.__name__)
                return function(self, *args, **kwargs)
            except ImportError:
                print  "[WARNING] Could not enable optimization for %s, %s" % (fn.__name__, self)
                return fn(self, *args, **kwargs)
        else:
            return fn(self, *args, **kwargs)

    setattr(_optimized, "__name__", fn.__name__)
    setattr(_optimized, "__repr__", fn.__repr__)
    setattr(_optimized, "__str__",  fn.__str__)
    setattr(_optimized, "__doc__",  fn.__doc__)

    return _optimized
392792
def advise(self, **kwargs):
        '''
        
        '''
        for name, value in kwargs.iteritems():
            self._optimizer_parameters[name] = value
1016356
def min_max(obj, val, is_max):
    
    n = getattr(obj, 'maximum' if is_max else 'minimum', None)
    if n == None:
        return

    _eq = getattr(obj, 'exclusiveMaximum' if is_max else 'exclusiveMinimum', False)
    if is_max:
        to_raise = val >= n if _eq else val > n
    else:
        to_raise = val <= n if _eq else val < n

    if to_raise:
        raise ValidationError('condition failed: {0}, v:{1} compared to o:{2}'.format('maximum' if is_max else 'minimum', val, n))