Пример #1
0
    def solve_problem_min_cost_s_t_model(self, model, x, tol):
        '''
        Fucntion solve the optimization problem find the x' that minimize the cost function with constrain of
        the model predict x' as positive.
        :param model: The model that the player wants to get positive prediction.
        :param x: Current player's vector features.
        :param tol: Small tolerance for optimization needs. That indicates how much x' should be above the model
        intercept.
        :return: Tuple: (x', cost(x, x')).
        '''
        x_t = cp.Variable(len(x))
        func_to_solve = cp.Minimize(self.cost_factor * (cp.maximum(
            (1 - self.epsilon) * self.a.T @ (x_t - x), 0) +
                                                        self.epsilon * cp.sum(
                                                            (x_t - x)**2)))
        constrains = [x_t @ model.coef_[0] >= -model.intercept_ + tol]

        prob = cp.Problem(func_to_solve, constrains)
        try:
            prob.solve()
            if x_t is None:
                print("couldn't solve this problem")
                return
            cost = cp.maximum((1 - self.epsilon) * self.a.T @ (x_t - x),
                              0) + self.epsilon * cp.sum((x_t - x)**2)
            cost *= self.cost_factor
            return x_t, cost
        except:
            print('solver failed')
            return x, None
Пример #2
0
    def op_func(self, A, B, estimate_loss):
        """ 
        Solves the convex optimzation problem 
        
        Args:
            A: Exponent of power-law equation
            B: of power-law equation
            estimate_loss: estimated loss on given data using power-law equation
        
        Return: Number of examples to collect for the slices within the budget
        """

        x = cp.Variable(self.num_class, integer=True)
        for i in range(self.num_class):
            loss = cp.multiply(B[i],
                               cp.power((x[i] + self.data_num_array[i]), A[i]))
            counter_loss = (np.sum(estimate_loss) -
                            estimate_loss[i]) / (self.num_class - 1)
            if i == 0:
                ob_func = loss + self.Lambda * cp.maximum(
                    0, (loss / counter_loss) - 1)
            else:
                ob_func += loss + self.Lambda * cp.maximum(
                    0, (loss / counter_loss) - 1)

        constraints = [cp.sum(cp.multiply(x, self.cost_func)) <= self.budget
                       ] + [x >= 0]
        objective = cp.Minimize(ob_func)
        prob = cp.Problem(objective, constraints)
        prob.solve(solver="ECOS_BB")
        return np.add(x.value, 0.5).astype(int)
Пример #3
0
    def test_rank_one_nmf(self):
        X = cp.Variable((3, 3), pos=True)
        x = cp.Variable((3, ), pos=True)
        y = cp.Variable((3, ), pos=True)
        xy = cp.vstack([x[0] * y, x[1] * y, x[2] * y])
        R = cp.maximum(cp.multiply(X, (xy)**(-1.0)),
                       cp.multiply(X**(-1.0), xy))
        objective = cp.sum(R)
        constraints = [
            X[0, 0] == 1.0,
            X[0, 2] == 1.9,
            X[1, 1] == 0.8,
            X[2, 0] == 3.2,
            X[2, 1] == 5.9,
            x[0] * x[1] * x[2] == 1.0,
        ]
        # smoke test.
        prob = cp.Problem(cp.Minimize(objective), constraints)
        prob.solve(SOLVER, gp=True)
        optimal_value = prob.value

        param = cp.Parameter(value=-2.0)
        R = cp.maximum(cp.multiply(X, (xy)**(param)),
                       cp.multiply(X**(param), xy))
        objective = cp.sum(R)
        prob = cp.Problem(cp.Minimize(objective), constraints)
        prob.solve(SOLVER, gp=True, enforce_dpp=True)

        # now change param to point to known_value, and check we recover the
        # correct optimal value
        param.value = -1.0
        prob.solve(SOLVER, gp=True, enforce_dpp=True)
        self.assertAlmostEqual(prob.value, optimal_value)
Пример #4
0
def peak(rates, infrastructure, interface, baseline_peak=0, **kwargs):
    agg_power = aggregate_power(rates, infrastructure)
    max_power = cp.max(agg_power)
    prev_peak = interface.get_prev_peak() * infrastructure.voltages[0] / 1000
    if baseline_peak > 0:
        return cp.maximum(max_power, baseline_peak, prev_peak)
    else:
        return cp.maximum(max_power, prev_peak)
Пример #5
0
    def test_elemwise_arg_count(self) -> None:
        """Test arg count for max and min variants.
        """
        error_message = r"__init__\(\) missing 1 required positional argument: 'arg2'"
        with pytest.raises(TypeError, match=error_message):
            cp.maximum(1)

        with pytest.raises(TypeError, match=error_message):
            cp.minimum(1)
Пример #6
0
    def test_maximum(self) -> None:
        """Test domain for maximum.
        """
        b = Variable()
        expr = cp.maximum(self.a, b)
        self.a.value = 2
        b.value = 4
        self.assertAlmostEqual(expr.grad[self.a], 0)
        self.assertAlmostEqual(expr.grad[b], 1)

        self.a.value = 3
        b.value = 0
        self.assertAlmostEqual(expr.grad[self.a], 1)
        self.assertAlmostEqual(expr.grad[b], 0)

        self.a.value = -1
        b.value = 2
        self.assertAlmostEqual(expr.grad[self.a], 0)
        self.assertAlmostEqual(expr.grad[b], 1)

        y = Variable(2)
        expr = cp.maximum(self.x, y)
        self.x.value = [3, 4]
        y.value = [5, -5]
        val = np.zeros((2, 2)) + np.diag([0, 1])
        self.assertItemsAlmostEqual(expr.grad[self.x].toarray(), val)
        val = np.zeros((2, 2)) + np.diag([1, 0])
        self.assertItemsAlmostEqual(expr.grad[y].toarray(), val)

        expr = cp.maximum(self.x, y)
        self.x.value = [-1e-9, 4]
        y.value = [1, 4]
        val = np.zeros((2, 2)) + np.diag([0, 1])
        self.assertItemsAlmostEqual(expr.grad[self.x].toarray(), val)
        val = np.zeros((2, 2)) + np.diag([1, 0])
        self.assertItemsAlmostEqual(expr.grad[y].toarray(), val)

        expr = cp.maximum(self.A, self.B)
        self.A.value = [[1, 2], [3, 4]]
        self.B.value = [[5, 1], [3, 2.3]]
        val = np.zeros((4, 4)) + np.diag([0, 1, 1, 1])
        self.assertItemsAlmostEqual(expr.grad[self.A].toarray(), val)
        val = np.zeros((4, 4)) + np.diag([1, 0, 0, 0])
        self.assertItemsAlmostEqual(expr.grad[self.B].toarray(), val)

        # cummax
        expr = cp.cummax(self.x)
        self.x.value = [2, 1]
        val = np.zeros((2, 2))
        val[0, 0] = 1
        self.assertItemsAlmostEqual(expr.grad[self.x].toarray(), val)

        expr = cp.cummax(self.x[:, None], axis=1)
        self.x.value = [2, 1]
        val = np.eye(2)
        self.assertItemsAlmostEqual(expr.grad[self.x].toarray(), val)
Пример #7
0
    def test_elemwise_arg_count(self):
        """Test arg count for max and min variants.
        """
        with self.assertRaises(Exception) as cm:
            cp.maximum(1)
        self.assertTrue(str(cm.exception) in (
            "__init__() takes at least 3 arguments (2 given)",
            "__init__() missing 1 required positional argument: 'arg2'"))

        with self.assertRaises(Exception) as cm:
            cp.minimum(1)
        self.assertTrue(str(cm.exception) in (
            "__init__() takes at least 3 arguments (2 given)",
            "__init__() missing 1 required positional argument: 'arg2'"))
    def maximize_features_against_binary_model(self, x: np.array, trained_model, tolerance=1e-9):
        x_tag = cp.Variable(len(x))

        func_to_solve = cp.Minimize(cp.maximum(self.cost_factor * self.a.T @ (x_tag - x), 0))
        constrains = [x_tag @ trained_model.coef_[0] >= -trained_model.intercept_ + tolerance]
        prob = cp.Problem(func_to_solve, constrains)
        prob.solve()
        cost_result = cp.maximum(self.cost_factor * self.a.T @ (x_tag.value - x), 0)
        if x_tag is None:
            print("couldn't solve this problem")
            return
        if trained_model.predict(x_tag.value.reshape(1, -1))[0] == 1 and cost_result.value < 2:
            return x_tag.value
        else:
            return x
Пример #9
0
    def difference_magnitude(self, other):
        # TODO:
        assert type(other) is QuadraticForm, \
            'Quadratic forms can only be compared among themselves'
        assert self.n == other.n, \
            'Quadratic forms must have the same dimension'

        if (self.b is None and self.c is None and other.b is None
                and other.c is None):
            lbd = cvx.Variable()
            mid_matrix = self.Q - lbd * other.Q
            con = [lbd >= 0]
        else:
            mid_matrix = self.Q - other.Q
            con = []

        mu_pos = cvx.Variable()
        mu_neg = cvx.Variable()
        con.append(mid_matrix << mu_pos * np.eye(self.n))
        con.append(mid_matrix >> -mu_neg * np.eye(self.n))
        con += [mu_pos >= 0, mu_neg >= 0]

        prob = cvx.Problem(cvx.Minimize(cvx.maximum(mu_pos, mu_neg)), con)
        prob.solve()

        if prob.status != 'optimal':
            if 'innacurate' in prob.status:
                logging.warning('Problem status is %s', prob.status)
            else:
                raise ETCUtilError(
                    'This shouldn'
                    't be happening. Problem status is %s', prob.status)

        return prob.value
Пример #10
0
 def test_rank_one_nmf(self) -> None:
     X = cp.Variable((3, 3), pos=True)
     x = cp.Variable((3, ), pos=True)
     y = cp.Variable((3, ), pos=True)
     xy = cp.vstack([x[0] * y, x[1] * y, x[2] * y])
     a = cp.Parameter(value=-1.0)
     b = cp.Parameter(pos=True,
                      shape=(6, ),
                      value=np.array([1.0, 1.9, 0.8, 3.2, 5.9, 1.0]))
     R = cp.maximum(cp.multiply(X, (xy)**(a)), cp.multiply(X**(a), xy))
     objective = cp.sum(R)
     constraints = [
         X[0, 0] == b[0],
         X[0, 2] == b[1],
         X[1, 1] == b[2],
         X[2, 0] == b[3],
         X[2, 1] == b[4],
         x[0] * x[1] * x[2] == b[5],
     ]
     problem = cp.Problem(cp.Minimize(objective), constraints)
     # SCS struggles to solves this problem (solved/inaccurate, unless
     # max_iters is very high like 10000)
     gradcheck(problem,
               gp=True,
               solve_methods=[s.SCS],
               atol=1e-2,
               max_iters=1000)
     perturbcheck(problem,
                  gp=True,
                  solve_methods=[s.SCS],
                  atol=1e-2,
                  max_iters=1000)
def offline_dynamic_provision(df, verbose):
    p = 0.4 / 2
    a = 4 / 2
    b = 4 / 2
    y = df.to_list()
    x = cp.Variable(672)
    cost = 0

    for i in range(1, 672):
        cost += p * x[i] + a * cp.maximum(
            0, y[i - 1] - x[i]) + b * cp.abs(x[i] - x[i - 1])

    objective = cp.Minimize(cost)
    constraints = [x[0] == 0, x[1:] >= 0]
    problem = cp.Problem(objective, constraints)
    result = problem.solve()
    opt = pd.Series(np.array(x.value), index=df.index)
    opt_dict['Offline Dynamic'] = result
    decision_dict['Offline Dynamic'] = opt

    if (verbose == True):
        print("\nThe optimal value is", result)
        print("First 15 optimal values of x is")
        print(x.value[0:15])
        plot_graph_offline('dynamic', opt)
    else:
        return opt
Пример #12
0
    def _init_input_constraints(self):
        input_constraints = {
            "s": self.constraints.sin,
            "v": self.constraints.vin
        }
        node_push_map = {
            "s": defaultdict(set),
            "v": defaultdict(set)
        }

        for src, dst, tp, _ in self.edges:
            if dst not in self.node_to_loc_map:
                continue
            node_push_map[tp][src].add(dst)

        for tp, push_map in node_push_map.items():
            if not push_map:
                continue
            movement = []
            for src, destinations in push_map.items():
                if not self._is_internal_node(src):
                    # we use this to filter out all of the contributions within a partition.
                    # since external nodes aren't in any relevant partition, they always contribute.
                    base_filter = np.zeros(self.partitions)
                else:
                    base_filter = self.node_to_partition_matrix[self.node_to_loc_map[src], :]

                contributions = functools.reduce(operator.add, [
                    self.node_to_partition_matrix[self.node_to_loc_map[dst]] for dst in destinations])
                movement.append(cvxpy.maximum(self._project_to_bool(contributions) - base_filter, 0))

                self.to_print["output - " + tp] = movement
            self._add_constraint(
                functools.reduce(operator.add, movement) <= input_constraints[tp])
def rhc_fixed_window(y, predictionHorizon, prediction_algo):
  T = 4;
  p = 0.4/2;
  a = 4/2;
  b = 4/2;
  optValues = np.zeros(T);
  for horizonStart in range(0, T):
    horizonEnd = horizonStart + predictionHorizon
    windowY = y[horizonStart: horizonEnd]
    
    obj = 0;
    x = cp.Variable(predictionHorizon)
    
    for i in range(0, predictionHorizon):
        obj += p * x[i] + a * cp.maximum(0, windowY[i] - x[i])
        if i == 0:
            obj += b * cp.abs(x[i]); #because x(0) is 0
        else:
            obj += b * cp.abs(x[i] - x[i - 1])
    
    objective = cp.Minimize(obj)
    problem = cp.Problem(objective)
    result = problem.solve()
    
    optValues[horizonStart] = x.value[0];

  obj = 0;
  for i in range(0, T):
      obj += p * optValues[i] + a * max(0, y[i] - optValues[i])
      if i == 0:
          obj += b * abs(optValues[i]); #because x(0) is 0
      else:
          obj += b * abs(optValues[i] - optValues[i - 1])

  return obj
    def solve_problem_max_model_s_t_cost(self, model, x, spare_cost, tol=0.00001):
        x_t = cp.Variable(len(x))
        func_to_solve = cp.Maximize(
            x_t @ model.coef_[0] + model.intercept_)

        constrains = [self.cost_factor * (cp.maximum((1 - self.epsilon) * self.a.T @ (x_t - x), 0) + self.epsilon *
                                          cp.sum((x_t - x) ** 2)) <= spare_cost - tol]
        prob = cp.Problem(func_to_solve, constrains)
        prob.solve()
        if x_t.value is None:
            print("couldn't solve this problem")
            return None
        cost = cp.maximum((1 - self.epsilon) * self.a.T @ (x_t - x), 0) + self.epsilon * cp.sum(
            (x_t - x) ** 2)
        cost *= self.cost_factor
        return x_t, cost
Пример #15
0
    def test_maximum(self):
        x = cp.Variable(pos=True)
        y = cp.Variable(pos=True)

        alpha = cp.Parameter(value=0.5)
        beta = cp.Parameter(pos=True, value=3.0)
        kappa = cp.Parameter(pos=True, value=1.0)
        tau = cp.Parameter(pos=True, value=4.0)

        prod1 = x * y**alpha
        prod2 = beta * x * y**alpha
        obj = cp.Minimize(cp.maximum(prod1, prod2))
        constr = [x == kappa, y == tau]

        problem = cp.Problem(obj, constr)
        self.assertTrue(problem.is_dgp(dpp=True))
        problem.solve(SOLVER, gp=True, enforce_dpp=True)
        # max(1*2, 3*1*2) = 6
        self.assertAlmostEqual(problem.value, 6.0, places=4)
        self.assertAlmostEqual(x.value, 1.0)
        self.assertAlmostEqual(y.value, 4.0)

        alpha.value = 2
        beta.value = 0.5
        kappa.value = 2.0  # x
        tau.value = 3.0  # y
        problem.solve(SOLVER, gp=True, enforce_dpp=True)
        # max(2*9, 0.5*2*9) == 18
        self.assertAlmostEqual(problem.value, 18.0, places=4)
        self.assertAlmostEqual(x.value, 2.0)
        self.assertAlmostEqual(y.value, 3.0)
Пример #16
0
  def train(self, X, Y):
    '''Assumes that each row is a sample'''
    # Create two optimization variables.
    w = cp.Variable(X.shape[1])
    b = cp.Variable()
    
    # Create constraints.
    constraints = self._create_cons(Y, X, w, b)

    # Form objective.
    obj = (1/2)*cp.norm(w,2)
    if self.soft:
      obj = obj/(self.C)
      for i in range(X.shape[0]):
        temp = cp.maximum(0, 1 - Y[i] * (w @ np.squeeze(X[i, :]) + b))
        obj = obj + temp
    obj = cp.Minimize(obj)

    # Form and solve problem.
    prob = cp.Problem(obj, constraints)
    prob.solve()  # Returns the optimal value.
    
    # storing for future accesses
    self.obj = obj
    self.constraints = constraints
    self.prob = prob
    self.w = w
    self.b = b
Пример #17
0
    def _init_output_constraints(self):
        output_constraints = {
            "s": self.constraints.sout,
            "v": self.constraints.vout
        }
        # for each node, if it's used anywhere not in the same partition, then it counts.

        # an external output automatically counts
        nodes_with_external_outputs = {
            "s": set(),
            "v": set()
        }
        for src, dst, tp, _ in self.edges:
            if self._is_internal_node(src) and not self._is_internal_node(dst):
                nodes_with_external_outputs[tp].add(src)

        node_push_map = {
            "s": defaultdict(set),
            "v": defaultdict(set)
        }

        for src, dst, tp, _ in self.edges:
            # don't count external nodes
            if not self._is_internal_node(src):
                continue
            # if a node already pushes out to an external node, we know it's guaranteed to have an output.
            if src in nodes_with_external_outputs[tp]:
                continue

            node_push_map[tp][self.node_to_loc_map[src]].add(self.node_to_loc_map[dst])

        for tp, push_map in node_push_map.items():
            if not push_map:
                continue
            exports = []
            for src_loc, destination_locs in push_map.items():
                src_partition = self.node_to_partition_matrix[src_loc, :]
                destination_vec = sum(self.node_to_partition_matrix[dst] for dst in destination_locs)
                has_exports = self._project_to_bool(
                    cvxpy.sum(cvxpy.maximum(destination_vec - src_partition * self.num_nodes, 0)))
                # has_exports && src_partition
                exports.append(cvxpy.maximum(has_exports + src_partition - 1, 0))

            total_movement = functools.reduce(operator.add, exports)
            for src in nodes_with_external_outputs[tp]:
                total_movement += self.node_to_partition_matrix[self.node_to_loc_map[src], :]
            self._add_constraint(total_movement <= output_constraints[tp])
Пример #18
0
    def test_parallel_vs_serial_learning(self):
        """Test parallel VS serial learning"""

        # Generate data
        np.random.seed(1)
        T = 5
        M = 2.
        h = 1.
        c = 1.
        p = 1.
        x_init = 2.
        radius = 2.
        n_train = 1000  # Number of samples

        # Define problem
        x = cp.Variable(T + 1)
        u = cp.Variable(T)

        # Define parameter and sampling points
        d = cp.Parameter(T, nonneg=True, name="d")
        d_bar = 3. * np.ones(T)
        X_d = uniform_sphere_sample(d_bar, radius, n=n_train)
        df = pd.DataFrame({'d': list(X_d)})

        # Constaints
        constraints = [x[0] == x_init]
        for t in range(T):
            constraints += [x[t + 1] == x[t] + u[t] - d[t]]
        constraints += [u >= 0, u <= M]

        # Objective
        cost = cp.sum(cp.maximum(h * x, -p * x)) + c * cp.sum(u)

        # Define problem
        cvxpy_problem = cp.Problem(cp.Minimize(cost), constraints)
        problem = Problem(cvxpy_problem)

        # Solve for all theta in serial
        results_serial = problem.solve_parametric(df, parallel=False)

        # Solve for all theta in parallel
        results_parallel = problem.solve_parametric(df, parallel=True)

        # Assert all results match
        for i in range(n_train):
            serial = results_serial[i]
            parallel = results_parallel[i]

            # Compare x
            npt.assert_array_almost_equal(serial['x'],
                                          parallel['x'],
                                          decimal=TOL)
            # Compare cost
            npt.assert_array_almost_equal(serial['cost'],
                                          parallel['cost'],
                                          decimal=TOL)

            # Compare strategy
            self.assertTrue(serial['strategy'] == parallel['strategy'])
Пример #19
0
    def _stamp_preference_constraints(self,
                                      X,
                                      x_sensitive,
                                      w,
                                      cons_type,
                                      s_val_to_cons_sum=None):
        """
            No need to pass s_val_to_cons_sum for preferred treatment (envy free) constraints
            # 1 - pref imp, 2 - EF, 3 - pref imp & EF
        """

        assert cons_type in self.VALID_PREFERED_CONSTRAINTS
        assert cons_type == self.CONSTRAINT_PREFERED_TREATMENT or s_val_to_cons_sum is not None
        assert set(x_sensitive) == w.keys()

        group_labels = set(x_sensitive)
        prod_dict = {}
        for z in group_labels:
            idx = x_sensitive == z
            Xz = X[idx, :]
            nz = float(Xz.shape[0])
            if self.sparse_formulation:
                Uz, mz = np.unique(
                    Xz, axis=0
                )  #dropping duplicates so that we have fewer constraints
                Tz = Uz * mz[:, np.newaxis]
                prod_dict[z] = {
                    o: cp.sum(cp.pos(Tz * wo)) / nz
                    for o, wo in w.items()
                }
            else:
                prod_dict[z] = {
                    o: cp.sum(cp.maximum(0.0, Xz * wo)) / nz
                    for o, wo in w.items()
                }

        constraints = []
        if cons_type == self.CONSTRAINT_PREFERED_IMPACT:
            for z in group_labels:
                constraints.append(prod_dict[z][z] >= s_val_to_cons_sum[z][z])

        elif cons_type == self.CONSTRAINT_PREFERED_TREATMENT:
            for z in group_labels:
                other_groups = set(group_labels) - {z}
                for o in other_groups:
                    constraints.append(prod_dict[z][z] >= prod_dict[z][o])

        elif cons_type == self.CONSTRAINT_PREFERED_BOTH:
            for z in group_labels:
                constraints.append(prod_dict[z][z] >=
                                   s_val_to_cons_sum[z][z])  #preferred impact
                other_groups = set(group_labels) - {z}
                for o in other_groups:
                    constraints.append(prod_dict[z][z] >= prod_dict[z][o])

        return constraints
Пример #20
0
 def _init_edge_deps(self):
     filtered_edges = [edge for edge in self.edges if
                       self._is_internal_node(edge.src) and self._is_internal_node(edge.dst)]
     for src, dst, _, _ in filtered_edges:
         # If either end is a retime node, then we make sure that it can't merge.
         twiddle = src in self.retime_nodes or dst in self.retime_nodes
         # self._add_constraint(
         #     self.node_partitions[self.node_to_loc_map[src]] + twiddle <= self.node_partitions[
         #         self.node_to_loc_map[dst]])
         self._add_pseudo_constraint(cvxpy.maximum(self.node_partitions[self.node_to_loc_map[src]] + twiddle - self.node_partitions[self.node_to_loc_map[dst]], 0))
Пример #21
0
    def setup_solver_cvx(self):
        c = self.constvars
        imagedims = c['imagedims']
        n_image = c['n_image']
        d_image = c['d_image']
        l_labels = c['l_labels']
        l_shm = c['l_shm']

        self.cvx_x = Variable(
            ('p', (l_shm, d_image, n_image)),
            ('q0', (n_image, )),
            ('q1', (l_labels, n_image)),
            ('q2', (l_labels, n_image)),
        )

        self.cvx_y = Variable(
            ('u1', (n_image, l_labels)),
            ('v', (n_image, l_shm)),
            ('misc', (n_image, )),
        )

        p, q0, q1, q2 = [cvxVariable(*a['shape']) for a in self.cvx_x.vars()]
        self.cvx_vars = p + [q0, q1, q2]

        fid_fun_dual = 0
        for i in range(n_image):
            for k in range(l_labels):
                fid_fun_dual += -1.0/c['b'][k]*(cvx.power(q2[k,i],2)/2 \
                             + cvx.maximum(q2[k,i]*c['b'][k]*c['f1'][i,k],
                                 q2[k,i]*c['b'][k]*c['f2'][i,k]))

        self.cvx_obj = cvx.Maximize(fid_fun_dual - cvx.sum(q0))

        div_op = sparse_div_op(imagedims)

        self.cvx_dual = True
        self.cvx_constr = []

        # u1_constr
        for i in range(n_image):
            self.cvx_constr.append(c['b'] * q0[i] - q1[:, i] >= 0)

        # v_constr
        for i in range(n_image):
            for k in range(l_shm):
                Yk = cvx.vec(c['Y'][:, k])
                self.cvx_constr.append(
                    Yk.T*(c['M'][k]*q2[:,i] + q1[:,i]) \
                        - cvxOp(div_op, p[k], i) == 0)

        # additional inequality constraints
        for i in range(n_image):
            self.cvx_constr.append(sum(cvx.sum_squares(p[k][:,i]) \
                                       for k in range(l_shm)) <= c['lbd']**2)
Пример #22
0
    def test_basic_maximum(self):
        x, y = cp.Variable(2)
        expr = cp.maximum(cp.ceil(x), cp.ceil(y))

        problem = cp.Problem(cp.Minimize(expr), [x >= 12, x <= 17, y >= 17.4])
        self.assertTrue(problem.is_dqcp())
        problem.solve(SOLVER, qcp=True)
        self.assertEqual(problem.objective.value, 18.0)
        self.assertLess(x.value, 17.1)
        self.assertGreater(x.value, 11.9)
        self.assertGreater(y.value, 17.3)
Пример #23
0
def get_cost(s):
    '''
    get total cost for a series of height differences given the corresponding cost function
    '''
    relu = lambda u: cp.maximum(0, u)
    fill_cost = lambda u: 2 * relu(u)**2 + 30 * relu(u)
    cut_cost = lambda u: 12 * relu(-u)**2 + relu(-u)

    fill_costs = np.vectorize(fill_cost)(s)
    cut_costs = np.vectorize(cut_cost)(s)
    return cp.sum(fill_costs + cut_costs)
Пример #24
0
    def test_basic_composition(self):
        x, y = cp.Variable(2)
        expr = cp.maximum(cp.ceil(cp.ceil(x)), cp.ceil(cp.ceil(y)))

        problem = cp.Problem(cp.Minimize(expr), [x >= 12, x <= 17, y >= 17.4])
        self.assertTrue(problem.is_dqcp())
        problem.solve(SOLVER, qcp=True)
        self.assertEqual(problem.objective.value, 18.0)
        self.assertLess(x.value, 17.1)
        self.assertGreater(x.value, 11.9)
        self.assertGreater(y.value, 17.3)

        # This problem should have the same solution.
        expr = cp.maximum(cp.floor(cp.ceil(x)), cp.floor(cp.ceil(y)))
        problem = cp.Problem(cp.Minimize(expr), [x >= 12, x <= 17, y >= 17.4])
        self.assertTrue(problem.is_dqcp())
        problem.solve(SOLVER, qcp=True)
        self.assertEqual(problem.objective.value, 18.0)
        self.assertLess(x.value, 17.1)
        self.assertGreater(x.value, 11.9)
        self.assertGreater(y.value, 17.3)
Пример #25
0
    def solve_problem_min_cost_s_t_model(self, model, x, tol):
        x_t = cp.Variable(len(x))
        func_to_solve = cp.Minimize(self.cost_factor * (cp.maximum(
            (1 - self.epsilon) * self.a.T @ (x_t - x), 0) +
                                                        self.epsilon * cp.sum(
                                                            (x_t - x)**2)))
        constrains = [x_t @ model.coef_[0] >= -model.intercept_ + tol]

        prob = cp.Problem(func_to_solve, constrains)
        try:
            prob.solve()
            if x_t is None:
                print("couldn't solve this problem")
                return
            cost = cp.maximum((1 - self.epsilon) * self.a.T @ (x_t - x),
                              0) + self.epsilon * cp.sum((x_t - x)**2)
            cost *= self.cost_factor
            return x_t, cost
        except:
            print('solver faild')
            return x, None
Пример #26
0
 def _init_output_costs(self, cost: Cost, matrix: cvxpy.Variable,
                        loc_map: typing.Dict[Node,
                                             int], edge_type: EdgeType):
     # for each node, for count number of distinct out_ids that aren't in the same partition.
     edge_map = defaultdict(list)
     edge_srcs = {}
     for edge in (edge for edge in self.edges if edge.tp == edge_type):
         edge_map[edge.out_id].append(edge.dst)
         edge_srcs[edge.out_id] = edge.src
     movement = []
     for out_id in edge_srcs:
         src_node = self.id_to_node_lookup[edge_srcs[out_id]]
         if src_node not in loc_map:
             continue
         src_row = self._get_row_or_zeroes(matrix, loc_map, src_node)
         dst_nodes = [
             self.id_to_node_lookup[dst] for dst in edge_map[out_id]
         ]
         if any(node not in loc_map for node in dst_nodes):
             # if a node can't be in this partition type, then we have to export.
             movement.append(src_row)
         else:
             num_outputs = len(dst_nodes)
             matrix_sum = sum(
                 self._get_row_or_zeroes(matrix, loc_map, dst)
                 for dst in dst_nodes)
             num_out_of_partition_type_nodes = num_outputs - cvxpy.sum(
                 matrix_sum)
             out_of_partition_type_movement = self._project_to_bool(
                 num_out_of_partition_type_nodes, num_outputs)
             in_partition_type_movement = cvxpy.sum(
                 cvxpy.maximum(
                     self._project_to_bool(matrix_sum, self.num_nodes) -
                     src_row, 0))
             has_movement = self._project_to_bool(
                 out_of_partition_type_movement +
                 in_partition_type_movement, cost.value)
             movement.append(cvxpy.maximum(has_movement + src_row - 1, 0))
     if movement:
         self._add_constraint(sum(movement) <= cost.value)
Пример #27
0
def d():
    x = cp.Variable()
    y = cp.Variable()
    obj = cp.Minimize(0)
    constraints = [
            cp.norm(cp.vstack([cp.maximum(x, 1), cp.maximum(y, 2)])) <= 3 * x + y
            ]
    problem = cp.Problem(obj, constraints)
    print(f"d before: {problem.is_dcp()}")

    x = cp.Variable()
    y = cp.Variable()
    a = cp.Variable()
    b = cp.Variable()
    obj = cp.Minimize(0)
    constraints = [
            cp.norm(cp.vstack([a, b])) <= 3 * x + y,
            a >= cp.maximum(x, 1),
            b >= cp.maximum(y, 2),
            ]
    problem = cp.Problem(obj, constraints)
    print(f"d after: {problem.is_dcp()}")
    problem.solve()
Пример #28
0
def get_sensitive_attr_cov(dist_dict):

    """
    computes the ramp function for each group to estimate the acceptance rate
    """    

    s_val_to_cons_sum = {0:{}, 1:{}} # s_attr_group (0/1) -> w_group (0/1) -> ramp approx
    
    for s_val in dist_dict.keys():
        for w_group in dist_dict[s_val].keys():
            fx = dist_dict[s_val][w_group]            
            s_val_to_cons_sum[s_val][w_group] = cvx.sum( cvx.maximum(0, fx) ) / fx.shape[0]
            

    return s_val_to_cons_sum
Пример #29
0
    def test_maximum(self) -> None:
        x = cp.Variable(pos=True)
        y = cp.Variable(pos=True)
        a = cp.Parameter(value=0.5)
        b = cp.Parameter(pos=True, value=3.0)
        c = cp.Parameter(pos=True, value=1.0)
        d = cp.Parameter(pos=True, value=4.0)

        prod1 = x * y**a
        prod2 = b * x * y**a
        obj = cp.Minimize(cp.maximum(prod1, prod2))
        constr = [x == c, y == d]
        problem = cp.Problem(obj, constr)
        gradcheck(problem, gp=True, atol=1e-3)
        perturbcheck(problem, gp=True, atol=1e-3)
def offline_dynamic_provision_fixed_window(y):
  p = 0.4/2
  a = 4/2
  b = 4/2
  x = cp.Variable(4)
  cost = 0

  for i in range(1,4):
      cost += p*x[i] + a*cp.maximum(0, y[i-1] - x[i]) + b*cp.abs(x[i]-x[i-1])
  
  objective = cp.Minimize(cost)
  constraints = [x[0] == 0, x[1:] >= 0]
  problem = cp.Problem(objective, constraints)
  result = problem.solve()
  opt = np.array(x.value)
  opt = np.insert(opt, 0, 0., axis=0)
  
  return opt