Get an objective function to be optimized.
18071
def get_objective(self, sampler):
        """"""
        def objective(params):
            circuit = self.get_circuit(params)
            circuit.make_cache()
            return self.get_energy(circuit, sampler)
        return objective
117108
def _create_optObject(self, **kwargs):
        

        optimizer = kwargs.get('optimizer',
                               self.config['optimizer']['optimizer'])

        if optimizer.upper() == 'MINUIT':
            optObject = pyLike.Minuit(self.like.logLike)
        elif optimizer.upper() == 'NEWMINUIT':
            optObject = pyLike.NewMinuit(self.like.logLike)
        else:
            optFactory = pyLike.OptimizerFactory_instance()
            optObject = optFactory.create(str(optimizer), self.like.logLike)
        return optObject
458420
def _parse_optimization(optimization):
    ''''''
    splitted = optimization.split('.')
    if len(splitted) == 1:
        splitted = ['pythran', 'optimizations'] + splitted
    return reduce(getattr, splitted[1:], __import__(splitted[0]))
421358
def opt(self, x_init, f_fp=None, f=None, fp=None):
        
        rcstrings = ['','Maximum number of iterations exceeded', 'Gradient and/or function calls not changing']

        opt_dict = {}
        if self.xtol is not None:
            print("WARNING: bfgs doesn't have an xtol arg, so I'm going to ignore it")
        if self.ftol is not None:
            print("WARNING: bfgs doesn't have an ftol arg, so I'm going to ignore it")
        if self.gtol is not None:
            opt_dict['gtol'] = self.gtol

        opt_result = optimize.fmin_bfgs(f, x_init, fp, disp=self.messages,
                                            maxiter=self.max_iters, full_output=True, **opt_dict)
        self.x_opt = opt_result[0]
        self.f_opt = f_fp(self.x_opt)[0]
        self.funct_eval = opt_result[4]
        self.status = rcstrings[opt_result[6]]
1180601
def objective(self, params):
        """"""
        val = self._penalty * np.sum(params**2)
        for win, los in self._data:
            val += np.logaddexp(0, -(params[win] - params[los]))
        return val
641560
def set_objective(self, expression):
        """"""

        if isinstance(expression, numbers.Number):
            # Allow expressions with no variables as objective,
            # represented as a number
            expression = Expression(offset=expression)

        linear = []
        quad = []

        # Reset previous objective.
        for var in self._non_zero_objective:
            if var not in expression:
                if not isinstance(var, Product):
                    linear.append((self._variables[var], 0))
                else:
                    t = self._variables[var[0]], self._variables[var[1]], 0
                    quad.append(t)

        self._non_zero_objective.clear()

        # Set actual objective values
        for var, value in expression.values():
            if not isinstance(var, Product):
                self._non_zero_objective.add(var)
                linear.append((self._variables[var], float(value)))
            else:
                if len(var) > 2:
                    raise ValueError('Invalid objective: {}'.format(var))
                self._non_zero_objective.add(var)
                var1 = self._variables[var[0]]
                var2 = self._variables[var[1]]
                if var1 == var2:
                    value *= 2
                quad.append((var1, var2, float(value)))

        # We have to build the set of variables to
        # update so that we can avoid calling set_linear if the set is empty.
        # This is due to set_linear failing if the input is an empty
        # iterable.
        if len(linear) > 0:
            self._cp.objective.set_linear(linear)
        if len(quad) > 0:
            self._cp.objective.set_quadratic_coefficients(quad)

        if hasattr(self._cp.objective, 'set_offset'):
            self._cp.objective.set_offset(float(expression.offset))
125230
def still_optimizing(self):
        """"""

        # Check if we need to give up on optimizing.
        if (self.iterations > self.max_iter) or (self.time_elapsed() > self.max_time):
            return False

        # Always optimize for at least 'min_iter' iterations.
        elif not hasattr(self, 'improvement') or (self.iterations < self.min_iter):
            return True

        # Check convergence.
        else:
            self.converged = self.improvement < self.tol
            return False if self.converged else True
476147
def optimize(self, loss, num_async_replicas=1, use_tpu=False):
    """"""
    lr = learning_rate.learning_rate_schedule(self.hparams)
    if num_async_replicas > 1:
      log_info("Dividing learning rate by num_async_replicas: %d",
               num_async_replicas)
    lr /= math.sqrt(float(num_async_replicas))
    train_op = optimize.optimize(loss, lr, self.hparams, use_tpu=use_tpu)
    return train_op
209417
function (ast, setting, debug) {
        let optimizer = new Optimizer(ast, setting, debug);
        optimizer.analyze();
        optimizer.optimize();
        return ast;
    }
156652
def maximize(self,
                 init_points=5,
                 n_iter=25,
                 acq='ucb',
                 kappa=2.576,
                 xi=0.0,
                 **gp_params):
        """"""
        self._prime_subscriptions()
        self.dispatch(Events.OPTMIZATION_START)
        self._prime_queue(init_points)
        self.set_gp_params(**gp_params)

        util = UtilityFunction(kind=acq, kappa=kappa, xi=xi)
        iteration = 0
        while not self._queue.empty or iteration < n_iter:
            try:
                x_probe = next(self._queue)
            except StopIteration:
                x_probe = self.suggest(util)
                iteration += 1

            self.probe(x_probe, lazy=False)

        self.dispatch(Events.OPTMIZATION_END)
856584
def main(dimension, iterations):
    
    objective_function = minimize(functions.sphere)
    stopping_condition = max_iterations(iterations)
    (solution, metrics) = optimize(objective_function=objective_function,
                                   domain=Domain(-5.12, 5.12, dimension),
                                   stopping_condition=stopping_condition,
                                   parameters={'seed': 3758117674,
                                               'rho': 1.0, 'e_s': 15, 'e_f': 5},
                                   velocity_update=gc_velocity_update,
                                   parameter_update=update_rho,
                                   measurements=[fitness_measurement])
    return solution
571685
void optimizeReset() {
    FlatParagraphTools flatPara = new FlatParagraphTools(xContext);
    flatPara.markFlatParasAsChecked(resetFrom + divNum, resetTo + divNum, isChecked);
    resetCheck = false;
  }
845291
def optimize(self, x0, target):
        """"""
        x = x0
        for _ in range(self.maxiter):
            delta = np.linalg.solve(self.h(x, target), -self.g(x, target))
            x = x + delta
            if np.linalg.norm(delta) < self.tol:
                break
        return x
917704
def opt(self, x_init, f_fp=None, f=None, fp=None):
        
        rcstrings = ['Converged', 'Maximum number of f evaluations reached', 'Error']

        assert f_fp != None, "BFGS requires f_fp"

        opt_dict = {}
        if self.xtol is not None:
            print("WARNING: l-bfgs-b doesn't have an xtol arg, so I'm going to ignore it")
        if self.ftol is not None:
            print("WARNING: l-bfgs-b doesn't have an ftol arg, so I'm going to ignore it")
        if self.gtol is not None:
            opt_dict['pgtol'] = self.gtol
        if self.bfgs_factor is not None:
            opt_dict['factr'] = self.bfgs_factor

        opt_result = optimize.fmin_l_bfgs_b(f_fp, x_init, maxfun=self.max_iters, maxiter=self.max_iters, **opt_dict)
        self.x_opt = opt_result[0]
        self.f_opt = f_fp(self.x_opt)[0]
        self.funct_eval = opt_result[2]['funcalls']
        self.status = rcstrings[opt_result[2]['warnflag']]

        #a more helpful error message is available in opt_result in the Error case
        if opt_result[2]['warnflag']==2: # pragma: no coverage, this is not needed to be covered
            self.status = 'Error' + str(opt_result[2]['task'])
1321913
def optimize(qs, info_dict, field_map):
    """"""
    fields = collect_fields(info_dict)
    for field in fields:
        if field in field_map:
            field_name, opt = field_map[field]
            qs = (qs.prefetch_related(field_name)
                  if opt == "prefetch" else qs.select_related(field_name))

    return qs
707887
def optimize
      # Ensure pending variables and constraints are added
      update

      # Run the solver and save the status for later
      iocp = GLPK::IOCP.new
      GLPK.glp_init_iocp iocp
      iocp[:presolve] = GLPK::GLP_ON
      status = GLPK.glp_intopt(@ptr, iocp)

      save_solution status
    end
348590
def set_objective_sense(self, sense):
        """"""

        if sense not in (ObjectiveSense.Minimize, ObjectiveSense.Maximize):
            raise ValueError('Invalid objective sense')

        self._p.ModelSense = self.OBJ_SENSE_MAP[sense]