Set type of problem (maximize or minimize).
169666
def set_objective_sense(self, sense):
        """"""

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

        swiglpk.glp_set_obj_dir(self._p, self.OBJ_SENSE_MAP[sense])
669942
private void defaultHeuristic() {
        IntStrategy intStrat = Search.intVarSearch(new FirstFail(csp), new IntDomainMin(), csp.retrieveIntVars(true));
        SetStrategy setStrat = new SetStrategy(csp.retrieveSetVars(), new InputOrder<>(csp), new SetDomainMin(), true);
        RealStrategy realStrat = new RealStrategy(csp.retrieveRealVars(), new Occurrence<>(), new RealDomainMiddle());
        solver.setSearch(new StrategiesSequencer(intStrat, realStrat, setStrat));
    }
539107
def _setuplimits(self, constraints):
        """"""
        self.constraints = tuple(constraints)
        assert len(self.constraints) == self.fmodel.dim_x
        self.goal = None
445828
def solve_minimize(
        self,
        func,
        weights,
        constraints,
        lower_bound=0.0,
        upper_bound=1.0,
        func_deriv=False
    ):
        

        bounds = ((lower_bound, upper_bound), ) * len(self.SUPPORTED_COINS)
        return minimize(
            fun=func, x0=weights, jac=func_deriv, bounds=bounds,
            constraints=constraints, method='SLSQP', options={'disp': False}
        )
826744
function(a, b){
    return new BB(
            min(a.l, b.l),
            min(a.b, b.b),
            max(a.r, b.r),
            max(a.t, b.t)
        );
}
200118
def setbb(self, x, y):
        """"""
        self.__xmin = min(self.__xmin, max(x, self.__clip_box[0]))
        self.__xmax = max(self.__xmax, min(x, self.__clip_box[2]))
        self.__ymin = min(self.__ymin, max(y, self.__clip_box[1]))
        self.__ymax = max(self.__ymax, min(y, self.__clip_box[3]))
1178126
private static MinimizedCondition computeMinimizedCondition(Node n) {
    switch (n.getToken()) {
      case NOT: {
        MinimizedCondition subtree = computeMinimizedCondition(n.getFirstChild());
        MeasuredNode positive = pickBest(
            MeasuredNode.addNode(n, subtree.positive),
            subtree.negative);
        MeasuredNode negative = pickBest(
            subtree.negative.negate(),
            subtree.positive);
        return new MinimizedCondition(positive, negative);
      }
      case AND:
      case OR: {
        Node complementNode = new Node(n.getToken() == Token.AND ? Token.OR : Token.AND).srcref(n);
        MinimizedCondition leftSubtree = computeMinimizedCondition(n.getFirstChild());
        MinimizedCondition rightSubtree = computeMinimizedCondition(n.getLastChild());
        MeasuredNode positive = pickBest(
            MeasuredNode.addNode(n,
                leftSubtree.positive,
                rightSubtree.positive),
            MeasuredNode.addNode(complementNode,
                leftSubtree.negative,
                rightSubtree.negative).negate());
        MeasuredNode negative = pickBest(
            MeasuredNode.addNode(n,
                leftSubtree.positive,
                rightSubtree.positive).negate(),
            MeasuredNode.addNode(complementNode,
                leftSubtree.negative,
                rightSubtree.negative).change());
        return new MinimizedCondition(positive, negative);
      }
      case HOOK: {
        Node cond = n.getFirstChild();
        Node thenNode = cond.getNext();
        Node elseNode = thenNode.getNext();
        MinimizedCondition thenSubtree = computeMinimizedCondition(thenNode);
        MinimizedCondition elseSubtree = computeMinimizedCondition(elseNode);
        MeasuredNode positive = MeasuredNode.addNode(
            n,
            MeasuredNode.forNode(cond),
            thenSubtree.positive,
            elseSubtree.positive);
        MeasuredNode negative = MeasuredNode.addNode(
            n,
            MeasuredNode.forNode(cond),
            thenSubtree.negative,
            elseSubtree.negative);
        return new MinimizedCondition(positive, negative);
      }
      case COMMA: {
        Node lhs = n.getFirstChild();
        MinimizedCondition rhsSubtree = computeMinimizedCondition(lhs.getNext());
        MeasuredNode positive = MeasuredNode.addNode(
            n,
            MeasuredNode.forNode(lhs),
            rhsSubtree.positive);
        MeasuredNode negative = MeasuredNode.addNode(
            n,
            MeasuredNode.forNode(lhs),
            rhsSubtree.negative);
        return new MinimizedCondition(positive, negative);
      }
      default: {
        MeasuredNode pos = MeasuredNode.forNode(n);
        MeasuredNode neg = pos.negate();
        return new MinimizedCondition(pos, neg);
      }
    }
  }
168750
protected void maximization() {
		// discard previous parameters by zeroing
		for (int i = 0; i < mixture.size; i++) {
			mixture.get(i).zero();
		}

		// compute the new mean
		for (int i = 0; i < info.size; i++) {
			PointInfo p = info.get(i);

			for (int j = 0; j < mixture.size; j++) {
				mixture.get(j).addMean(p.point,p.weights.get(j));
			}
		}
		for (int i = 0; i < mixture.size; i++) {
			GaussianGmm_F64 g = mixture.get(i);
			if( g.weight > 0 )
				CommonOps_DDRM.divide(g.mean,g.weight);
		}

		// compute new covariance
		for (int i = 0; i < info.size; i++) {
			PointInfo pp = info.get(i);
			double[] p = pp.point;

			for (int j = 0; j < mixture.size; j++) {
				GaussianGmm_F64 g = mixture.get(j);

				for (int k = 0; k < p.length; k++) {
					dx[k] = p[k]-g.mean.data[k];
				}

				mixture.get(j).addCovariance(dx, pp.weights.get(j));
			}
		}
		double totalMixtureWeight = 0;
		for (int i = 0; i < mixture.size; i++) {
			GaussianGmm_F64 g = mixture.get(i);
			if( g.weight > 0 ) {
				CommonOps_DDRM.divide(g.covariance, g.weight);
				totalMixtureWeight += g.weight;
			}
		}

		// update the weight
		for (int i = 0; i < mixture.size; i++) {
			mixture.get(i).weight /= totalMixtureWeight;
		}
	}
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
28093
def set_conditions(self, variables, constraints):
        
        self._vars, self._constraints = variables, []
        self._constraints_for_var = {}
        vars_constraint_count = {}
        # build constraint objects
        for func, variables, values in constraints:
            c = Constraint(func, variables, values, self._compute_search_spaces(variables))
            self._constraints.append(c)
            for var in variables:
                self._constraints_for_var[var] = self._constraints_for_var.get(var, []) + [c]
                vars_constraint_count[var] = vars_constraint_count.get(var, 0) + 1
        # sort into most constraining first
        self._constraints.sort()

        self._variable_expand_order = tuple(sorted(self._vars.keys(), key=vars_constraint_count.get, reverse=True))
208523
private double optimize(int k0, int kmax, double sumx, double sumx2, double xp, double yp, double sumxy, double sumy) {
    int k = kmax - k0 + 1;
    return (sumxy - xp * sumy - yp * sumx + k * xp * yp) / (sumx2 - 2 * sumx * xp + k * xp * xp);
    // return (-xp * yp * + yp * sumx - sumxy + xp * sumy) / (-xp * xp *
    // kmax - sumx2 + 2 * xp * sumx);
  }
571685
void optimizeReset() {
    FlatParagraphTools flatPara = new FlatParagraphTools(xContext);
    flatPara.markFlatParasAsChecked(resetFrom + divNum, resetTo + divNum, isChecked);
    resetCheck = false;
  }
80528
def setcover_ilp(candidate_sets_dict, items=None, set_weights=None, item_values=None, max_weight=None, verbose=False):
    
    import utool as ut
    import pulp
    if items is None:
        items = ut.flatten(candidate_sets_dict.values())
    if set_weights is None:
        set_weights = {i: 1 for i in candidate_sets_dict.keys()}
    if item_values is None:
        item_values = {e: 1 for e in items}

    if max_weight is None:
        max_weight = sum(ut.take(set_weights, candidate_sets_dict.keys()))

    if False:
        # This is true set coer
        # Formulate integer program
        prob = pulp.LpProblem("Set Cover", pulp.LpMinimize)
        # Solution variable indicates if set it chosen or not
        set_indices = candidate_sets_dict.keys()
        x = pulp.LpVariable.dicts(name='x', indexs=set_indices,
                                  lowBound=0, upBound=1, cat=pulp.LpInteger)
        # minimize the number of sets
        prob.objective = sum(x[i] for i in set_indices)
        # subject to
        for e in items:
            # each element is covered
            containing_sets = [i for i in set_indices if e in candidate_sets_dict[i]]
            prob.add(sum(x[i] for i in containing_sets) >= 1)
        # Solve using with solver like CPLEX, GLPK, or SCIP.
        #pulp.CPLEX().solve(prob)
        pulp.PULP_CBC_CMD().solve(prob)
        # Read solution
        solution_keys = [i for i in set_indices if x[i].varValue]
        solution_cover = {i: candidate_sets_dict[i] for i in solution_keys}
        # Print summary
        if verbose:
            print(prob)
            print('OPT:')
            print('\n'.join(['    %s = %s' % (x[i].name, x[i].varValue) for i in set_indices]))
            print('solution_cover = %r' % (solution_cover,))
    else:
        prob = pulp.LpProblem("Maximum Cover", pulp.LpMaximize)
        # Solution variable indicates if set it chosen or not
        item_indicies = items
        set_indices = candidate_sets_dict.keys()
        x = pulp.LpVariable.dicts(name='x', indexs=set_indices,
                                  lowBound=0, upBound=1, cat=pulp.LpInteger)
        y = pulp.LpVariable.dicts(name='y', indexs=item_indicies,
                                  lowBound=0, upBound=1, cat=pulp.LpInteger)
        r = pulp.LpVariable.dicts(name='r', indexs=item_indicies)
        # maximize the value of the covered items
        primary_objective = sum(item_values[e] * y[e] for e in item_indicies)
        # minimize the number of sets used (make sure it does not influence the chosen primary objective)
        # This is only possible when values are non-negative
        # TODO: minimize redundency
        min_influence = min(item_values.values())
        secondary_weight = min_influence / (1.1 * len(set_indices))
        secondary_objective = (sum(-x[i] for i in set_indices)) * secondary_weight
        #
        prob.objective = primary_objective + secondary_objective
        # subject to
        # no more than the maximum weight
        prob.add(sum(x[i] * set_weights[i] for i in set_indices) <= max_weight)
        # If an item is chosen than at least one set containing it is chosen
        for e in item_indicies:
            containing_sets = [i for i in set_indices if e in candidate_sets_dict[i]]
            if len(containing_sets) > 0:
                prob.add(sum(x[i] for i in containing_sets) >= y[e])
                # record number of times each item is covered
                prob.add(sum(x[i] for i in containing_sets) == r[e])
        # Solve using with solver like CPLEX, GLPK, or SCIP.
        #pulp.CPLEX().solve(prob)
        pulp.PULP_CBC_CMD().solve(prob)
        # Read solution
        solution_keys = [i for i in set_indices if x[i].varValue]
        solution_cover = {i: candidate_sets_dict[i] for i in solution_keys}
        # Print summary
        if verbose:
            print(prob)
            print('OPT:')
            print('\n'.join(['    %s = %s' % (x[i].name, x[i].varValue) for i in set_indices]))
            print('\n'.join(['    %s = %s' % (y[i].name, y[i].varValue) for i in item_indicies]))
            print('solution_cover = %r' % (solution_cover,))
    return solution_cover
223557
def optimize(self, x0, f=None, df=None, f_df=None):
        
        # Based on the documentation of DIRECT, it does not seem we can pass through an initial point x0
        try:
            from DIRECT import solve
            def DIRECT_f_wrapper(f):
                def g(x, user_data):
                    return f(np.array([x])), 0
                return g
            lB = np.asarray(self.bounds)[:,0]
            uB = np.asarray(self.bounds)[:,1]
            x,_,_ = solve(DIRECT_f_wrapper(f),lB,uB, maxT=self.maxiter)
            return np.atleast_2d(x), f(np.atleast_2d(x))
        except ImportError:
            print("Cannot find DIRECT library, please install it to use this option.")
            raise
987321
def as_minimized(values: List[float], maximized: List[bool]) -> List[float]:
    
    return [v * -1. if m else v for v, m in zip(values, maximized)]
45530
def dumbguy_minimize(f, xmin, xmax, xstep):
    

    prev = f(xmin)
    this = f(xmin+xstep)
    for x in frange(xmin+xstep,xmax,xstep):
        next = f(x+xstep)

        # see if we're on top
        if this < prev and this < next: return x, this

        prev = this
        this = next

    return x, this
207402
def minimize(self, minimize):
        '''
        '''

        self._minimize = minimize
        self._logger.log('debug', 'Minimize set to {}'.format(minimize))