Пример #1
0
    def __obj(self, λ):
        '''
        defines the objective function for section between A and B during the Trade-off analysis

        parameters:
        λ(float): a constant greater than 0
        '''

        if not ((isinstance(λ, float) or isinstance(λ, int)) and λ > 0):
            raise ValueError('λ must be a float and is > 0')

        self.objFunc = norm(self.Σ_p_sqrt * self.a,
                            2) + λ * norm(self.Σ_n_sqrt * self.a, 2)
        self.obj = cp.Minimize(self.objFunc)
Пример #2
0
def tv(value):
    """Total variation of a vector or matrix.

    Uses L1 norm of discrete gradients for vectors and
    L2 norm of discrete gradients for matrices.

    Parameters
    ----------
    value : Expression or numeric constant
        The value to take the total variation of.

    Returns
    -------
    Expression
        An Expression representing the total variation.
    """
    value = Expression.cast_to_const(value)
    rows, cols = value.size
    if value.is_scalar():
        raise ValueError("tv cannot take a scalar argument.")
    # L1 norm for vectors.
    elif value.is_vector():
        return norm(value[1:] - value[0:max(rows, cols) - 1], 1)
    # L2 norm for matrices.
    else:
        row_diff = value[0:rows - 1, 1:cols] - value[0:rows - 1, 0:cols - 1]
        col_diff = value[1:rows, 0:cols - 1] - value[0:rows - 1, 0:cols - 1]
        return sum_entries(norm2_elemwise(row_diff, col_diff))
Пример #3
0
def tv(value, *args):
    """Total variation of a vector, matrix, or list of matrices.

    Uses L1 norm of discrete gradients for vectors and
    L2 norm of discrete gradients for matrices.

    Parameters
    ----------
    value : Expression or numeric constant
        The value to take the total variation of.
    args : Matrix constants/expressions
        Additional matrices extending the third dimension of value.

    Returns
    -------
    Expression
        An Expression representing the total variation.
    """
    # Accept single list as argument.
    if isinstance(value, list) and len(args) == 0:
        args = value[1:]
        value = value[0]
    value = Expression.cast_to_const(value)
    rows, cols = value.size
    if value.is_scalar():
        raise ValueError("tv cannot take a scalar argument.")
    # L1 norm for vectors.
    elif value.is_vector():
        return norm(value[1:] - value[0:max(rows, cols)-1], 1)
    # L2 norm for matrices.
    else:
        args = list(map(Expression.cast_to_const, args))
        values = [value] + list(args)
        diffs = []
        for mat in values:
            diffs += [
                mat[0:rows-1, 1:cols] - mat[0:rows-1, 0:cols-1],
                mat[1:rows, 0:cols-1] - mat[0:rows-1, 0:cols-1],
            ]
        length = diffs[0].size[0]*diffs[1].size[1]
        stacked = vstack(*[reshape(diff, 1, length) for diff in diffs])
        return sum_entries(norm(stacked, p='fro', axis=0))
Пример #4
0
def tv(value, *args):
    """Total variation of a vector, matrix, or list of matrices.

    Uses L1 norm of discrete gradients for vectors and
    L2 norm of discrete gradients for matrices.

    Parameters
    ----------
    value : Expression or numeric constant
        The value to take the total variation of.
    args : Matrix constants/expressions
        Additional matrices extending the third dimension of value.

    Returns
    -------
    Expression
        An Expression representing the total variation.
    """
    # Accept single list as argument.
    if isinstance(value, list) and len(args) == 0:
        args = value[1:]
        value = value[0]
    value = Expression.cast_to_const(value)
    rows, cols = value.size
    if value.is_scalar():
        raise ValueError("tv cannot take a scalar argument.")
    # L1 norm for vectors.
    elif value.is_vector():
        return norm(value[1:] - value[0:max(rows, cols)-1], 1)
    # L2 norm for matrices.
    else:
        args = map(Expression.cast_to_const, args)
        values = [value] + list(args)
        diffs = []
        for mat in values:
            diffs += [
                mat[0:rows-1, 1:cols] - mat[0:rows-1, 0:cols-1],
                mat[1:rows, 0:cols-1] - mat[0:rows-1, 0:cols-1],
            ]
        length = diffs[0].size[0]*diffs[1].size[1]
        stacked = vstack(*[reshape(diff, 1, length) for diff in diffs])
        return sum_entries(norm(stacked, p='fro', axis=0))
Пример #5
0
def tv(value, *args):
    """Total variation of a vector, matrix, or list of matrices.

    Uses L1 norm of discrete gradients for vectors and
    L2 norm of discrete gradients for matrices.

    Parameters
    ----------
    value : Expression or numeric constant
        The value to take the total variation of.
    args : Matrix constants/expressions
        Additional matrices extending the third dimension of value.

    Returns
    -------
    Expression
        An Expression representing the total variation.
    """
    value = Expression.cast_to_const(value)
    if value.ndim == 0:
        raise ValueError("tv cannot take a scalar argument.")
    # L1 norm for vectors.
    elif value.ndim == 1:
        return norm(value[1:] - value[0:value.shape[0]-1], 1)
    # L2 norm for matrices.
    else:
        rows, cols = value.shape
        args = map(Expression.cast_to_const, args)
        values = [value] + list(args)
        diffs = []
        for mat in values:
            diffs += [
                mat[0:rows-1, 1:cols] - mat[0:rows-1, 0:cols-1],
                mat[1:rows, 0:cols-1] - mat[0:rows-1, 0:cols-1],
            ]
        length = diffs[0].shape[0]*diffs[1].shape[1]
        stacked = vstack([reshape(diff, (1, length)) for diff in diffs])
        return sum(norm(stacked, p=2, axis=0))
Пример #6
0
def mixed_norm(X, p=2, q=1):
    """Lp,q norm; :math:`(\\sum_k (\\sum_l \\lvert x_{k,l} \\rvert^p)^{q/p})^{1/q}`.

    Parameters
    ----------
    X : Expression or numeric constant
        The matrix to take the l_{p,q} norm of.
    p : int or str, optional
        The type of inner norm.
    q : int or str, optional
        The type of outer norm.

    Returns
    -------
    Expression
        An Expression representing the mixed norm.
    """
    X = Expression.cast_to_const(X)

    # inner norms
    vecnorms = norm(X, p, axis=1)
    # outer norm
    return norm(vecnorms, q)
Пример #7
0
def sum_squares(expr):
    """The sum of the squares of the entries.

    Parameters
    ----------
    expr: Expression
        The expression to take the sum of squares of.

    Returns
    -------
    Expression
        An expression representing the sum of squares.
    """
    return square(norm(expr, "fro"))
Пример #8
0
def mixed_norm(X, p=2, q=1):
    """Lp,q norm; :math:` (\sum_k (\sum_l \lvert x_{k,l} \rvert )^q/p)^{1/q}`.

    Parameters
    ----------
    X : Expression or numeric constant
        The matrix to take the l_{p,q} norm of.
    p : int or str, optional
        The type of inner norm.
    q : int or str, optional
        The type of outer norm.

    Returns
    -------
    Expression
        An Expression representing the mixed norm.
    """
    X = Expression.cast_to_const(X)

    # inner norms
    vecnorms = [norm(X[i, :], p) for i in range(X.size[0])]

    # outer norm
    return norm(hstack(*vecnorms), q)
Пример #9
0
def mixed_norm(X, p=2, q=1):
    """Lp,q norm; :math:` (\sum_k (\sum_l \lvert x_{k,l} \rvert )^q/p)^{1/q}`.

    Parameters
    ----------
    X : Expression or numeric constant
        The matrix to take the l_{p,q} norm of.
    p : int or str, optional
        The type of inner norm.
    q : int or str, optional
        The type of outer norm.

    Returns
    -------
    Expression
        An Expression representing the mixed norm.
    """
    X = Expression.cast_to_const(X)

    # inner norms
    vecnorms = [norm(X[i, :], p) for i in range(X.size[0])]

    # outer norm
    return norm(hstack(*vecnorms), q)
Пример #10
0
def tv(value, *args):
    """Total variation of a vector, matrix, or list of matrices.

    Uses L1 norm of discrete gradients for vectors and
    L2 norm of discrete gradients for matrices.

    Parameters
    ----------
    value : Expression or numeric constant
        The value to take the total variation of.
    args : Matrix constants/expressions
        Additional matrices extending the third dimension of value.

    Returns
    -------
    Expression
        An Expression representing the total variation.
    """
    value = Expression.cast_to_const(value)
    rows, cols = value.size
    if value.is_scalar():
        raise ValueError("tv cannot take a scalar argument.")
    # L1 norm for vectors.
    elif value.is_vector():
        return norm(value[1:] - value[0:max(rows, cols)-1], 1)
    # L2 norm for matrices.
    else:
        args = list(map(Expression.cast_to_const, args))
        values = [value] + list(args)
        diffs = []
        for mat in values:
            diffs += [
                mat[0:rows-1, 1:cols] - mat[0:rows-1, 0:cols-1],
                mat[1:rows, 0:cols-1] - mat[0:rows-1, 0:cols-1],
            ]
        return sum_entries(norm2_elemwise(*diffs))
Пример #11
0
def tv(value, *args):
    """Total variation of a vector, matrix, or list of matrices.

    Uses L1 norm of discrete gradients for vectors and
    L2 norm of discrete gradients for matrices.

    Parameters
    ----------
    value : Expression or numeric constant
        The value to take the total variation of.
    args : Matrix constants/expressions
        Additional matrices extending the third dimension of value.

    Returns
    -------
    Expression
        An Expression representing the total variation.
    """
    value = Expression.cast_to_const(value)
    rows, cols = value.size
    if value.is_scalar():
        raise ValueError("tv cannot take a scalar argument.")
    # L1 norm for vectors.
    elif value.is_vector():
        return norm(value[1:] - value[0:max(rows, cols) - 1], 1)
    # L2 norm for matrices.
    else:
        args = map(Expression.cast_to_const, args)
        values = [value] + list(args)
        diffs = []
        for mat in values:
            diffs += [
                mat[0:rows - 1, 1:cols] - mat[0:rows - 1, 0:cols - 1],
                mat[1:rows, 0:cols - 1] - mat[0:rows - 1, 0:cols - 1],
            ]
        return sum_entries(norm2_elemwise(*diffs))
Пример #12
0
print(f"\n\nMatrix U: {U}")
print(f"Shape of U: {U.shape}.")

Q = deepcopy(U[:, 4:len(destination)])
print(f"\n\nMatrix Q: {Q}")
print(f"Shape of Q: {Q.shape}.")

# Solve SDP problem
A = cp.Variable(shape=(len(destination), len(destination)))
A_bar = Q.transpose() * A * Q

print(f"\n\nShape of A: {A.shape}.")
print(f"Shape of A_bar: {A_bar.shape}.")

objective = cp.Maximize(lambda_min(-A_bar))
constraint = [A * N == 0, norm(A) <= 10]

problem = cp.Problem(objective, constraint)
problem.solve()

gain_A = np.array(A.value).round(5)
# gain_A = np.matrix(A.value)

print(f"Status: {problem.status}. \n")
print(f"Optimal value: {problem.value}. \n")
print(f"Optimal variable: \n{gain_A}. \n")

print(f"Shape of gain_A: {gain_A.shape}")

gain_Ai = np.zeros((number_of_agent, number_of_agent, 2,
                    2))  # I try putting everything nice and neat
Пример #13
0
def col_norm(X, p=2):

    X = Expression.cast_to_const(X)
    vecnorms = [norm(X[:, i], p) for i in range(X.size[1])]
    return hstack(*vecnorms)
Пример #14
0
def col_norm(X, p=2):

    X = Expression.cast_to_const(X)
    vecnorms = [ norm(X[:, i], p) for i in range(X.size[1]) ]
    return hstack(*vecnorms)
Пример #15
0
def row_norm(X, p=2):

    X = Expression.cast_to_const(X)
    vecnorms = [ norm(X[i, :], p) for i in range(X.size[0]) ]
    return hstack(*vecnorms).T